Get JSON Array into another file via Ajax - javascript
I'm trying to add a JSON array from a separate file into another array in my main page via Ajax. For some reason my Ajax is not working, There are 4 arrays, I need to store each of them in separate arrays in my main page. This is what I got.
load file:
<?php
session_start();
if(!isset($_SESSION['usersId']))
{
header("Location: ../index.php");
exit();
}
else
{
include_once 'includes/dbh.inc.php';
}
$id = $_SESSION['userId'];
$dBname = "infosensor";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
$sql = "SELECT sensor1, sensor2, sensor3 FROM `$id`;";
$result = mysqli_query($conn, $sql);
$jsonsensor1 = array();
$jsonsensor2 = array();
$jsonsensor3 = array();
$jsonsensorsum = array();
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
$jsonsensor1[] = intval($row['sensor1'] * ($p = pow(10, 2))) / $p;
$jsonsensor2[] = intval($row['sensor2'] * ($p = pow(10, 2))) / $p;
$jsonsensor3[] = intval($row['sensor3'] * ($p = pow(10, 2))) / $p;
$jsonsensorsum[] = intval(($row['sensor1'] + $row['sensor2'] + $row['sensor3']) * ($p = pow(10, 2))) / $p;
}
}
echo json_encode($jsonsensor1);
echo json_encode($jsonsensor2);
echo json_encode($jsonsensor3);
echo json_encode($jsonsensorsum);
?>
Output from the load file:
[5,10,10.99,10.99,13,5,14.31,1,1,5,5,5,1,5,3,3,5,5,1,5,10.32,10.32,5,8,5,10,5,5,19,5,7.36,7.36,5,12.2,12.2,2.2,2.2,23.3,5,10.87,6.87,6.87,5,5,10,10,10,10,5,5,5,5,5,0,5,5]
[8,12.5,12.5,12.53,12.53,8,10.11,1,1,8,8,8,1,8,3,3,8,8,1,8,12.83,32.32,8,8,8,10,8.31,8,10,8,18.2,18.2,8,10.3,10.3,2.29,2.29,12.3,8,8.23,2.23,2.23,8,8,10,10,10,20,5,5,5,5,8,0,8,2]
[6,8.86,8.86,8.87,8.87,6,8.33,1,2,6,2,3,1,6,3,8,6,6,1,6,8.32,7.32,6,8,6,10,3.31,6,12,6,12.3,12.3,6,11.1,11.1,4.09,4.09,33.1,6,5.16,12.16,2.16,6,6,10,20,30,30,30,30,5,0,6,0,6,5]
[19,31.36,32.36,32.4,34.4,19,32.76,3,4,19,15,16,3,19,9,14,19,19,3,19,31.47,49.96,19,24,19,30,16.62,19,41,19,37.86,37.86,19,33.6,33.6,8.6,8.6,68.7,19,24.26,21.26,11.26,19,19,30,40,50,60,40,40,15,10,19,0,19,12]
What I tried in my main page:
$(document).ready(function(){
$.getJSON("loadchart.php", function(jsonsensor1){
var sensor1 = [$jsonsensor1];
var sensor2 = [$jsonsensor2];
var sensor3 = [$jsonsensor3];
var sensorsum = [$jsonsensorsum];
});
});
Don't use multiple encode/echo calls. This will just create invalid json. Instead put your data into a single container(an object or array) and encode echo that.
For instance using a normal array:
$data = [$jsonsensor1,$jsonsensor2,$jsonsensor3,$jsonsensorsum];
echo json_encode($data);
And on the front end access them accordingly
$.getJSON("loadchart.php", function(data){
//get the arrays based on what position you put them
//in the array in the backend
//change this if you end up using a different container,
//eg php associative array or object
var sensor1 = data[0];
var sensor2 = data[1];
//and so on
});
Replace this code :
echo json_encode($jsonsensor1);
echo json_encode($jsonsensor2);
echo json_encode($jsonsensor3);
echo json_encode($jsonsensorsum);
With this code :
$data=array("jsonsensor1"=>$jsonsensor1,"jsonsensor2"=>$jsonsensor2,"jsonsensor3"=>$jsonsensor3,"jsonsensorsum"=>$jsonsensorsum);
echo json_encode($data);
Related
using javascript for loop
I am trying to get the data from database and put it into js for loop here is the php part: $result = mysql_query("SELECT * FROM db"); $row = mysql_fetch_array($result); $array[] = $row['value']; here is the js part var days=<?php echo json_encode($row['value']);?>; for(var i=0;i<days.length;i++){ document.write("Number"+ days[i] +"<br>"); } When I try to echo the values, I can echo the array in the php part with no problem, but on the js part there is no error, just a blank page OK whole scenario has changed when viewed the page source now my code is : rows = array(); $result = mysql_query("SELECT * FROM db"); $i=1; while($row = mysql_fetch_array($result)) { $array[] = $row['value']; $i++; } var days=<?php echo json_encode($array);?>; for(var i=0;i<days.length;i++){ document.write("Number"+ days[i] +"<br>"); when I viewed the page source I can see the values var days=["8","11","18"]; Now the next step is to implement it into js graph code If I try the js code var days=<?php echo json_encode($array);?>; for(var i=0;i<days.length;i++){ document.write("Number"+ days[i] +"<br>"); on a seperate page alone it works, but when I put the code in dataPoints dataPoints: [ {y: var days=<?php echo json_encode($array);?>; for(var i=0;i<days.length;i++){ document.write(days[i] +"<br>"); };, label: "test"}, ] I get blank page with no error. and still see the values when I view the page source . var days=["8","11","18"];
your page is blank because php return not string json you can try: var days= JSON.parse("<?php echo json_encode($row);?>"); for(var i=0;i<days.length;i++){ document.write("Number"+ days[i] +"<br>"); } Or: php file: $result = mysql_query("SELECT * FROM db"); $row = mysql_fetch_array($result); return json_encode($row); js file: $.get("phpfile.php",function(rs){ var days = JSON.parse(rs); for(var i=0;i<days.length;i++){ document.write("Number"+ days[i] +"<br>"); } });
How to get a php array index and use it in javascript
I have a PHP script that returns a latitude and longitude from the database. Then I have a Javascript loop that loops according to the number of rows the PHP query returns and populate my data object with the logitude and latitude at a given index. The challenge now is - how do I get the index without hard coding it? PHP $DBhost = 'localhost'; $DBuser = 'root'; $DBpass = ''; $DBname = 'symptoms'; $con = mysqli_connect($DBhost, $DBuser, $DBpass) or die(mysql_error()); mysqli_select_db($con, $DBname); $query = mysqli_query($con, 'SELECT latitude,longitude FROM markers') or die(mysql_error()); $longArr = array(); $latArr = array(); $count = 0; while ($row = mysqli_fetch_array($query)) { $lat = $row['latitude']; $lon = $row['longitude']; $latArr[$count] = $lat; $longArr[$count] = $lon; ++$count; } JavaScript var latArr = []; var longArr = []; var markersD = []; var num = <?php echo $count ?>; for (var i = 0; i < num; i++) { var data = { lat: '<?php echo $latArr[1]?>', lon: '<?php echo $longArr[1]?>' } console.log(data); }
You have to create json object via php while($row = mysqli_fetch_array($query)) { $json[] = array('lat' => $row['latitude'], 'lon' => $row['longitude']); } $json_string = json_encode($json); === JS === var data = <?php echo json_string; ?>; console.log(data);
You can put all your coords in one array $coords = array(); while($row = mysqli_fetch_array($query)) { $coords[] = array( 'latitude' => $row['latitude'], 'longitude' => $row['longitude'], ) } and pass it to the js as a JSON object var data = <?php echo json_encode($coords) ?>; console.log(data); All data you need should be available in the javascript
Json working for certain vars but not for others
I've made a script that requests information via Json. For some variables this works just fine, for others it doesn't. When I use alert() for the variable neighbour1 it says the variable is undefined, when doing the same for the variables number and colour it works just fine. This is the request script: function getcolours() { var hr = new XMLHttpRequest(); hr.open("GET", "camp_map_script.php", true); hr.setRequestHeader("Content-type", "application/json"); hr.onreadystatechange = function () { if (hr.readyState == 4 && hr.status == 200) { var data = JSON.parse(hr.responseText); for (var obj in data) { number = data[obj].number; colour = data[obj].colour; neighbour1 = data[obj].n1; alert (neighbour1); window["colour" + number] = colour; var x = document.getElementsByClassName(number + ' ' + colour); x[0].style.display = "block"; } } } hr.send(null); } This is the php part: <?php include_once("../php_includes/check_login_status.php"); ?><?php $number = ""; $sql = "SELECT camp_id FROM users WHERE username='$log_username'"; $query = mysqli_query($connect, $sql); $row = mysqli_fetch_row($query); $campid = $row[0]; $sql = "SELECT players FROM campaigns WHERE id='$campid'"; $query = mysqli_query($connect, $sql); $row = mysqli_fetch_row($query); $players = $row[0]; $number = ($players*2)-1; $sql = "SELECT number, colour, player, n1, n2, n3, n4, n5, n6, n7, n8 FROM lands WHERE camp_id='$campid' ORDER BY number"; $query = $connect->query($sql); $jsonData = '{'; if ($query->num_rows > 0) { while($row = $query->fetch_assoc()) { $jsonData .= '"obj'.$row["number"].'":{"number":"'.$row["number"].'", "colour":"'.$row["colour"].'", "player":"'.$row["player"].'", "n1":"'.$row["n1"].'"},'; } } $jsonData = chop($jsonData, ","); $jsonData .= '}'; echo $jsonData; $connect->close(); ?> Also when I check the php document the variable n1 is echoed correctly. So the error must be on the java script side or the transit. It is probably something stupid that I'm overlooking but I just don't see it. I've copy pasted the working parts and changed them to work with other variables but it still doesn't work. :/
Why is my PHP array not posting as an array to JavaScript?
This is my first time building my own JavaScript code so not completely up to speed with it yet. I am querying my MySQL database to get all the disabled days so that the results are disabled in the date picker. I nearly have this working but the problem is that only one set of values is being posted to the JavaScript variable when there are two being read from the database. i.e if there are two bookings in my database, one from 6/3/15 - 10/3/15 and one from 14/3/15 - 17/3/15 only one is being stored in the JavaScript variable. i.e 6/3/15 - 10/3/15. When I echo the json_encode($date_list) i get the results as: ["2015-3-14","2015-3-15","2015-3-16","2015-3-17","2015-3-17"] ["2015-3-6","2015-3-7","2015-3-8","2015-3-9","2015-3-10","2015-3-10"] Which is correct but when I do a console.log on the bookedDays variable the only values stored are: ["2015-3-6", "2015-3-7", "2015-3-8", "2015-3-9", "2015-3-10", "2015-3-10"] Below is the code I am using. <?php $bookeddates = "SELECT fromdate, todate FROM messages WHERE listing_id = '".$_GET['listingid']."'"; $resultbookeddates = mysql_query($bookeddates) or die(mysql_error() . "<br>" . $bookeddates); while ($rowbookeddates = mysql_fetch_assoc($resultbookeddates)) { $from = date('Y-n-j', strtotime($rowbookeddates['fromdate'])); $to = date('Y-n-j', strtotime($rowbookeddates['todate'])); $start_time = strtotime($from); $end_time = strtotime($to); $date_list = array($from); $current_time = $start_time; while($current_time < $end_time) { //Add one day $current_time += 86400; $date_list[] = date('Y-n-j',$current_time); } $date_list[] = $to; ?> <script type="text/javascript"> var bookedDays = <?php echo json_encode($date_list); ?>; </script> <?php echo json_encode($date_list); } ?> Any help would be appreciated.
you need to move your injected JS outside of your while loop like this. As said in comments, build your data first, then output it. <?php $bookeddates = "SELECT fromdate, todate FROM messages WHERE listing_id = '".$_GET['listingid']."'"; $resultbookeddates = mysql_query($bookeddates) or die(mysql_error() . "<br>" . $bookeddates); $date_list = array(); while ($rowbookeddates = mysql_fetch_assoc($resultbookeddates)) { $from = date('Y-n-j', strtotime($rowbookeddates['fromdate'])); $to = date('Y-n-j', strtotime($rowbookeddates['todate'])); $start_time = strtotime($from); $end_time = strtotime($to); $date_list[] = $from; $current_time = $start_time; while($current_time < $end_time) { //Add one day $current_time += 86400; $date_list[] = date('Y-n-j',$current_time); } $date_list[] = $to; } ?> <script type="text/javascript"> var bookedDays = <?php echo json_encode($date_list); ?>; </script> <?php echo json_encode($date_list);
Your problem is the asigment of javascript variable. Please, move outside the while loop the asigment and you can see all results. <?php $bookeddates = "SELECT fromdate, todate FROM messages WHERE listing_id = '".$_GET['listingid']."'"; $resultbookeddates = mysql_query($bookeddates) or die(mysql_error() . "<br>" . $bookeddates); while ($rowbookeddates = mysql_fetch_assoc($resultbookeddates)) { $from = date('Y-n-j', strtotime($rowbookeddates['fromdate'])); $to = date('Y-n-j', strtotime($rowbookeddates['todate'])); $start_time = strtotime($from); $end_time = strtotime($to); $date_list = array($from); $current_time = $start_time; while($current_time < $end_time) { //Add one day $current_time += 86400; $date_list[] = date('Y-n-j',$current_time); } $date_list[] = $to; } ?> <script type="text/javascript"> var bookedDays = <?php echo json_encode($date_list); ?>; </script>
XML not parsing in jQuery
When I try to parse my PHP-generated XML file using the jQuery Feeds plugin, it doesn't do what it's supposed to - loop through the template below and output the XML <title> tag in the place of <!=title!>. Instead, it returns just one instance of the template with nothing in place of <!=title!>. Nothing is returned in the Chrome JavaScript console. Strangely, I have a similar PHP-generated XML file that works just fine. Here's the jQuery I'm using: $('.feed').feeds({ feeds: { feed1: 'http://www.comfyshoulderrest.com/scrape.php?id=1' // this one doesn't work }, //max: 3, loadingTemplate: '<h1 class="feeds-loader">Loading items...</h1>', entryTemplate: '<div class="item"><div class="image"><img src="images/tie.jpg" style="width: 100%;"></div>' + '<div class="text"><ul class="list-inline">' + '<li><span class="price text-warning"><strong>£7.00</strong></span> <span class="text-muted"><strike>£14.00</strike></span></li>' + '<li class="text-muted"><strong>Topman</strong></li></ul>' + '<!=title!>' + '</div></div>' }); Here's the code that generates the XML file: <?php function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country) { header("Content-Type: application/xml; charset=UTF-8"); $xml = new SimpleXMLElement('<rss/>'); $xml->addAttribute("version", "2.0"); $channel = $xml->addChild("channel"); $channel->addChild("product_url", $product_url); $channel->addChild("shop_name", $shop_name); $channel->addChild("photo_url", $photo_url); $channel->addChild("was_price", $was_price); $channel->addChild("now_price", $now_price); $html = file_get_contents($list_url); $doc = new DOMDocument(); libxml_use_internal_errors(TRUE); if(!empty($html)) { $doc->loadHTML($html); libxml_clear_errors(); // remove errors for yucky html $xpath = new DOMXPath($doc); /* FIND LINK TO PRODUCT PAGE */ $products = array(); $row = $xpath->query($product_location); /* Create an array containing products */ if ($row->length > 0) { foreach ($row as $location) { $product_urls[] = $product_url_root . $location->getAttribute('href'); } } $imgs = $xpath->query($photo_location); /* Create an array containing the image links */ if ($imgs->length > 0) { foreach ($imgs as $img) { $photo_url[] = $photo_url_root . $img->getAttribute('src'); } } $result = array(); /* Create an associative array containing all the above values */ foreach ($product_urls as $i => $product_url) { $result = array( 'product_url' => $product_url, 'shop_name' => $shop_name, 'photo_url' => $photo_url[$i] ); $item = $channel->addChild("item"); $item->addChild("product_url", $result['product_url']); $item->addChild("shop_name", $result['shop_name']); $item->addChild("photo_url", $result['photo_url']); } //print_r($result); } else { echo "this is empty"; } echo $xml->asXML(); } /* CONNECT TO DATABASE */ $dbhost = "xxx"; $dbname = "xxx"; $dbuser = "xxx"; $dbpass = "xxx"; $con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $id = $_GET['id']; /* GET FIELDS FROM DATABASE */ $result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'"); while($row = mysqli_fetch_array($result)) { $list_url = $row['list_url']; $shop_name = $row['shop_name']; $photo_location = $row['photo_location']; $photo_url_root = $row['photo_url_root']; $product_location = $row['product_location']; $product_url_root = $row['product_url_root']; $was_price_location - $row['was_price_location']; $now_price_location - $row['now_price_location']; $gender = $row['gender']; $country = $row['country']; scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country); } mysqli_close($con); ?>