How to grab JSON values with Ajax JQuery.each()? - javascript

this is my first question here! New to using Ajax, and have hit an issue that maybe someone could catch what I am doing wrong.
var featuredList;
$.ajax({
url: "myurl",
type: 'GET',
success: function(result){
featuredList = JSON.stringify(result);
alert(result);
$.each( result, function( key, value ) {
alert('not working');
});
},
error: function(){alert('error');}
});
I have gone this path before with no issues, this time around I cannot get inside the loop. The alert(result) is returning my data just fine.
Thanks!

Hi,
Hope this might help you to process JSON data received from AJAX request, try below code:
jQuery.ajax({
url:'myurl',
dataType: "json",
data:{
classId:'C001'
},
type: "GET",
success: function(data) {
for (var j=0; j < data.length; j++) {
//syntax to get value for given key
//data[j].yourKey
var userId = data[j].userId;
var name = data[j].name;
var address = data[j].address;
}
}
});
Thanks,
~Chandan

As per your code try doing this:it should work
var data = JSON.parse(result);//here result should be json encoded data
$.each( data, function( key, value ) {
alert(value);
});

Use jQuery promises, gives you more semantic and readable code
var featuredList;
$.getJSON("myurl", {"optional": "data"})
.done(function(data){
// successful ajax query
$.each( data, function( key, value ) {
// do whatever you want with your iterated data.
});
});
.fail(function(){
// catch errors on ajax query
});

I do it this way
$.getJSON('url',
function(dataList) { // on server side I do the json_encode of the response data
if(dataList !== null) {
$.each(dataList, function(index, objList ) {
// rest of code here
});
}
});
Hope this works for you as well.

