Question

Changing the question because the context changed.

I want to post the value of a Javascript variable to another page in the server using Ajax to POST and PHP to receive.

My Javascript code on page1.js:

var data = "test data";
var url = "page2.php";
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        console.log(data);//this prints "test data" on my page1.js successfully
    }else{
    console.log(http.readyState); //this always shows different ready states
}
}

This is my "receiving" php code on page2.php:

if (isset($_POST)) {
  if (isset($_POST["data"])){
    echo "SUCCESS"; // I am only testing whether "data" was captured in the POST, for now.
  }
}

But it is not printing anything.

Was it helpful?

Solution

You can do that with following code;

$.get("page1.php", function(data) {
  var html = $('<div>',{html:data});
  var my_content = html.find("#div1").text();
  $("#div2").html(my_content);
});

Here is a working fiddle: http://jsfiddle.net/uKBL3/1/

Note: I have used jsfiddle json service for ajax simulation.

Second way: You can load page1.php in to a hidden div and read content from hidden div. By loading in to hiddendiv, your js codes will be triggered and dynamic content will be fetched. After that, you can read your data. Example:

$("#hidden_div").load("page2.php", function() {
    var html = $(this);
    var my_content = html.find("#div1").text();
    $("#div2").html(my_content);
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top