javascript - AJAX sending variable to PHP not working -


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;?>'; // <--- not working 

how can make work? don't receive variable in php whether use or post methods.

you seem have 2 fundamental misunderstandings. 1 ajax, , other client side vs. server side code. latter more important.

server vs. client

essentially php , javascript totally agnostic each other. not run in parallel. in context, don't run on same machine (the php code runs on server, javascript on user's computer). communication each script can other via http.

it's test.php needs have code

<?php if(isset($_post['abc'])) { $test123 = 'worked'; } ?> 

as long test.php exists, should work, i'm thinking of standalone script.

using ajax

because of asynchronous nature of ajax , http dependency, can't rely on when ajax request complete or if complete. code depends on result of ajax call must done in ajax response callbacks.

that is, 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!');     } } 

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -