JavaScript cannot find JSON data from PHP json_encode - javascript

The idea here is to automatically load (or load at all) my index page with some products out of a MySQL database table.
Firstly, my PHP.
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
echo json_encode($itemsJSON);
}
This seems to be working great, and gives me two properly encoded JSON objects of my Item class.
{"name":"Slippers","quantity":"3","cost":"4.00"}
{"name":"Gloves","quantity":"5","cost":"9.00"}
My JavaScript looks like this(and many other similar variations)
$(document).ready(function () {
$.post( "productloader.php", function( data ) {
$( "#result" ).html( data );
});
});
I'm not sure why it is not working. I did not want to use $.getJSON() because there is no query string to work with, so I'd assume I would need $.post().
It seems like this is a pretty common issue, but I've not found a solution yet. Any help would be appreciated. Thank you.

You can't json_encode() each item separately. The data you're sending to the browser is not valid JSON, just many little chunks of valid JSON one after the other. Build an array inside your loop and then encode the whole thing. See also http://jsonlint.com/
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON[] = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
}
echo json_encode($itemsJSON);

In your method of AJAX, you're outputting multiple JSON strings while the js side is expecting 1 string (data). Try removing your for loop to just:
echo json_encode($items);

You are creating JSON for each row, so you are getting separate JSON objects for each row in front end.
You should put all row in to and array and create the JSON object outside the loop, and echo the encoded JSON string.
<?php
$allitem = $db->getRows('SELECT * FROM products');
$itemArr=array();
foreach($allitem as $item){
array_push( $itemArr , new Item($item->product_name, $item->product_quantity, $item->product_cost) );
}
echo json_encode($itemArr);
?>
or
$allitem = $db->getRows('SELECT * FROM products');
echo json_encode($allitem );

Related

Pull mySQL data via PHP into an array of Javascript objects

i am trying in pull my data from mySQL and convert it to a format I can then pass to google.maps API. I am thinking mySQL -> php -> javascript -> google.maps makes the most sense but am deffinitly open to other suggestions.
So far I have connected to and successfully queried my data into an array
<?php
//library of mysql functions including linkDB()
include('../sqlFunctions/sqlFunctions.php');
//Establish connection to database
if($link = linkDB()){
echo "connected to DB";
}
//set up a MySQL query. I am simply pulling geocoordinate ints, strings and boolean.
$sql = "SELECT title
,lat
,lng
,titleYou
,descriptionAre
,privacyRockstar
FROM shelters;";
if($results = $link->query($sql)){
echo "<p>Query succsessful.</p>";
}else{
echo "Query Failed";
}
//initialize an array to store data
$rows = array();
while ($data = $results->fetch_assoc()) {
$rows[] = $data;
echo "<br><br>Loop rotation: ";
var_dump($data);
}
echo "<br><p>The End of The Loop<p><br>";
var_dump($rows);
?>
Now I just need to convert this data into something usable I can pass to google.maps.
Before I was pulling JSON from a text file, which worked, but I want to flexibility and stability of a database. It was easy to parse into and array of Javascript Objects. Then I could just call the index and the property that I needed as you can see from this function I was using.
function setMarkers(){
for(i=0; i < jsonParsed.arrayOfObjs.length; i++){
//setting parameters to hand to google
var markerOptions = {
position : jsonParsed.arrayOfObjs[i].position,
map : mapCanvas,
description : jsonParsed.arrayOfObjs[i].title,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
};
//create marker
this ['marker' + i] = new google.maps.Marker(markerOptions);
}
}
Thank you for any light you can help shed on my issue.
It sounds like you already found your answer but I'll post for completeness.
Simply change your the var_dump($rows) line to json_encode($rows).
Read more about json_encode in the php docs.
You probably want to have two php files:
api.php file that emits Content-type: application/json
index.php file that emits Content-type: text/html and calls api.php
On the index page, you can make an AJAX call to your API endpoint and then use JSON.parse(response).

Using jQuery/Javascript to get value from PHP array

I've got a PHP array...
<?php
$tweets = array(
'1' => array(
"title" => "title",
"challenge" => "challenge",
"answer" => "answer",
"type" => "type",
"class" => "class",
),
/* .... */
)
?>
That I need to go fetch data from using AJAX and for the life of me, I can't get the data that I need.
What I've got right now is...
var challenge = 10;
var tweets = <?php echo json_encode($tweets); ?>;
$('.cur_race_title').html(tweets[challenge]['title']);
$('.cur_race_challenge').html(tweets[challenge]['challenge']).addClass(tweets[challenge]['class']);
$('.cur_race_answer').html(tweets[challenge]['answer']);
$('.tweet-submission').addClass(tweets[challenge]['type']);
(Note: the challenge number is a variable that changes)
Using PHP's json_encode, I get an array of all of the values in the PHP file (which is included earlier on the file) and then use the challenge ID to populate the data.
The downside is that this shows the data for the entire array - I'd like to only show the data for the single challenge defined by the ID above.
Any help would be greatly appreciated.
Thanks!
I wouldn't recommend generating JavaScript variables with PHP tags.
Use: http://api.jquery.com/jquery.getjson/
$.getJSON("myurl.php", function(JSON){
//do something
});
PHP Side: Returning JSON from PHP to JavaScript?
header('Content-type: application/json');
echo json_encode( $myArray[ $myId ] );

Debugging JSON Object Javascript

