8

If I load a PHP page with Jquery .load(file.php), can the included file use the php variables that were defined on the page that called the load()?

1
  • 2
    Hi @user1091856 - welcome to SO. It is good practice to accept an answer if it works for you (not just this question but any four of your previous questions). cheers! Dec 12, 2011 at 20:47

6 Answers 6

19

No, you have to pass the variables you want to use to your file.php:

$('#yourdiv').load('file.php?var1=xyz&var2=xyz&var3=xyz');

And then you can GET those in your file.php:

$var1 = $_GET['var1'];
$var2 = $_GET['var2'];
$var3 = $_GET['var3'];

If there are a lot of variables then use the POST method:

$('#yourdiv').load('file.php', {var1:x, var2:y, var3:z})

And then get the variables in file.php:

$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
2
  • This works too...I would just replace the 'file.php?var1=xyz&var2=xyz&var3=xyz' with 'file.php?var1={$xyz}&var2={$xyz}&var3={$xyz}' if you are using variables populated from the current PHP file. Again, the whole line would have to be echoed from within PHP tags. Dec 12, 2011 at 19:57
  • I appreciate this method much better since it uses the native jQuery load function.
    – RCNeil
    Feb 11, 2013 at 21:16
14

You're misunderstanding how things work.

  • PHP runs before any browser response is issued to the client, and all code runs on the server. The variables declared in your PHP file are destroyed after all the PHP code has been run; they "vanish."
  • JavaScript runs after the browser response has begun, and all code runs on the client. By "loading" the output result of the PHP file, you won't get any access to PHP's variables, only the output.

If you want to transfer certain variables from PHP to JavaScript, you could dump some output into JSON in your PHP script, like so:

<?PHP
    header("Content-Type: application/json");

    $myVariable = "hello world";

    echo json_encode(array(array("myVariable" => $myVariable)));

    /* Output looks like this:
       [
           {
               "myVariable": "hello world"
           }
       ]
    */
?>

Your JavaScript/JSON should look something like this:

$.getJSON("test.php", function(result) {
    console.log(result[0].myVariable);
});

Does that make sense?

4
  • I like your clear explanation of why it won't work and that's wny I upvoted the answer. But your tip to generate JSON with plain unescaped echo statements is scary; that's why json_encode() exists. Dec 12, 2011 at 20:11
  • Right, my apologies. I was just trying to make it easy enough to understand. It's been a while since I've used PHP, and I haven't in the past had to serialize JSON from PHP, so my bad. Dec 12, 2011 at 21:11
  • Pretty sure I know the answer, but an associative call works with this too, right? console.log(result['myVariable']);?
    – Plummer
    Apr 29, 2013 at 13:11
  • Why are there TWO arrays and would I just separate multiple variables with a comma?
    – user1994804
    Jun 12, 2015 at 12:54
6

Yes, use the data parameter, see http://api.jquery.com/load/:

$('#someelement').load(
    "test.php", 
    {
        'key1': '<?php echo $value1; ?>',
        'key2': '<?php echo $value2; ?>'
    } 
);

The parameters are posted to the file test.php and are accessible as:

$_POST['key1']
$_POST['key2']
1
  • This is a clean solution, but keep in mind that if you want to use variables defined in the current PHP file, you have to swap out the values with PHP variables echoed from within PHP tags. Dec 12, 2011 at 19:59
0

You would have to pass those variables to the loaded PHP file through the .load function.

Example:

$("#objectID").load("test.php", { 'choices[]': ["{$choice1}", "{$choice2}"] } );

The variables defined in the current PHP file would become part of the Javascript that loads the new PHP file.

1
  • Of course this line would have to be echoed out from within PHP tags. Dec 12, 2011 at 19:56
0

variables scope in the PHP script loaded by JavaScript is different from the page that loaded the PHP script, so the answer is no.

but you can define global variables or use super global variables like ($_GET, $_POST, etc.) to get what you want.

3
  • You can define the variables passed by Javascript in the page dynamically using PHP. Dec 12, 2011 at 20:02
  • @WatermarkStudios variables passed by Javascript is different from what OP is asking: can the included file use the php variables that were defined on the page that called the load().
    – fardjad
    Dec 12, 2011 at 20:06
  • You can use them exactly how TK Kocheran described (although json_encode() is highly recommended). You're right that javascript can't directly access PHP variables because of the sequence of loading in the RESPONSE cycle, but adding a line of PHP to define a Javascript variable with the same value as the PHP variable isn't unheard of, nor is it bad practice unless that values of the PHP variables are sensitive. Using Session variables would probably be best if sensitive data is an issue. Dec 12, 2011 at 20:58
0

The second argument (params) of the JQuery load function should be an object or a callback function, but could also be an empty string. Depending on that, load does send post or get requests.

I had the idea to switch automatically between get and post, (for example if cookie set),because get is more fast and cache able, and post is more save.

Its worse to write the load function including the content inside the callback function twice than to write something like that:

//get
var url="cache_dir/my_bag.html";
var params="";
if(document.cookie){
  //post
  url="post.php";
  params="{my:bag}";
  }
$(selector).load(url,params,function(){
...

  });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.