function getArray(){
return $.getJSON('url');
}
var gdata = [];
getArray().then(function(json) {
$.each(json, function(key, val) {
gdata[key] = val ;
});
console.log(gdata);
I had the Same Problem It took 2 days to got the solution.
You have to resolve the promise and return the json object to access the value.

You could easily do this using the open source project http://www.jinqJs.com
/* For Async Call */
var result = null;
jinqJs().from('http://.....', function(self){
result = self.select();
});
/* For Sync Call */
var result = jinqJs().from('http://....').select();

You can also use $.Json to get your solution , here is an example
$.getJSON('questions.json', function (data) {
$.each(data,function(index,item){
console.log(item.yourItem); // here you can get your data
}
}
You can use or print Index if you want it. Its show the data index.
Hope it may help you, I am exactly not sure its your requirement or not, But i have tried my best to solve it.

This will work as the result from ajax call is a string.
$.each($.parseJSON(result), function( key, value ) {
alert('This will work');
});

Related

Convert Json encoded data to javascript array and access value by index

I am getting json response from ajax like this
echo json_encode($data);
Ajax code:
$.ajax({
url:"PaymentSlip/check",
data:{val:val},
type: 'POST',
success:function(ajaxresult)
{
$("#jgoli").html(ajaxresult);
}
});
Result I am getting is:
[{"paymentId":"2","paymentLabNo":"MR-622-040618",paymentTestId":"1"}]
Now I want to access my json array in javascript by index like
ajaxresult[0] = 2; i.e paymentId=2
ajaxresult[1] = 2; i.e paymentLabNo=MR-622-040618
How would I achieve that?
Note: I have tried many examples on stackoverflow, I know this question must have answered earlier. But I am still stuck. Any help would be appreciated.
$(document).ready(function(){
var data = [{"paymentId":"2","paymentLabNo":"MR-622-040618","paymentTestId":"1"}];
//Loop on the object as key=>value
$.each(data, function(key, value){
//And diplay it in the result div
$('#result').append('<p>'+data[key]['paymentId']+'</p>');
$('#result').append('<p>'+data[key]['paymentLabNo']+'</p>');
$('#result').append('<p>'+data[key]['paymentTestId']+'</p>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="result"></div>
What you are getting is a string of encoded JSON, to use it as an object you must parse it.
Check this answer
$(document).ready(function(){
$.get("ajax_call.php", function(data){
//console.log(data);
var result = JSON.parse(data);
$.each(result, function(key, value){
$('#data').append('<tr><td>'+result[key]['username']+'</td><td>'+result[key]['email']+'</td><td>'+result[key]['mobile']+'</td></tr>');
console.log(result[key])
});
});
});
$.ajax({
url:"PaymentSlip/check",
data:{val:val},
type: 'POST',
datatype: "json", // add this
success:function(ajaxresult)
{
// access return results as
//ajaxresult[0].paymentId;
//ajaxresult[0].paymentLabNo;
//ajaxresult[0].paymentTestId;
//$("#jgoli").html(ajaxresult);
}
});

Wikipedia AJAX call

I have this code, it does an AJAX call to Wikipedia, asking for results of a given query (var searchText):
function main() {
$(".btn").click(function() {
$("#iframe").attr('src', 'https://en.wikipedia.org/wiki/Special:Random');
$(".embed-container").css('visibility', 'visible');
});
function wikiAjax (searchURL) {
return $.ajax({
url: searchURL,
jsonp: "callback",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
}
});
}
$(".search-form").submit(function() {
event.preventDefault();
var searchText = $('#search').val();
var searchURL = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=" + searchText + "&gsrlimit=15&prop=extracts&exsentences=3&exintro=&explaintext&exlimit=max&callback=JSON_CALLBACK";
console.log(searchURL);
var wikiResponse = wikiAjax(searchURL);
wikiResponse.done(function(data) {
console.log(data);
}).fail(function(err) {
alert("The call has been rejected");
});
});
}
$(document).ready(main);
But it returns me a strange object:
Could someone please help me?
you've the right response from Wikipedia, check your query parameters, specially this one
var searchText = $('#search').val();
which value you are testing with, if you entered something like "2sasd23sda" you'll get this object response.
The Ajax call needs to have 3 parameters. There is JSON data in the 3rd param. Try it with this jsfiddle.
wikiResponse.done(function(error, success, data) {
console.log(data.responseJSON.query.pages);
})
This is the correct response for a query that has no matches. the issue is most likely the search value you are appending.
Below are two result sets, one using a term that yields no response the other using Test.
Response with no results:
No Results
Response with results:
Results

JQuery: parsing ajax call versus imbedded str

I am confused because I have two functions, one using ajax to get the data and the other getting it from a string.
function loadMenuData() {
$.ajax({
url: "./shoulders.json",
success: function(data) {
dataObj = $.parseJSON(data);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
});
}
function loadMenuDataX() {
var str = '[{"id":"A","name":"Bart"},{"id":"B", "name":"Joe"},{"id":"C", "name":"Gomer"}]';
dataObj = $.parseJSON(str);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
I created the file shoulders.json buy pasting the str between the single quotes ' into the file. If I call loadMenuX, it fills in the <select></select> correctly. If I call loadMenu, it doesn't fill anything in.
I have tried JSON.parse instead of the above and get the same behavior.
I was unable to use $("#dropDownDest") and had to use $(document).find. Why?
Hitting the DOM each loop seems to be excessive. What would be a better way to do the ajax version THAT WOULD WORK and be better?
What would be a better way to do the ajax version THAT WOULD WORK and be better?
Because you're trying to get JSON file the better way is using jQuery.getJSON(), so you will be sure that the returned result is in json format :
$.getJSON( "./shoulders.json", function( json ) {
$.each(json, function( key, value) {
$("#dropDownDest").append('<option value="+value.id+">'+value.name+'</option>');
});
});
Hope this helps.

Jquery get data from JSON (undefined)

When i try to get value from json data i getting undefined
$.get( baseURL + 'vacation/show/' + name_surname, function( data ) {
alert(data); // return [{"id":"1","title":"Testas","start":"2015-03-04","end":"2015-03-04"}]
alert(data.start); // return undefined (should be here 2015-03-04)
});
I need get only start value from data, how can i fix this?
If your data is not an object, you need to make an object out of it to be able to access its values. I am not sure what it is at the moment. Hence, I've put a condition to check the type and then alert accordingly.
$.get( baseURL + 'vacation/show/' + name_surname, function( data ) {
alert(data);
// return [{"id":"1","title":"Testas","start":"2015-03-04","end":"2015-03-04"}]
if (typeof data === "object") {
alert (data[0].start);
} else {
alert (JSON.parse(data)[0].start);
}
});
A demo#fiddle along the same lines.
Use this :
$.get( url, function( data ) {
/* do stuff */
}, 'json');
or this :
$.getJSON( url, function( data ) {
/* do stuff */
});
Before Accessing a Json data from 'data' object, you need to parse it to Json Object.
you can achieve this as below:
var parsedJson=$.parseJSON(data)
Here after you can access the json objects like:
alert(parsedJson[i].start);
where 'i' is the index on N-th data set in the Json object, it can take any numeric value ranging from 0,1,..N
Hope this Helps!!
you can do like following:
$.ajax({
type: 'GET',
url: baseURL + 'vacation/show/' + name_surname,
dataType: 'json',
success: function(data) {
for(var i = 0; i < data.length; i++) {
console.log(data[i].start);
}
},
error: function(e) {
console.log(error);
}
});
Ty to all, it works fine now, just wondering, or i doing good in my next step, if i retrieve from array for loop and then push only dates into array again to get min date, or it will not be a duplication of work?
$.getJSON( baseURL + 'vacation/show/' + name_surname, function( data ) {
if(data != '') {
var dates = [];
for(var i = 0; i < data.length; i++) {
var date = new Date(data[i].start);
dates.push(date);
}
var minDate = new Date(Math.min.apply(null, dates));
var year = minDate.getFullYear();
var month = minDate.getMonth();
$('#calendar').fullCalendar('gotoDate', year, month);
}
});

Getting typeError:e is undefined in firebug while running a script

I am not able to figure out what is wrong with my code.I am getting data from post as an array and I am then displaying that data in box.
function worker() {
var a = $("#BeeperBox");
var delay =2000;
$.ajax({
url: '/index.php/admin/getLatest',
success: function(data) {
$.each(data.upda,function(i, v){
var out = v.name + v.mob ;
$('span.blueName').html(out);
$("#BeeperBox").show();
timerId = setTimeout(function () {
a.hide();
}, delay);
});
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 50000);
}
});
}
When i run it firebug shows error: TypeError: e is undefined.
since your sending the response as JSON.. its better to specify your dataType as JSON (though If none is specified, jQuery will try to infer it based on the MIME type of the response ) so that you don't have to parse it manaully..i think the problem here is you havn't parsed the json that you got as response
try this
$.ajax({
url: '/index.php/admin/getLatest',
dataType: 'json',
success: function(data) {
$.each(data.upda,function(i, v){
var out = v.name + v.mob ;
......
},
Check if data.upda is undefined, I think the problem is that that variable doesn't exist and you're trying to iterate over a undefined element.

Categories