How to access entry in the javascript object array - php

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);
}
});

Related

$.ajax()function with json data from javascript array to a php processing file

i trying to use json for the first time with $.ajax() i got the values of checkboxes and other needed data to a php file for processing and posting to mysqldb through an array for the data section of $.ajax() function but would get an empty array[] on my php file. When i try using javascript debugging tool from my browser i got the reprot
**Uncaught SyntaxError: Unexpected end of input jquery-1.9.0.min.js:1
st.extend.parseJSON jquery-1.9.0.min.js:1
(anonymous function) index.php?url=account/registration/:297
st.event.dispatch jquery-1.9.0.min.js:2
y.handle**
the array i produced looks like this at the console log
[checkbox1: "COM 101", semester: "1st Semester", mid: "7", checkbox2: "COM 112", checkbox3: "STA 111"…]
checkbox1: "COM 101"
checkbox2: "COM 112"
checkbox3: "STA 111"
checkbox4: "STA 112"
checkbox5: "MTH 111"
length: 0
mid: "7"
semester: "1st Semester"
on my php processing file i did print_r on the json data but got an Array[] as a result
this is my javascript code block "myDataArray is a global variable"
$('#mytable2').on('change',function(e){
var rel = e.target.getAttribute('rel');
console.log(e.target.value+ " "+ e.target.checked)
if(rel === globals.payment_target && e.target.checked===true){
myDataArray[e.target.getAttribute("name")]= e.target.value;
myDataArray["semester"] = $("#semester").val()
myDataArray["mid"] = $("#mid").val()
}
if(rel === globals.payment_target && e.target.checked ===false){
delete myDataArray[e.target.getAttribute("name")]
console.log(myDataArray)
}
});
$('#mytable2').on('click',function(e){
var rel = e.target.getAttribute('rel');
console.log(e.target.value+ " "+ e.target.getAttribute('name'))
if(rel === globals.payment_target && e.target.value =="Register"){
console.log(myDataArray)
var jsonstring = $.parseJSON(myDataArray);
var myglob =JSON.stringify(globals)
console.log(myglob)
$.ajax({url:'courseregistration.php', type:'POST',data:{data:jsonstring},success: function(result){
$('#putmehere').html("<h4 style='text-align:center'>"+result+"</h4>")
alert(result)
}
})
}
});
and this what the php file looks like
$data = json_decode($_POST['data']);
print_r($data);
i just can't figure out what the problem is. can someone please tell me what is wrong with the way i'm doing it or suggest a better way
Try to set data type property json
$.ajax({
url:'courseregistration.php',
type:'POST',data:{data:jsonstring},
datatype:"json",
success: function(result){
$('#putmehere').html("<h4 style='text-align:center'>"+result+"</h4>")
alert(result)
}
});
Also set content type in php script.
header('Content-Type: application/json');
The reason that your page is not working is the critical error (your first listing). You need to clear up this error before you can do anything else because your form is not being submitted as you want it to.
The reason for the error: maybe a corrupt file - download another copy of jQuery and try again.
i removed this --- $.parseJSON(myDataArray) --- and the error did not come again i used JSON.stringify(myDataArray) instead. also i declared myDataArray as an object instead of as an array and things went fine, it solved the Uncaught SyntaxError: issue
Initially, i declared myDataArray as an array
var myDataArray = new array();
but when i changed myDataArray to Object
var myDataArray = new Object;
i effect it as below and things went fine
$('#mytable2').on('click',function(e){
var rel = e.target.getAttribute('rel');
console.log(e.target.value+ " "+ e.target.getAttribute('name'))
if(rel === globals.payment_target && e.target.value =="Register"){
console.log(myDataArray)
console.log(globals)
var jsonstring = JSON.stringify(myDataArray);
console.log(myglob)
$.ajax({url:'courseregistration.php',dataType:"json", type:'POST',data:{data:jsonstring},success: function(result){
$('#putmehere').html("<h4 style='text-align:center'>"+result+"</h4>")
alert(result)
}
})
}
});

Reading JSON data (created by PHP) via jQuery Ajax results in "parserror"

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.

Passing array through AJAX from php to javascript

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);
});
});

Pass array from php back to javascript and loop over it

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);
});

Parsing PHP/JSON data in Javascript

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!

Categories