Unable to loop through JSON reponse in JQuery with .each method - javascript

I'm unable to extract object properties using the . each() method in Jquery. I'm able to view the full response with console.log (result), but I'm unable to extract from that response. I receive an undefined or [Object object] message when I attempt to use result.snippet in the .each method. When I use the .each for other json responses I'm able to extract by using data.value, but for this response it doesn't work.
(function getArticles(){
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "",
'q': "obama"
});
$.ajax({
url: url,
type:"GET",
data:{
}
}).done(function(result) {
console.log(result);
$.each(result, function () {
document.write(result.snippet); // This is not working, but works with other json responses from other API's//
})
});
})();

The response you're getting is an object, not an array. You can't iterate over an object. You can iterate over the keys of an object and then reference each key. In either case, you don't need jQuery to do the iteration.
var response = {
"hello": "world",
"foo": "bar"
};
for (var key in response) {
console.log(key, response[key]);
}
In your case, to get to the snippet:
response.docs[0].snippet
You could iterate each document:
response.docs.forEach(function(doc) {
console.log(doc.snippet);
});

Related

Accessing Ajax Response JSON Data in javascript

I use an AJAX request to get the data from the backend when user select an option from a dropdown menu.
$('#adSpace').change(function () {
var sel_opt = $(this).val();
alert(sel_opt);
var location = null;
var width = null;
var height = null;
$.ajax({
type: "GET",
dataType: 'json',
url: "advertisements-controller.php",
data: {
action: "getDimension",
location: sel_opt
},
success: function (response) {
location = response.banner_location;
alert(location);
},
error: function (xhr) {
alert("error");
}
});
});
Now i'm getting the data from backend in JSON format like below:
[{"banner_location":"category_group_sidebar","banner_width":250,"banner_height":225}]
I want to access the values of banner_location, banner_width, banner_height by assigning those to javascript variables but I'm failing to do it.
Any ideas?
Use this
location = response[0].banner_location;
Your response comes in the form of an array: [...]. That means you can access the first array item by using the index. Also if there are multiple objects you can iterate response with forEach or jQuery's each($(response).each).
response[0].banner_location
response is an array of json. In order to access the json you need to firsr access the index of the array which is done by array[indexNumber] then the key of the json.
In your case it will be response[0].banner_location

How can I capture the Array object returned by an api call through HTTP GET?

The API call
https://myhost.net/api/get_global_search_result/methods/test
returns an Array object. I am trying to hold it in an Array object in order to read the attributes and values in it.
var queryResult = [];
queryResult = browser.get('https://myhost.net/api/get_global_search_result/methods/test/');
console.log('result length: ' + queryResult.length);
This is what I see on my console:
result length: undefined
If I load the above specified URL directly in a browser instance, it shows the Array with its contents.
What is the better way of capturing the array object returned by this call?
What about using JQuery ajax request.
it would be some thing like :
$(document).ready(function() {
$("#testbutton").click(function() {
$.ajax({
url: 'http://localhost:9200/xyz/xyz/xfSJlRT7RtWwdQDPwkIMWg',
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function() {
alert('error');
}
});
});
});

How to parse json object datalist in ajax sucess using javascript

