PHP is a server side language, meaning that once it has sent its data to the browser, the PHP variables and data cannot be changed...
However, using AJAX, you can send another request to a PHP page and change data in the DOM based on the result.
Consider this:
var id = parent.location.hash.split('#')[1];;
$.ajax({
url: 'http://www.example.net/id.php',
dataType: 'JSON',
data: {id: id},
success: function(data){
// Do whatever you want with you JSON object
// The following will log what has been returned
console.log(data);
// If you want to update your id variable then simply do this
id = data.id;
// You can then change elements in the DOM that reflect what your PHP
// variable originally set
$('#id').text(id);
}
});
The following will include the $currentID
as it was sent when the page loaded... But, you can update this text using the above script.
<p>My current ID is: <span id="id">$currentID</span></p>
PLEASE NOTE: This will not update the PHP variable as once PHP has sent data to the browser, the script has terminated and it cannot be modified, nor can varibles be accessed. The above script will simply update the text in the HTML.
Server Side Scripting
You need to understand how server side scripting functions before you start programing PHP, it is pretty basic really:
- You send a request to
my.php
- This request goes to the server where PHP generates your HTML, it will write any variables you have specified into the HTML
- The data is then sent back as HTML, NOT PHP, to the browser, where you can use javascript to make changes to the DOM.
The bottom line is, once PHP has generated and sent your page data to the browser, nothing to do with PHP then exists on that page! It is pure HTML, or whatever other type of document it may be...
Another way to explain it is this:
Your server sees the PHP page as this:
echo "<p>My current ID is: <span id=\"id\">$currentID</span></p>";
Your browser (where javascript sees it), sees the page like this
<p>My current ID is: <span id="id">1</span></p>
There is no PHP variable to access, it simply does not exist!
See the following for more information:
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-difference-between-server-side-and-client-side-programming