jQuery Ajax to grab specific PHP variable
What i'm trying to do is create a dashboard with jQuery ajax calls to a PHP page to populate fields on the dashboard. I've done lots of ajax with jquery in the past but i'm struggling to get my head around this problem.
My desired HTML:
<div id="phase1">
</div>
<div id="phase2">
</div>
<div id="phase3">
</div>
In my PHP page i have 3 variables - $phase1, $phase2 and $phase3. I'd imagine using set开发者_开发百科Interval to keep it "live" to populate the 3 divs with their respective PHP variables. The bit i'm scratching my head about is how to tell the PHP page that i'd like to grab variable $phase1 from it and distinguish between the 3 variables so they fill the right divs. my php page is called db.php!
Can anyone think how i could construct such a ajax call...
In your ajax calls set a $_GET parameter and in your php if/elseif/else on it:
$.get("db.php?phase=1", function(data){ alert("Data Loaded: " + data); });
$.get("db.php?phase=2", function(data){ alert("Data Loaded: " + data); });
$.get("db.php?phase=3", function(data){ alert("Data Loaded: " + data); });
PHP:
switch($_GET['phase']) {
case '1':
//do code and echo
break;
case'2':
//do code and echo
break
case '3':
//do code and echo
break;
}
Not being a jQuery person at all I may be wrong here but here goes:
Isn't it impossible to read PHP variables once the page has been sent? AFAIK those variables only exist on the server while the script is running, to access them you would have to output them somehow.
As hidden fields...
<input type="hidden" name="phase1" value="<?php echo $phase1; ?>" />
Or XML
<phases>
<phase1><?php echo $phase1; ?></phase1>
</phases>
Or something else...
精彩评论