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()?
The DOMDocument::load() function is an inbuilt function in PHP which is used to load an XML document from a file. Parameters: This function accepts two parameters as mentioned above and described below: $filename: This parameter holds the path to the XML document.
The jQuery load() method is a simple, but powerful AJAX method. The load() method loads data from a server and puts the returned data into the selected element. Syntax: $(selector).load(URL,data,callback);
The Load() method in jQuery helps to load data from server and returned into selected element without loading the whole page. Syntax: $(selector). load(URL, data, callback);
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'];
You're misunderstanding how things work.
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?
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With