How to get retrieve data via ajax in my case? - javascript

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.

Related

Using JSON.stringify and can't access the JSON array

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

howto cut json string?

I have a problem here and no idea how to solve it...
I have a json file like this:
{"data":[{"kw":"48","val":"10","val2":"05"},{"kw":"49","val":"04","val2":"05"}]}
But I need this format:
[{"kw":"48","val":"10","val2":"05"},{"kw":"49","val":"04","val2":"05"}]
In javascript/jQuery I make an ajax request and get the json back:
$.ajax({
type : "POST",
cache : "false", // DEBUG
url : weburl,
dataType : "json",
contentType : "application/json; charset=utf-8",
success : function(data) {
// Strip data?
}
});
Does anyone know how to do this?
Thanks!
success : function (data) {
var array = data ? data.data : null;
// now perform the required operations with array variable.
}
This will return just the array, not wrapped in a object.
$.ajax({
type: "POST",
cache: "false", // DEBUG
url: weburl,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
var arrayYouWant = data.data; // http://thedailywtf.com/Articles/Data-Data-data-Data.aspx
}
});
Why do you need to strip it, you just reference it
success : function(data) {
var myArrayofObjects = data.data;
}
In order to really understand read about the Member operators in Javascript, particularly the dot notation. JSON is a subset of Javascript and the JSON object is a Javascript object in the end.
Not sure what you mean by archive. Do you mean simply access the array that is associated with the data property?
The array is associated to the 'data' property in your JSON string. I would maybe change the name of the data argument passed into the success function.
Try this:
$.ajax({
type: "POST",
cache: "false", // DEBUG
url: weburl,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(resp) {
var yourArray = resp.data;
console.log(yourArray);
}
});

javascript jquery and using eval

i am currenty using jquery plugin to read a data file (data.html)
data.html has below format
[10,20,30,40,50]
my jquery data request and the javascript to return values is below
function test(){
var result=$.ajax({
url:'data.html',
type:'get',
dataType:'text',
async:false,
cache:false
}).responseText
return result;};
var my=test();
alert(my[0])
i want to get these values in the array format i.e i want my[0] to be value 10, but instead i get "[".
If i use eval function
my=eval(test());
i can get 10, but is there any other better way to store the returned ajax calls into an array instead of string?
Thanks
i tried the below answer and i am bit puzzled, the follow code results in myArray is null (in firebug), but i put async:false then it works. why do i need async:false to store the values into array ? (http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req)
jQuery.extend({getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;}
});
return result;}});
myArray=$.getValues("data.html");
alert(myArray[1]);
You don't need eval. Just indicate the proper dataType: 'json':
function test() {
return $.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
async: false,
cache: false
}).responseText;
}
var my = test();
alert(my[0]);
or even better do it asynchronously:
function test() {
$.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]);
}
});
}
test();
I think jquery $.getScript('data.html',function(){alert("success"+$(this).text())} might be simpler. I have not had time to try it so if I'm on right track, improve this answer, if not I'm happy to learn now...

looping through JSON array

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

Can't query JSON using jQuery

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.

Categories