Load a variable from the PHP file using jQuery Ajax load ()


This question already has an answer here:

  • Jquery load() and PHP variables 6 answers

Assuming my example.php looks like this:

$variable = "I am a variable";

and on another page I have:

<div id="loadme"></div>

How can I get that variable to my div?

Can it be achieved by using .load()?

I can imagine could be something like this:

$('#loadme').load("example.php", $variable);

Am I even close?

You're close, you need to echo the variable in the PHP file -

$variable = "foo";
echo $variable;

Then load like this -


The content of #loadme will now be 'foo'.

EDIT: Based on the OP's comments -

Each echo containing a variable could be a div with an id, e.g.,

echo '<div id="foo">$variable</div>';

Then your load statement would look like this -

$('#loadme').load('example.php #foo');

Now #loadme would contain the variable echoed in that div. This is not an efficient plan if the variables are to be re-used by JavaScript/jQuery code.