I'm aware of the difference between the client side javascript and server side PHP and that it's necessary to send the javascript back to the server to be retrieved again but I'm not sure how to do this.
Assuming some trivial javascript code that a variable is created based on some dynamic client side activity from the user:
var teststring = some selection
How would I be able to send and use this teststring in PHP to echo its contents (possibly using ajax or something else) and is it possible to do this on the same PHP page that the javascript is operating on?
I've tried something like this in javascript:
$.ajax({
url: "originalpage.php",
type: "POST",
data: {
teststring
}
})
and in the originalpage.php which is the same page the js is operating on:
var_dump($_POST['teststring']);
Which outputs NULL. an echo returns nothing.
2 Answers 2
POST parameters require key name and key value, what you need is the following:
$.ajax({
url: "originalpage.php",
type: "POST",
data: {
'teststring': teststring
}
)};
4 Comments
Try this code, tested on my pc and all works ok. You can read the PHP response (the 'echo') only inside success or error.
$.ajax({
url: "originalpage.php",
type: "POST",
data: "teststring="+teststring,
success: function(response) {
alert(response);
}
});