i am trying to parse json datalist in ajax success bt it couldnot work. i have passed object containing list of data using json from controller to view,i help to parse json object in ajax success. i have attached my code below.
//return json object from controller
PurchaseDetails pd = new PurchaseDetails();
foreach (DataRow dr in dt.Rows)
{
pd.serialList.Add(new SerialInfo {
Machine_serial_no = dr[0].ToString(), macAddress = dr[1].ToString(), isMacPresent = _TD1.CheckMac(machineTypes_MTId),brandName=obj.brandName,machineName=obj.machineName,MachineModel=obj.MachineModel,modelId=modelId,machineId=obj.machineId,brandId=obj.brandId});
// pd.macaddressList.Add(new MacAddressInfo { MacAddress = dr[1].ToString() });
}
}
}
return Json(new {pd}, JsonRequestBehavior.AllowGet);
return Json(new {pd}, JsonRequestBehavior.AllowGet);
// my ajax code
$.ajax({
url: "/Import/ImportPurchase",
type: "POST",
data: function () {
var data = new FormData();
data.append("file", jQuery("#file").get(0).files[0]);
data.append("machineTypes_MTId", jQuery('#machineTypes_MTId').val());
data.append("modelId", jQuery('#searchValue').val());
data.append("modelName", jQuery('#searchid').val());
return data;
}(),
dataType:"JSON",
contentType: false,
processData: false,
success: function (data) {
alert(data.Machine_serial_no)
Your controller method is returning
return Json(new { serialObj = pd}, JsonRequestBehavior.AllowGet);
which is an object containing a name serialObj
So in the ajax success call back, you would need to access it using
success: function (data) {
var PurchaseDetails = data.serialObj;
Since PurchaseDetails contains a collection named serialList which is a collection of SerialInfo, then to access the value of the first Machine_serial_no, it would be
var serialNo = data.serialObj.serialList[0].Machine_serial_no;
However it would be easier to just use
return Json(pd, JsonRequestBehavior.AllowGet);
If you then want to access each Machine_serial_no property in the collection, use
success: function (data) {
$.each(data.serialList, function(index, item) {
var serialNo = item.Machine_serial_no;
you can use jQuery.parseJSON() to parse ajax response to JSON.
but seeing from your code, seems the response should already be in JSON because dataType parameter is already set to "JSON".
try this:
remove "()" after the ending bracket of function in "data" parameter.
try to console.log(data) and look at the response from your browser console,
the response might not be a valid json string.
If you are looking for convert js array to JSON then just use JSON.stringify() function. This will convert your JS variable data value to JSON format.
You can more find here.

How do I handle this jQuery ajax reponse

I receive the following
[{"user_id":"1","user_invoice_add1":"Stark Towers","user_invoice_add2":"123 Reginald Street","user_invoice_city":"Newport","user_invoice_state":"New York","user_invoice_country":"US","user_invoice_zip":"321654"}]
How do I pick out information from it?
trying data.user_id or data[0].user_id returns as undefined
jQuery
$.post('post.php', qString, function (obj) {
console.log(obj);
}
You'd have to first convert this string into JSON object by using a jQuery function var obj = $.parseJSON(data).
It will return you a JSON object that you can access like obj[0].user_id
use this:
myObject = jQuery.parseJSON( dataReceived );
and then you can access the data as properties of the object
Try like this..
$.map(data.d, function (item) {
alert(item.user_id)
});
jquery.ajax has a setting called dataType this is what your getting response from server as..
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.
$.ajax({
....
dataType:"json",
success:function(data){
alert(data.user_id) //no need to parseJSON...dataType does it
};
});
Using POST
$.post('post.php', qString, function (obj) {
console.log(obj);
}, "json");
or you can use $.parseJSON(data) to convert the string as json object

Send JavaScript object to web server call via jQuery - what is the correct way?

I'm trying to send JSON data to my web server via jQuery and I'm running into an error.
Uncaught TypeError: Cannot use 'in' operator to search for 'context' in {"id":45,"isRead":true}
code I am testing:
var obj = {};
obj.id = 45;
obj.isRead = true;
var data = JSON.stringify(obj);
var url = "/notification/read"
$.ajax(url, data, 'application/json', function() {
// code remove notification from the DOM
});
});
Is there a better or more correct way to do this? Not sure if I'm getting the params right on the $.ajax call either.
UPDATE
code I got to work
var obj = {
id: 45,
isRead: true
};
var json = JSON.stringify(obj);
var url = "/notification/read"
$.ajax({ url: url,
type:'POST',
contentType: 'application/json',
data: json,
success: function(data, textStatus) {
// do stuff
}
});
My server was expecting JSON data POSTed as application/json. So was I wrong in thinking I needed all these variables? without these it was sent as a GET and was application/x-www-form-urlencoded. Without the stringify it also didn't work.
You are passing too many arguments to the ajax function: http://api.jquery.com/jQuery.ajax/
Also, the JSON.stringify call is not necessary, jQuery will take care of that for you.
var obj = {
'id':45,
'isRead':true
};
$.ajax({
url: "/notification/read",
data: obj,
success: function(data, textStatus){
/* code here */
}
});
$.ajax(url, obj);
You need to send an object as second param
{success: success, data: data}
Documentation is here:
http://api.jquery.com/jQuery.ajax/
You have to pass parameters as one object, not multiple ones

Categories