PHP not able to pass JSON array to jQuery - php

Pardon me if I am making a silly mistake here... But I am little new to PHP...
I have been stuck at this for long time.
I have tried several methods but I am only able to pass ONe table row , not multiple rows
I've even tried with the following approach, but I landed with the same error.
http://www.electrictoolbox.com/json-data-jquery-php-mysql/
Here's what I am trying to do :
1) Make Ajax call using JQuery, to fetch data from server.
$.ajax({
url: 'test.php', //the script to call to get data
data: "",
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
//use "data"
}
2) fetch table data from MySql database, using PHP.
$result = mysql_query("SELECT username,characterType FROM usertable");
3) pass ALL of the rows as JSON data, back to the calling function.
//This works , Returns one row and I am able to get the result back at AJAX end
$array = mysql_fetch_row($result);
echo json_encode($array);
mysql_fetch_assoc($result) FAILS with the following error :
XML Parsing Error: no element found Location: moz-nullprincipal:{6b1***-****somecrap numbers****-***86} Line Number 17, Column 3:
$array = mysql_fetch_assoc($result);
echo json_encode($array);
I have even tried using mysql_fetch_array($result, MYSQL_NUM) as suggested in the other relevant questions, but I am not able to workaround the problem.
Any Help is greatly appreciated.
============
UPDATE:
I may be wrong but just wanted to know, if this could be the possibility or not... Can this be a local setup related issue ? A Configuration mistake .. ?
I have done my localhost setup using "XAMPP installation" [ Apache / MySQL / Tomcat ... bundled in one package ] ...
When I run the file as "PHP application" it runs just fine ... I am able get "all rows" But when I deploy the code on my apache servers it doesn't run ... The whole php file comes as a response , with "XML parsing Error" [ I am using firebug to track the response ]
Thanks
Pranav

A few things to note here:
As Rup mentioned, $array = mysql_fetch_row($result); only returns a single row.
The other thing is that test.php does not currently return a JSON object; to see whats going on, it helps to comment out dataType: 'json', and use console.log(data); to see what is being returned. Your response probably looks something like this:
["someUsername","someChartype"]
The format of the object you are expecting is probably something more like:
[{"username":"foo","chartype":"admin"},
{"username":"bar","chartype":"user"},
{"username":"fum","chartype":"guest"}]
To get the format of the associative array, use mysql_fetch_assoc($result) instead; that will give
{"username":"someUsername","chracterType":"someChartype"}
To summarize, update your php code to:
Loop through your results, pushing them onto an array.
Encode the entire array at the end
$outputArray = array();
while( $row = mysql_fetch_assoc( $result ) ){
array_push($outputArray, $row);
}
echo json_encode($outputArray);
Take a look at How to build a JSON array from mysql database for more info. Also, as one of the answers mention, its worth using PDO rather than mysql_*

Don't start manually composing a JSON string as #Tuanderful indicated. Let json_encode() handle that -- just give it the right data. Try something like this:
$records = array();
while ( $record = mysql_fetch_assoc( $result ) ) {
$records[] = $record;
}
echo json_encode( $records );

Well I would to like this:
$.ajax({
url: 'test.php', //the script to call to get data
//data: "",
dataType: 'json', //data format
success: somevar
})
var somevar = function(data) //on recieve of reply
{
//use "data"
somevar2 = jQuery.parseJSON(data)
//now You can enter each row/cell from db(/php) like this
// somevar2[0] would be the first row from php
//if You want to do something with every line You can use:
//$.each(somevar2, function(key,value){
//$('#divname').html(value.cellnameoftable)
}
I hope it will help ;)

Related

Create a list in PHP from a DB call

