var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("abc=123");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
<?php if(isset($_POST['abc'])) {
$test123 = 'worked';
}
?>
}}
var worked = '<?php echo $test123;?>'; // <--- this is not working
How can I make this work? I don't receive the variable in PHP whether I use get or post methods.
You seem to have two fundamental misunderstandings. One is about AJAX, and the other is about client side vs. server side code. The latter is more important.
Essentially PHP and JavaScript are totally agnostic to each other. They do not run in parallel. In this context, they don't even run on the same machine (the PHP code runs on your server, the JavaScript on the user's computer). The only communication each script can do with the other is via HTTP.
It's test.php
that needs to have the code
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
?>
As long as test.php
exists, this should work, but I'm thinking of it as a standalone script.
Because of the asynchronous nature of AJAX and its HTTP dependency, you can't rely on when an ajax request will complete or even if it will complete. That is to say that any code that depends on the result of an AJAX call must be done in the ajax response callbacks.
That is, you would do something like this:
//php
<?php if (isset($_POST['abc']) { echo json_encode(array('success' => true)); }
//JavaScript
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if (JSON.parse(xmlhttp.responseText).success) {
console.log('it worked!');
}
}
Additionally to what @Explosion Pills explained this means the php inside the ajax doesn't work as you expect.
At the place inside test.php put this:
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
echo $test123;
?>
Then in the code you have up there replace this:
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
?>
by:
var worked = xmlHttp.responseText;
and finally remove this last line:
var worked = '<?php echo $test123;?>';
And check out what happens.