I am using php and using json_encode() function I returned/echoed JSON array. I was using jquery ajax and successfully retrieved this data:
[{"id":"1132","city":"Manila Central Post Office","province":"Manila"}]
I use this code on my Javascript btw:
var val = jQuery.parseJSON(JSON.stringify(result));
and when I tried to accessed the data on the array like:
console.info(val.city); // results to undefine
It gives me 'undefined' result. I tried doing For in loop still doesn't work. Maybe I'm doing something wrong, any help would be great. THANKS
Ajax code:
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
success: function (result) {
var val = jQuery.parseJSON(JSON.stringify(result, false, replacer));
var val2 = jQuery.parseJSON(val);
console.info(val2);
console.info(val2.id);
},
error: function (e) {
$("#sys_msg").html(e);
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});
val is an array. You need to specify index like below.
var result = [{ "id": "1132", "city": "Manila Central Post Office", "province": "Manila" }];
var val = jQuery.parseJSON(JSON.stringify(result));
alert(val[0].city);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here val is an array of objects, so you cannot access the city value directly by calling val.city. If the data being returned is already encoded by using json_encode(), then you simply need to use $.parseJSON(data). The following code snippet shows how to do this-
var temp = '[{"id":"1132","city": "Manila Central Post Office", "province":"Manila"},{"id":"1133","city": "Another Test Post Office", "province":"Test"}]'; //Defined temp as string since the data response returned from the server should also be a json encoded string.
var val = $.parseJSON(temp);
$.each(val, function(index, item) {
var city = item.city;
$('.container').append('City: '+city+'<br/>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="container"></div>
See, the issue can be easily resolved by dataType:"json". If you don't have this attached in your ajax code then the returned response will be a json string and in this case only you have to parse it with jQuery.parseJSON() or JSON.parse().
So, you can add the dataType to the ajax or instead just only parse it.
success: function(result){
var val = jQuery.parseJSON(result); // or JSON.parse(result);
console.info(val[0].city);
},
With dataType:
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
dataType: 'json', //<-----add this here
success: function(result) {
for (o in result) { // <----and just use this way
console.info(o.city);
}
},
error: function(e) {
$("#sys_msg").html(e);
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});
You don't have to stringify it then parse it to JSON again. You can just add dataType: "json" in your AJAX.
$.ajax({
type: 'POST',
url: path,
cache: false,
data: postData,
dataType: "json",
success: function (result) {
console.info(result);
console.info(result.id);
},
error: function (e) {
$("#sys_msg").html(JSON.stringify(e));
$("#myModal").modal({
show: true,
backdrop: false,
keyboard: true
});
}
});
Related
I have an weird issue in my php and javascript.
I have something in php like
$testData = array(
'prop1' => true,
'prop2' => 2,
'name' => 'testname',
'number' => 123
);
echo json_encode($testData);
in Javascript
$.ajax({
type: "GET",
cache: false,
async: false,
url: phpfile,
global: false,
success: function(result) {
console.log(result)
console.log(result.prop1)
console.log(result.prop2)
}
I was able to get result from console.log(result) but I can't get anything from console.log(result.prop1) nor console.log(result.prop2). Did I do something wrong here?
Thanks!
You have transform the json from php
success: function(result) {
var res = JSON.parse(result)
console.log(result)
console.log(res.prop1)
console.log(res.prop2)
}
There are 2 ways to get json objects from ajax.
First: (Recomended)
You have to define dataType property with JSON,
example:
$.ajax({
type: "GET",
cache: false,
async: false,
url: phpfile,
global: false,
dataType: 'JSON',
success: function(result) {
console.log(result)
console.log(result.prop1)
console.log(result.prop2)
}
});
in this case, jQuery will process the result as JSON and then you can access it's object property, if it is not an JSON, then it will go for error event.
Second:
The other way to parse the object is by using JSON.parse() function because the data you are getting is just string.
example:
$.ajax({
type: "GET",
cache: false,
async: false,
url: phpfile,
global: false,
success: function(result){
var data = JSON.parse(result);
console.log(data);
console.log(data.prop1);
console.log(data.prop2);
}
});
you encode your array in PHP to send it to Javascript, by writing json_encode($testData); so to get it on javascript side you have to use JSON.parse(yourencodedArray) by using this you are able to get values inside your array.
var data = JSON.parse(yourencodedArray);
var dat1 = data.prop1;
var dat2 = data.prop2;
JSON.parse is able to decode your encoded Array.
If I need to call a controller like this:
name.php?data={"user":"test","pass":"test"}
In order to obtain the information I need, via .ajax, I need help setting the variable to be sent with that specific format.
I used to the following code:
var arr = [{
data: {
"user" : $("#usuario").val(),
"pass" : $("#password").val()
}];
arr = JSON.stringify(arr);
However if doesn't send the right output, I've been said I need to send the variable with the json on it.
function callAjax(url, arr) {
var response = null;
jQuery.ajax({
url: url,
type: 'POST',
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(data) {
response = data;
},
error: function(jqXHR, textStatus, errorThrown) {
response = errorThrown;
},
timeout: 5000
});
return response;
}
Any advises?
Best Regards!
This link will help you a lot!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
I used .post instead and solved the issue
Here is my script:
$.ajax({
type: "Get",
url: "Sample.js",
datatype: 'json',
data: JSON.stringify({ key:key }),
success: function (data) {
var sample = data.name;
$("#html").html(sample);
},
error: function () {
alert("Error");
}
});
This is my Sample.js file:
{ "name": "user" }
When I run this code I get a blank screen. This is my script using getJSON():
$.getJSON("Sample.js", function (data) {
var sample = data.name;
$("#html").html(sample);
})
This produces "user" perfectly. What is the problem with $.ajax code?
In the getJSON version your don't send any data. Could this be the reason why that works? To me it looks like this could be sth. on the server side that delivers an empty JSON object when you pass the key parameter.
As the jQuery documentation states:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Try modifying the dataType param.
change your datatype to dataType. Its case sensitive. Refer http://api.jquery.com/jQuery.getJSON/
Remove JSON.Stringify and change Get to GET
$.ajax(
{ type: "GET",
url: "Sample.js",
dataType: "json",
data: {key:key },
success: function (data)
{ var sample = data.name; $("#html").html(sample); },
error: function () { alert("Error"); }}
);
I have recently posted another question which straight away users pointed me in the right direction.
$.ajax({
type: 'POST',
url: './',
data: 'token=' + token + '&re=8',
cache: false,
timeout: 5000,
success: function(html) {
auth(html);
var JSON_array = eval(html);
alert(JSON_array[0].username);
}
});
this returns the data correctly but I want to perform a kind of 'foreach'. the array contains data about multiple incoming and outgoing Instant Messages. So if a user is talking to more than one person at a time i need to loop through. the array's structure is as follows.
Array(
[0] => Array
(
[username] => Emmalene
[contents] =>
<ul><li class="name">ACTwebDesigns</li><li class="speech">helllllllo</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">sds</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">Sponge</li><li class="speech">dick</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">arghh</li></ul>
)
)
Any help very much appreciated.
Well since you are using jQuery already you could use the each function:
$.ajax({
type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000,
success: function(html){
auth(html);
var JSON_array = eval(html);
$.each(JSON_array, function(index, data) {
$('someelement').append(data.contents);
});
}
});
Instead of evaluating the HTML, you can even specify JSON as return type...
Iteration is easy when using $.each:
$.ajax({
type: "POST",
data: ...,
url: url,
dataType: "json",
success: function(data) {
$.each(data, function(i, item){
// do something with every item in data
// you can reference items in data via
// data.fieldName
});
}
});
But a for ... in loop isn't much harder:
$.ajax({
...,
dataType: "json",
success: function(data) {
var fields = data.fieldName;
var value;
for (value in fields) {
// do something with value
}
}
});
Just to clarify, As I've read many helpful hints and answers and only this one worked for me:
$.ajax({
type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000, datatype: 'json',
success: function(html){
auth(html);
var JSON_array = eval(html);
$.each(JSON_array, function(index, data) {
var talk_to = JSON_array.username;
var contents_to_update = JSON_array.contents;
});
}
});
this which made work:
1) use of eval.
2) datatype: 'json'
3) use of jquery's $.each function
I'm using jQuery to grab some JSON data. I've stored it in a variable called "ajaxResponse". I cant pull data points out of it; I'm getting ajaxResponse.blah is not defined. typeof is a string. Thought it should be an object.
var getData = function (url) {
var ajaxResponse = "";
$.ajax({
url: url,
type: "post",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
return ajaxResponse;
},
...
typeof ajaxResponse; // string
ajaxResponse.blah[0].name // ajaxResponse.blah is not defined
make sure you specify option dataType = json
$.ajax({
url: url,
type: "post",
dataType: "json",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
Q8-coder has the right of it, but to give you some details: your server is really passing back a string that you've formatted into JSON. You'll need to tell jQuery what to expect, otherwise it just assumes it received a string.
Add the following to your $.ajax options:
dataType: "json"
Also, refer to the jQuery API for examples and documentation for these options.