I need to create this list (in javascript):
var videoList = ['GACS1.mp4','GACS4.mp4'];
From a call to the DB. So within the DB I have a field that I am calling to to get those mp4's back.
Here is the function.php, it is really just an Ajax page that processes the request.
function assignedvideos()
{
global $db_name, $path;
$uid = $_GET['uid'];
$selectedvideos = ORM::for_table('movies1')->raw_query('SELECT B.ID AS bid, B.*, LX.* FROM movies1 LX JOIN movies B ON LX.movieid = B.id JOIN locations L ON LX.locationid = L.id JOIN tablets T ON LX.locationid = T.tabletlocation WHERE T.uniqueid =".uid." ORDER BY LX.order ASC')->find_many();
if($selectedvideos)
{
foreach ($selectedvideos as $row)
{
$row['movielocation'] = stripslashes($row['movielocation']);
$row['moviename'] = stripslashes($row['moviename']);
}
}
die();
}
And ofcourse here is the call to the ajax page to retrieve the function.php page to retrieve the values.
$something = $_GET['uid'];
jQuery.ajax({
url: 'function.php',
type: "POST",
data: 'action=assignedvideos&uid='+$something,
success: function (response) {
},
error: function (response) {
}
});
The question is does this get built in the AJAX and sent back as a string and if so how?
Or does the AJAX return the list of variables and I build the list within the success response of the AJAX call? If so, then how?
To make it easy on yourself, put whatever values you want to send back to the client into a variable, and then call
echo json_encode($somevar);
in your case, there is an additional problem,
foreach ($selectedvideos as $row)
{
$row['movielocation'] = stripslashes($row['movielocation']);
$row['moviename'] = stripslashes($row['moviename']);
}
$row is replaced on each iteration of the loop with new data from the next row in $slectedvideos, so your operation basically does nothing, after the foreach $row will contain the last row of data from $selectedvideos. (also, $row will not modify $selectedvideos). if you wanted to modify $selectedvideos, there's a number of ways to do that, but without changing your code too much, you could do
foreach ($selectedvideos as $key => $row)
{
$selectedvideos[$key]['movielocation'] = stripslashes($row['movielocation']);
$selectedvideos[$key]['moviename'] = stripslashes($row['moviename']);
}
and then
echo json_encode($selectedvideos);
which you can then convert to a javascript object in the success call using JSON.parse()
Note that in this case, the javascript object won't look exactly how you want your data to look, instead it will be an array of objects such that array[0].movielocation will be (if I'm not mistaken) the file location of the first movie etc.
If you want it to be exactly an array of file paths, the foreach loop could look like this:
$output = array();
foreach ($selectedvideos as $row)
{
$output[] = stripslashes($row['movielocation']);
}
echo json_encode($output);
Note also that using stripslashes on the file location will force you to either put all the videos in the same folder on the server or use mod_rewrite in some shape or form.

Get Json From php file

I am new to jQuery. I have got an error when I try to get data from fileresult.php.
fileresult.php
$return_arr = array();
$row_array['status'] = 'Ok';
$row_array['message'] = 'good'
array_push($return_arr, $row_array);
echo json_encode($return_arr);
JSON output
[{"date":"2014-03-15","status":"ok","message":"good"}]
get_result.js
$.post('file.php', $("form").serialize(), function(data) {
var status = data['status'];
alert(status);
});
When I alert data, it shows undefined. Somebody please help me. How can I show the correct data.
You have two problems.
You are outputting "HTML"
PHP defaults to claiming that its output is HTML. jQuery will see this claim and treat it as such instead of parsing it as JSON.
Override PHP's default with:
header("Content-Type: application/json");
You have an array
You are accessing data.status but the top level data structure you are outputting is an array so you need data[0].status with that data.
You don't have multiple objects though, so (unless you plan to add more in the future) it would make more sense to return
{"date":"2014-03-15","status":"ok","message":"good"}
instead of
[{"date":"2014-03-15","status":"ok","message":"good"}]
So remove everything to do with $return_arr and:
echo json_encode($row_array);

AJAX enabled web form

I am new to Jquery and want some help from you guys.
i want to decode json data in jquery as i am able to pass data from php to ajax but after it came back in jquery it is not parsing it says undefined. the code is bellow
JavaSript file
$.post("GetData.php", function(data) {
if(data==false)
var tpl = '<p>no record found<p>'
else
var tpl = DrawTableRowsforSection(data);
$("#result").append($(tpl));
},"json");
function DrawTableRowsforSection(p)
{
alert(p.id[0]);
var o = '<table>';
for (var i = 0; i < p.length; i++)
alert(p.id[i]);
o += '<tr><td>'+p.id[i]+'</td><td>'+p.section_name[i]+'<td></tr>';
o+='</table>'
return O;
}
PHP Script
header('Content-Type: application/json');
mysql_connect('localhost','root','') ;
mysql_select_db('news');
session_start();
$query = 'select id,section_name from section';
if ($result = mysql_query($query)) {
if (!mysql_num_rows($result)==null) {
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$id = ToSring($row['id']);
$myArray[] = $row;
}
echo json_encode($myArray);
}
}
The database has a table named section
fields are as follows
id int(11)
section_name varchar(20)
There are total 5 records there.
What I want is to populate a table using returned data.
Can any one guide me where I am making mistake
Regards
Kashif Afzaal
Be sure that mysql returns results and you can take them through ajax.
Also, I've seen the following mistake:
You are using the variable tpl wrong. It is just a js variable, no need to use $ .
Use this way:
$("#result").append(tpl);
OK, from the top in the PHP script:
The MySQL extension is ancient and decrepit. Use MySQLi or PDO.
You never handle a failed MySQL query, so the response will quite possibly be empty. In 99% of cases, any if block should have a corresponding else block.
The result of mysql_num_rows() is never null. Do if (mysql_num_rows($result) > 0), or better yet, just if (mysql_num_rows($result)).
Never do if (!something == something) - it rarely does what you want it to. Do if (something != something)
You never handle mysql_num_rows() failing/giving no rows, so (again) the response will quite possibly be empty.
You never do anything with the $id variable you create.
I'm pretty sure ToSring should read ToString. But there's actually no such function in PHP - you would have either define it or invoke it as a method of a class/object. Indeed, this is likely to be the problem, as it will result in a fatal error.