I am learning Javascript and have been following a tutorial on coding an autofill search box. I have got so far but am now stuck on parsing some JSON code. The JSON code is the result of a PHP SELECT from my database.
The JSON result looks like the below.
["Leeds","Leicester"]
According to JSONLint it is valid JSON code.
However when I run the snippet of code below I get a script 1014 Invalid Character at the jQuery.parseJSON line...................I know its something to do with the fact that my JSON code is not an object but cannot work out what to do. I even tried stringify on the data before parsing but that did not work either
................other code
$.get("No1PHPfile.php",{keyword:keyword})
.done(function(data) {
console.log(data);
var results=jQuery.parseJSON(data);
console.log(results);
...................other code
EDIT
Two sets of PHP Files
No. 1
<?php
require('..........sqldatabase.php');
require('.........selectdatabasecode.php');
if(!isset($_GET['keyword'])) {
die();
}
$keyword=$_GET['keyword'];
$data=searchForKeyword($keyword);
echo json_encode($data);
?>
No. 2
<?php
function getDbconnection() {
$db=new PDO(DB_DRIVER.":dbname=".DB_DATABASE.";host=".DB_SERVER.";charset=utf8",DB_USER,DB_PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $db;
}
function searchForKeyword($keyword) {
$db=getDbconnection();
$stmt=$db->prepare("SELECT stationlong FROM `station` WHERE stationlong LIKE ? ORDER BY stationlong ");
$keyword=$keyword.'%';
$stmt->bindParam(1,$keyword,PDO::PARAM_STR,100);
$isQueryOk=$stmt->execute();
$results=array();
if ($isQueryOk) {
$results=$stmt->fetchAll(PDO::FETCH_COLUMN);
} else {
trigger_error('Error Executing Staement.',E_USER_ERROR);
}
$db=null;
return $results;
}
?>
something like
$result = json_encode ($data_i_want_to_send);
header('Content-type: application/json');
echo $result;
may help
UPD
Yes. i'm sclerotic((
Try
$data=searchForKeyword($keyword);
$data=array ('data' => $data); // so you send OBJECT anyway
$data=json_encode($data);
header('Content-type: application/json');
echo $data;
and on client side
var results= data.data; // instead of jQuery.parseJSON(data);
It should help to avoid different "magic" differences how it interpret your data and it works for sure in my site.

PHP json_encode then getJSON issue in javascript

Sorry if this is still another thread on the subject but I am struggling since hours but could not find the solution.
I am trying to get data from a Mysql database, create a JSON with php, then parse this JSON in javascript.
Here is my json.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect". mysql_error());
mysql_select_db("people") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM nom");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":',json_encode($arr),'}';
/*
//The json object is :
{"users":[{"id":"1","prenom":"Alain","age":"23"},{"id":"2","prenom":"Bruno","age":"24"}]}
*/
?>
Then I try to parse it into java
<div id="placeholder6"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://localhost/json.php', function(data) {
var output="<ul>";
for (var i in data.users) {
output+="<li>" + data.users[i].id + " " + data.users[i].prenom + "--" + data.users[i].age+"</li>";
}
output+="</ul>";
document.getElementById("placeholder6").innerHTML=output;
});
</script>
when I replace localhost/json.php by the result in a file data.json, it works, when I open localhost/json.php with firefox, I can see the JSON table...so I do not know why it does not work with localhost/json.php.
Is my php code or javascript code wrong ?
Thanks in advance for your help !
Try this method
var users= data.users;
$.each(users,function(index,users){
console.log(users.prenom); /// and users.id etc
})
Try This in php
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$return = new stdClass();
$return ->users = $arr;
echo json_encode($return);
I think your web application server (like Apache or nginx) sends Content-Type: text/html by default or something of that sort for your json.php file. On the other hand, it looks like $.getJSON method requires a application/json content type field.
Try adding:
header("Content-Type: application/json");
to the top of the json.php file.
Edit - additional info:
I couldn't find in the original documentation of the $.getJSON method whether it, in fact, requires the specific Content-Type so I looked into the source code:
https://github.com/jquery/jquery/blob/1.7.1/src/ajax.js#L294
Here is the line of source code for jQuery 1.7.1 (which is the version you said that you use, I hope) for getJSON and as you can see, it calls jQuery.get with the last argument set to "json".
In turn, the jQuery.get documentation reveals that this argument means:
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
from: http://api.jquery.com/jQuery.get/
Thus, when you call $.getJSON("/url/to/file", ...) that first argument is expected to be a JSON. If you add the PHP code from the top of my answer, your web application server will mask the output of the php file as a JSON.

sending php array using ajax (no jQuery use) yields bad data at server

I'm trying to send php array data using ajax.
Maybe this is not the correct method, so if there is a better one, I will be happy to know.
Anyway, I do not want to use JQuery, but a pure ajax.
I convert the php array to a string (in order to create an array back in the destination php)
$aData = array(
"Function" => "runRequestedFunction",
"ReqFunctionName" => "Lomba",
"ReqFunctionData" => 74
);
$sendvar = "data=".serialize($aData);
Then I send it using ajax
cAjax = new XMLHttpRequest();
--- there is some code here for callback ---
cAjax.open("POST","doSomthing.php",true);
cAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
cAjax.send("<?php echo $sendvar; ?>");
The problem is that the string $sendvar contains double quote (") which break the data received in the doSomthing.php file.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$aData= $_POST;
echo "Postinput: "; print_r($aData);echo "</br>";
}
?>
The echo output the follow
Postinput: Array ( [data] => a:3:{s:8: )
This is because the string is
a:3:s:8:"Function";s:20:"runRequestedFunction";s:15:"ReqFunctionName";s:5:"Lomba";s:15:"ReqFunctionData";i:74;}
so the first double quote breaks the data.
Try using single quotes:
cAjax.send('<?php echo $sendvar; ?>');

Categories