I am having trouble to solve a simple ajax function
I want to send php variables with ajax to another page if the user click on a link
Javascript
function sendData(a, b, c, d)
{
$.ajax({
url: "page.php",
type: "POST",
data: {"a": a, "b": b, "c": c, "d": d},
success:function(data) {
console.log(data);
document.location.href="page.php";
},
error:function(jqXHR,error_string,error){
console.log(error);
}
});
}
<button onClick="sendData(<?php echo $a ?>, <?php echo $b ?>, <?php echo $c ?>, <?php echo $d ?>)"> click </button>
<button onClick="sendData('<?php echo $a ?>', '<?php echo $b ?>', '<?php echo $c ?>', '<?php echo $d ?>')"> click </button>
you forgot single quotation
document.location.href="page.php";
the code above will redirect to page.php
after getting a success ajax response, you won't get any data from previous ajax request in a new page(new GET request).
The ajax request already done and print it's response to console, and the new request is a GET request without data, so you will got an empty array(print_r($_POST)) in page.php
.
A simple way to see what response you got, just comment or delete the code above, and then check ajax response in console.
If you want to pass data to other pages, you can store data into session
, and then retrieve it from session in the other page.
PS: It is very helpful to turn on your browser development tools(such as google chrome Network
).