I need to get an array generated from a script php. I have Latitude and Longitude for each user in a database.
I take the values from the db with this code (file.php):
$query = "SELECT Latitude, Longitude FROM USERS";
$result=mysql_query($query);
$array=array();
while ($data = mysql_fetch_array($result)) {
$array[]=$data['Latitude'];
$array[]=$data['Longitude'];
}
echo $array;
and I call with ajax with this code:
$.post('./file.php',
function( result ){
alert(result);
});
but even if in the script php the array is correct (if I echo array[25] I obtain the right value) in Javascript I obtain "Undefined".
How can I get the array in correct way??
thanks!
edit: after encoded with json_encode($array); in php and JSON.parse(result) in javascript seems not working.
In the console I have the array, but I can't access to its values. (Array[0] gave me "undefined").
use this
echo json_encode($array);
on server side
and
var arr=JSON.parse(result);
on client side
As Ruslan Polutsygan mentioned, you cen use
echo json_encode($array);
on the PHP Side.
On the Javascript-Side you can simply add the DataType to the $.post()-Function:
$.post(
'./file.php',
function( result ){
console.log(result);
},
'json'
);
and the result-Parameter is the parsed JSON-Data.
You can also set the correct Content-Type in your PHP Script. Then jQuery should automaticly parse the JSON Data returned from your PHP Script:
header('Content-type: application/json');
See
http://api.jquery.com/jQuery.post/
http://de3.php.net/json_encode
You need to convert the php array to json, try:
echo json_encode($array);
jQuery should be able to see it's json being returned and create a javascript object out of it automatically.
$.post('./file.php', function(result)
{
$.each(result, function()
{
console.log(this.Latitude + ":" + this.Longitude);
});
});
Related
I assigned a JSON result from php to a javascript variable.
The result returned looks like below but it gives me undefined undefined
[{"a":"2","u":"jamesoduro","l":"Oduro","f":"James"},{"a":"5","u":"deary.grace","l":"Grace","f":"Dear"}]
I simple know this look like a javascript array with two objects.
I am trying to access the data inside the objects but to no avail.
Below is script:
PHP
<?php
//fetch online users
$array = array();
$sql = "SELECT id as a,username as u, lastname as l,firstname as f FROM users WHERE active =1 limit 2";
$q = mysqli_query($dbc_conn,$sql);
while($row = mysqli_fetch_assoc($q)){
$array[] = $row;
}
$json = json_encode($array);
echo $json;
?>
JQUERY
$(document).ready(function(){
//checking online users
setTimeout(function(){
$.ajax({
url:"testing.php",
type:"post",
success:function(response){
var array = response;
console.log(array[0].f +" "+ array[0].l);
}
});
},200);
});
Please what could be the problem?? Thank you
$.ajax({
url:"testing.php",
type:"post",
success:function(response){
var array = JSON.parse(response);
console.log(array[0].f +" "+ array[0].l);
}
});
You get a string from php , need turn the string into a json object .
You have to learn to debug your code to find what is going wrong I guess .
Try deserializing the response:
var array = JSON.parse(response);
EXPLANATION
The response you get from the ajax call is of type string, so you have to convert it to an object. That's what JSON.parse() method do: it parses the JSON string and creates the object that this string represent, following specific rules (The parsed string must be in a valid JSON format).
Keep your server side PHP script code neat and clean
Start PHP block from first character of first line.
Do not close php block if there is no output in HTML format.
Use ob_clean() function before echo output in is your are in developer mode and display error is enabled.
for example
ob_clean();
echo json_encode($array);
In client side, if you are getting JSON response in ajax, pass dataType:'json' in ajax option
$.ajax({
url:"testing.php",
type:"post",
dataType:"json",
success:function(response){
console.log(response[0].f +" "+ response[0].l);
}
});
I create JSON-data with the following php code:
if($res = $db->query('Select row1 from table1')){
while($row = $res->fetch_row()){
$json[] = $row;
}
}
sort ($json);
$json = json_encode($json);
echo $json;
The result is [["1"],["2"],["3"]].
When I try to fetch this data with jquery ajax
<div id="output">JSON will be put here</div>
<script language="javascript" type="text/javascript">
$(function () {
$.ajax({
url: 'json.php',
dataType: 'json',
data: '',
error: function(request,error) {
alert(error);
},
success: function(data) {
var json = data[0];
alert(json);
$('#output').html(json+", ");
}
});
});
it says: "parseerror".
I searched a lot (here at Stack Overflow), but my jQuery version seem to be right (1.7.2) and reformating the JSON-outpu did not help (I deleted the opening brackets and tried a lot of other things).
Any ideas?
Parse the data return in ajax result,
var retData= JSON.parse(data);
You should check if you get an object before using it:
if(typeof data != 'object')
data = $.parseJSON(data);
Sometime it is interpreted as a string and you have to convert it first
I don't think you need to push it in an array. Your query is already an array. SO try to only json_encode() and that alert the data what you get and try to access the data by using data.somevariable( at least that is how I access my json data in the ajax).
Hope it helps
Verify the content type of the response header (you can see this in any modern browser's network console). It needs to be coming back as application/json. Any other type may cause your Javascript to fail. Before echoing the JSON in your PHP file, try adding:
header('Content-Type: application/json');
This will explicitly and correctly set the response content type. Keep in mind, this in contingent upon your return string being valid JSON in the first place, which it seems to be.
Hi I'm working on passing back an array from php to javascript. I learned online that I should use json_encode on the array when passing it back but now that i have it in the ajax i'm unsure how i can loop over it because doing things like response[0] gives me [ and response[1] gives me " although when writing the entire thing to the document using innerHTML i can see it looks like an array but using a for loop gives me each letter like i stated above with the response[0] equaling [ rather than the first entry. What am i doing wrong? Any help is greatly appreciated!
PHP
<?PHP
$link = mysql_connect('localhost', 'root', 'root');
mysql_select_db("Colleges");
$result = mysql_query("SELECT * FROM `Colleges` ORDER BY School");
$schools = array();
while ($row = mysql_fetch_array($result)) {
array_push($schools, $row['School']);
}
mysql_close();
die(json_encode($schools));
?>
Ajax
<script type="text/javascript">
function schools(){
$.ajax({
url: "Schools.php",
type: "POST",
success: function (response) {
//Loop over response
}
});
}
</script>
You should decode your JSON response (which is a string actually) to be able to work with it as with an object:
var respObj = JSON.parse(response);
The other way around is noticing jQuery that JSON will be supplied by the server (with either dataType: 'json' ajax parameter or Content-Type: application/json response header).
In the object you pass to the ajax method, you should try to add dataType: 'json' in order to specify that the result is json, or you could specify it in your php script calling header('Content-type: application/json'); before the call to die();
Doing so will result in your response being the object you expect instead of a string.
Finally, you could leave it as is, and call in your success callback response = $.parseJSON(response); which will take the response string and turn it into an object, see http://api.jquery.com/jQuery.parseJSON/
Use Following if it helps
res=jQuery.parseJSON(response);
for(i=0;i<res.length;i++)
{
alert(res[i].propertyname);
}
here property name implies to the keys on json .In your case it can be 'School' or just a number i or value can also be just res[i]
Javascript
for ( variable in response ) {
alert(results[variable]);
}
JQuery
$.each(response, function(ind, val){
alert("index:" + ind + ". value:" + val);
});
I'm trying to communicate AJAX, JSON to PHP and then PHP returns some data and I'm trying to parse it with Javascrpt.
From the php, server I return,
echo json_encode($data);
// it outputs ["123","something","and more something"]
and then in client-side,
success : function(data){
//I want the data as following
// data[0] = 123
// data[1] = something
// data[3] = and more something
}
But, it gives as;
data[0] = [
data[1] = "
data[2] = 1
It is reading each character but I want strings from the array, not individual characters. What is happening here? Thanks in advance, I am new to Javascript and JSON, AJAX.
JSON.parse(data) should do the trick.
Set the dataType property of the ajax call to json. Then jQuery will automatically convert your response to object representation.
$.ajax({
url : ...,
data : ...,
dataType : "json",
success : function(json) {
console.log(json);
}
});
Another option is to set headers in PHP so that JQuery understand that you send a JSON object.
header("Content-Type: application/json");
echo json_encode($data);
Check this one... Should Work
success : function(data){
var result = data;
result=result.replace("[","");
result=result.replace("]","");
var arr = new Array();
arr=result.split(",")
alert(arr[0]); //123
alert(arr[1]); //something
alert(arr[2]); //......
}
You did not shown function in which you parse data. But you shoud use
JSON.parse
and if broser does not support JSON then use json polyfill from https://github.com/douglascrockford/JSON-js
dataArray = JSON.parse(dataFomXHR);
I'm not sure if this is what you want but why don't you want php to return it in this format:
{'item1':'123','item2':'something','item3':'and more something'}
Well to achieve this, you'll need to make sure the array you json_encode() is associative.
It should be in the form below
array("item1"=>123,"item2"=>"something","item3"=>"more something");
You could even go ahead to do a stripslashes() in the event that some of the values in the array could be URLs
You could then do a JSON.parse() on the JSON string and access the values
Hop this helps!
I am currently working on a php/javascript project which retrieves information from a database and json encodes the data. It is supposed to show the values from the database inside a combo box on the web page.
In the PHP script that encodes the mysql data I have the following code:
$query = "SELECT pla_platformName as `platform` FROM platforms";
$result = mysql_query($query);
if ($result)
{
while ($myrow = mysql_fetch_array($result))
{
$output[] = $myrow;
}
print json_encode($output);
die();
}
In the javascript code I have the following:
<script>
$(document).ready(function()
{
getPlatforms();
function getPlatforms()
{
$.post("phpHandler/get-platforms.php", function(json)
{
alert(json);
alert(json.platform);
}
);
}
});
</script>
I have alert(json); which shows the entire json data which looks like the following:
[{"0":"hello","platform":"hello"},{"0":"android","platform":"world"}]
The next alert(json.platform) I am expecting it to show either hello or world or both but on this line it keeps on saying undefined. Why isn't this working and how do I get a specific platform, i.e. either hello, or world.
Thanks for any help you can provide.
You need to first convert your JSON string into an object
var data = $.parseJSON(json);
In this case, the object returned is an array. Try
alert(data[0].platform);
You can skip the first step if you set the dataType option to json in your ajax call.
$.post("phpHandler/get-platforms.php", function(data) {
alert(data[0].platform);
},
'json'
);
See jQuery.post() documentation
Your platform member is defined on each item, you'll have to specify which array item you want the platform for. This should do the trick:
alert(json[0].platform);
I'm assuming that your json parameter actually holds a javascript object, and not simply a string. If it is a string, you should define contentType 'application/json' on your php page. (I'm not sure how you do that in php since I do .NET for server side myself.)
To test it quickly however, you can do a $.parseJSON(json) to get the object.