Decoding JSON Array of Objects in PHP, is it the back slashes?

So I'm posting an array of objects in a JSON string using javascript to a PHP script and I'm having real problems decoding it in the php.
My javascript is as follows:
$.ajax({
type: 'POST',
url: "question_save.php",
data: {myJson: JSON.stringify(jsonArray)},
success: function(data){
alert(data);
}
});
The string sent to the PHP looks like this:
[{"content":"Question text"},{"answerContent":"Some answer text","score":"234","responseChecked":0,"responseContent":""},{"answerContent":"","score":"0","responseChecked":0,"responseContent":""}]
If I echo $_POST['myJson'] I get this:
[{\"content\":\"Question text\"},{\"answerContent\":\"Some answer text\",\"score\":\"234\",\"responseChecked\":0,\"responseContent\":\"\"},{\"answerContent\":\"\",\"score\":\"0\",\"responseChecked\":0,\"responseContent\":\"\"}]
Yet when I want to decode the JSON and loop through it like this...
$json = $_POST['myJson'];
$data = json_decode($json, true);
foreach ($data as &$value) {
echo("Hi there");
}
...I get this error:
Warning: Invalid argument supplied for foreach() in /home/thecrime/public_html/test1/question_save.php on line 15
I really don't understand what silly mistake I'm making, is it something to do with the back slashes?
Any help much appreciated!
Thanks,
-Ben
Use stripslashes ( $string ) - http://php.net/manual/en/function.stripslashes.php
This should work
$json = $_POST['myJson'];
$json_string = stripslashes($json)
$data = json_decode($json_string, true);
// simple debug
echo "<pre>";
print_r($data);
However, as already pointed by the others, it's better to disable magic_quotes_gpc.
Open your php.ini file and search for this row:
magic_quotes_gpc = On
Set it to Off and restart the server.
This has to do with Magic Quotes
Is better to disable this annoying old feature and forget those problems.
You can disabled following these instructions.

JQuery.getJson isn't triggered properly

I am trying to use JSON for getting dynamic content to my webpage, using javascript. Something is not correct and I have problem figuring out what it can be. In firebug I can see that the JSON-data is retreived as it should. When looking in Firebug under "DOM", the URL I am accessing for the page (the actual page I have created, not the URL to JSON-data) is coloured red (see screenshot below). Here is my javascript:
$(document).ready(function() {
$('#target').click(function() {
alert("At least I',m reached ");
$.getJSON('http://localhost/timereporting/phpscriptlibrary/get_remaining_hours.php', function(data) {
document.getElementById('errorDiv').innerHTML = "Divtext";
alert("Inside getJason");
});
alert("At least I',m done ");
});
This is the significant part of my php file:
$json_string = "{\"activities\": ";
$json_string = $json_string."[";
for ( $counter = 0; $counter < $num; $counter += 1) {
$json_string = $json_string."[".mysql_result($rows,$counter,'date').", \"".mysql_result($rows,$counter,'activity_id')."\", ".mysql_result($rows,$counter,'hours')."]";
if($counter != ($num-1)){
$json_string = $json_string.", ";
}
}
$json_string = $json_string."]}";
echo $json_string;
I assume that "echo" is the way to "send" the JSON-data to the javascript?
One strange thing is that in firebug the JSON-data is presented in two different ways. If you look at the included screenshots below, the second one has dates like "1988" or similar while on the first one the dates are more complete like "2010-12-10". The first screenshot depicts how it should be and that's how I am trying to send it, and obviously it is received like this at some point.
How come my div-tag isn't updated with the date or that the alert inside the $.getJSON isn't triggered, only the alert before and after?
You don't create your JSON strings properly. Every string has to be enclosed in double quotes. But 2010-12-10 is not and jQuery evaluates this as 2010 - 12 - 10 = 1988.
Don't build your string manually, use json_encode, something like:
$data = array();
while(($row = mysql_fetch_array($result))) {
$data[] = array($row['date'], intval($row['activity_id']), intval($row['hours']));
}
echo json_encode(array('activities' => $data));

Categories