Reputation: 1089
Usually I can get php variables from a different php file declared like this:
$myVar = 'hello';
require 'header.php'
So then in header.php I can use $myVar. But I cannot access a variable that I loaded with ajax in jquery. For example:
index.php:
<html>
<body>
<div id="myDiv"></div>
</body>
</html>
In a script I have:
$(#myDiv).load('newPage.php')
newPage.php :
$myLoadedVar = 'loaded var';
But then I cannot access $myLoadedVar from index.php, is it possible to do this or you cannot access php variables created with ajax ?
Upvotes: 0
Views: 381
Reputation: 343
PHP is a server-side language while JavaScript is a client-side language. The only way you can get PHP data into JavaScript is by outputting the data in some manner. If you want the full output, just echo it. If you want to load a bunch of simple PHP variables into JavaScript, you can add all the variables you need JS to know about into an array, and then json_encode
them.
$firstName = 'John';
$lastName = 'Doe';
$outputArray = array('firstName' => $firstName, 'lastName' => $lastName);
echo json_encode($outputArray);
Then when an ajax function can retrieve this data as an object and you can use result.firstName
in JavaScript.
Passing complex items is impossible though, such as those with database connections as properties.
Upvotes: 1