I am working on a project that sends a ajax post request to a php file and then sets a php variable and returns the variable in js. That all works fine. What I am struggling with is being able call $name in the index.php file once getPhpVar() function has run.
This is what the program is supposed to do: 1.run getPhpVar() function 2.sends ajax post to get.php 3. get.php set name variable 4. get.php sends name variable back through js 5. I am able to call name variable in php Code: index.php
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function getPhpVar(varname) {
$.post("get.php",
{
name: varname,
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
}
getPhpVar(11);
</script>
<?php echo $name;
?>
get.php:
<?php
if( $_REQUEST["name"] ) {
$name = $_REQUEST['name'];
echo $name;
}
?>
alert()not show the expected result? What does it show?<?php echo $name; ?>in index.php will always run before your ajax call. It runs on your server before the page is sent to user.alertis JavaScript. You have the value you got from the server, so that's the value you use. What exactly isn't working here?$namein response to the AJAX request. You've proven this by alerting the value. If you want to also put that value in a page element, you would do so in that JavaScript function. The answer below demonstrates this. You have everything you need. There is genuinely no problem here, the code is working.index.php2. Your server gets the request, and the PHP code executes immediately (that's yourecho $name) 3. After PHP is done, send result to client 4. Client browser executes Javascript code 5. At some point, the JavascriptgetPhpVarfunction executes 6. Send AJAX request to server @get.php7. PHP executes and sends back$name8. Javascript callback from client browser gets the response