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!
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);
});
How do I accomplish the following:
User clicks on "Start" button on an HTML page makes a GET to a getnumber.php page, that returns the number 10 in the following form: {count: 10}
//you jquery code
$.getJSON('getnumber.php', function(data) {
alert(data); //returns your json_encoded number sent from getnumber.php page
});
//your php page
$arr = array("count" => 10);
echo json_encode($arr);
<input type="button" id="btnID"/>
$("#btnID").click(function(e){
e.preventDefault(); //prevent the default behavior of the button, or return false as #alecgorge pointed it out
$.get("process.php",function(data){
console.log(data);
},'json'); //<-- specifying the dataType as json will parse the json return by the server
});
in the process.php
var $count=10;
echo json_encode($count);
look at
json_encode
$.get()
Try Google.
Here is a good place to start.
Then go here and learn more.
Put them together and you should be well on your way.
You need PHP return data in JSON format, which would be:
{"count": 10}
and indicating the returning data is JSON format with a header in the response.
From JavaScript side the returned value, the previous string, can be evalutated and converted to a JS object.
use json_decode in getnumber.php
json decode manual page
Try something like this
$.get('getnumber.php', function(data) {
var result = eval(data);
});
If the page getnumber.php output {count: 10} then you get the result with result.count
You can also use $.getJSON method.
How can print date and age (in following array) separate by $.ajax()?
php:
$array = array(
'date' => 2011/9/14,
'age' => 48,
);
return $array // this send for ajax call in the jQuery
I want this output by jquery:2011/9/14 & 48
Use $.ajax Methods and setting parameter dataType to JSON for receive data type JSON from PHP file.
Jquery Code:
$.ajax({
url: "getdata.php",
type: "post",
dataType: "json",
success: function(data){
alert("Date:" + data.date + "\n" + "Age:" + data.age);
}
});
if your array data contains string make sure it's closured with quote then make data type JSON with json_encode() function.
PHP Code (getdata.php):
$array= array('date'=>'2011/9/14','age'=>48);
echo json_encode($array);
Echo the encoded array in php page say mypage.php
using
echo json_encode($array);
And use jQuery.getJson in the client side
$.getJSON('mypage.php', function(data) {
alert(data['date']);
alert(data['age']);
});
You need to encode the array as a valid JSON string using the PHP function json_encode. You can then use the jQuery function $.parseJSON to convert it into a JavaScript object. From there you'll be able to do whatever you want with it.
If you do this, you'll end up with an object like:
ajaxDataObj = {
date: '2011/9/14',
age: 48
}
**Edit**
Please see stratton's comment below about using $.getJSON for a more compact solution.
Also, Ben Everard's comment on your original post about using echo rather than return is critical.
You can't just return $array to the browser, the result will be "Array" as string.
YOu have to use return json_encode($array); which returns a string that could be parsed by browser.
If the server-client communication is working alright, then you should do something like this on the client side:
$.ajax({
//configuration...
'success':function(response){
var dateAge = response.date+' & '+response.age;
//put or append the string somewhere.
}
});