Ivaldir Ivaldir - 1 year ago 37
Ajax Question

Getting a variable from PHP to javascript (echo not updating after PHP variables change)

I'm working on a script that forms a web page based on what is in my database. For his I call a java script function when the page loads and whenever the page needs to update.

Firstly I made a script that gets the information from the database, passes it to java script by

echo "var region_list = ". $js_region_list . ";\n";
and then proceeded to generate the page itself which worked.

After that I tried to get this to work based on an AJAX request but this failed horribly. As it stands I get correct information from the database but it does not change the value of
echo "var region_list = ". $js_region_list . ";\n";
which prevents the page from updating.

The PHP part of my script:

if(isset($_POST["campaign_id"])){
// Get variables and sanetize
$campaign_id = preg_replace('#[^0-9]#i', '', $campaign_id);

// Create planet list
$planet_list = array();
$sql = "SELECT planet_nr, size, moon FROM planets WHERE campaign_id = $campaign_id";
if ($result = mysqli_query($db_conx, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
array_push($planet_list, array($row["planet_nr"],$row["size"],$row["moon"]));
}
/* free result set */
mysqli_free_result($result);
}

// Create region list
$region_list = array();
$sql = "SELECT planet_id, region_id, region_type, owner FROM regions WHERE campaign_id = $campaign_id";
if ($result = mysqli_query($db_conx, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
array_push($region_list, array($row["planet_id"],$row["region_id"],$row["region_type"],$row["owner"]));
}
/* free result set */
mysqli_free_result($result);
}

// Convert array's for use in java
$js_planet_list = json_encode($planet_list);
$js_region_list = json_encode($region_list);

$list = array($planet_list, $region_list);
$list = json_encode($list);
echo $list;
exit();


The javascript part:

<?php
echo "var planet_list = ". $js_planet_list . ";\n";
echo "var region_list = ". $js_region_list . ";\n";
?>
var ajax = ajaxObj("POST", "campaign.php?c="+campaign_id);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "Fail"){
alert(ajax.responseText);
}
}
}
ajax.send("campaign_id="+campaign_id);


NOTE: These are just snippets of the whole script. The whole script is in the same PHP file with the PHP up above between it's tags and the java down between the script tags.

Answer Source

In your ajax success part, you need to just update the values of the the variables planet_list and region_list as shown below

planet_list = ajax.responseText[0];
region_list = ajax.responseText[1];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download