I'm trying to access some JSON data that I got through an ajax call. I'm not sure how to access this data now though. I want to extract the "test" portion out of the json. Could someone please help me out with this
Image of current output
code sample:
$(".test").on("click", function() {
var dialogID = $(this).attr("id");
console.log(dialogID);
$.ajax({
type: "GET",
url: "test.php?id=" + dialogID,
dataType: "json",
success: function(data) {
console.log(data);
},
error: function() {
console.log("error");
}
});
Assuming the ajax data is stored in a variable called 'data'
data['DATA'][0][0];
If you look at the developer console, you'll notice that 'test' in an item in array at index 0. That array is at index 0 of another array called DATA. DATA is an array in the object returned by the AJAX call.
You can see all the data types next to the variable names in the developer console, i.e 'COLUMNS: Array[1]' on the second line tells you that COLUMNS is an array of length 1.
Related
I'm using ajax POST method
to send objects stored in an array to Mvc Controller to save them to a database, but list in my controller is allways empty
while in Javascript there are items in an array.
here is my code with Console.Log.
My controller is called a ProductController, ActionMethod is called Print, so I written:
"Product/Print"
Console.Log showed this:
So there are 3 items!
var print = function () {
console.log(productList);
$.ajax({
type: "POST",
url: "Product/Print",
traditional: true,
data: { productList: JSON.stringify(productList) }
});}
And when Method in my controller is called list is empty as image shows:
Obliviously something is wrong, and I don't know what, I'm trying to figure it out but It's kinda hard, because I thought everything is allright,
I'm new to javascript so probably this is not best approach?
Thanks guys
Cheers
When sending complex data over ajax, you need to send the json stringified version of the js object while specifying the contentType as "application/json". With the Content-Type header, the model binder will be able to read the data from the right place (in this case, the request body) and map to your parameter.
Also you do not need to specify the parameter name in your data(which will create a json string like productList=yourArraySuff and model binder won't be able to deserialize that to your parameter type). Just send the stringified version of your array.
This should work
var productList = [{ code: 'abc' }, { code: 'def' }];
var url = "Product/Print";
$.ajax({
type: "POST",
url: url,
contentType:"application/json",
data: JSON.stringify(productList)
}).done(function(res) {
console.log('result from the call ',res);
}).fail(function(x, a, e) {
alert(e);
});
If your js code is inside the razor view, you can also leverage the Url.Action helper method to generate the correct relative url to the action method.
var url = "#Url.Action("Print","Product)";
I could not retrieve data to jquery div element but i can see ajax response in firebug.
$(document).ready(function () {
$.ajax({
url: "https://m.lowes.com/CatalogServices/product/nvalue/v1_0?nValue=4294857975&maxResults=6&showURL=1&rollUpVariants=1&showUrl=true&storeNumber=0595&priceFlag=rangeBalance&showMarketingBullets=1&callback",
dataType: "jsonp",
success: function (data) {
var returnedData = JSON.parse(data);
$('#result').html(returnedData);
}
});
})
this is my response.for example my url contains data productCount:64 ,I should extract productCount from ajax success and display it in html div id result
When you parse out the JSOn data you use it like so:
var parsed_data = JSON.parse(JSON_DATA);
$('#result').html(parsed_data.key);
So if your parsed_data is somewhat like:
{name:"test",age:12}
then you use it like:
$('#result').html(parsed_data.name); //it will give you test
if you really want to print out the whole data use JSON.stringify(obj) like so:
$('#result').html(JSON.stringify(parsed_data));
In your code you are returning a json and you are trying to insert ino the div it, into the div you can only insert html code instead json.
Try to inspect the json you are returning and in case you need to insert each element into the div, do it, but don't do for all.
The html() method doesn't know what you want to assign, it only insert an html.
You need to iterate over your json data in returnData. You are not able to put json directy into html. You need to convert / parse / iterate it before. So, for example:
$.each(returnedData, function (index, value) {
// do stuff with it, e. g.:
// $('#result').html($('#result').html() + value);
});
https://jsfiddle.net/m8udusps/
The code here actually works. However it says there is a problem when it is parsing the JSON. You needed to add crossDomain: true, to allow it to actually get the results.
Having received a supposed JSON struct like:
{
"Field1": "value1",
"Field2": "value2"
}
This code gets the values of the keys (just first key in this example). Result is an alert message with Data: value1:
$.ajax({
'url' : './localurl',
'type' : 'GET',
'success' : function(data) {
alert("Data: "+data.Field1);
},
'error' : function(request,error) {
alert("Error in response: "+JSON.stringify(data));
}
});
In this case Field1 is the key received and it is directly accesible through data variable, so it is not necessary to do the JSON.parse(data) (in fact this JSON.parse produce an error)
I am using the following code to make a request to a PHP script:
$.ajax({
method: "POST",
url: "myAPI.php",
data: {
orderById: 2,
action: 'returnStuff',
},
success: function(data){
$.each(data.data, function(key, value) {
var $targetToMove = $('.shape.'+value.attr_name);
//if element already exists on page, move it to the end of the container
if($('.'+value.xml_name).length){
$('.container').append($targetToMove);
}
});
}
});
Here is a simplified example of my return data
{"data":{"0":{"id":"1","name":"This","color":"blue"},
"1":{"id":"2","name":"That","color":"red"},
"2":{"id":"3","name":"whatever","color":"blue"}}}
If the orderById equals 1, the data is returned numerically from lowest to highest by the id. If it equals 2 it is returned numerically from highest to lowest like this:
{"data":{"0":{"id":"3","name":"whatever","color":"blue"},
"1":{"id":"2","name":"That","color":"red"},
"2":{"id":"1","name":"This","color":"blue"}}}
The idea is that the API returns the data in the order I want, then on success in the ajax call, the elements are re-arranged on the page in the order of the returned data object.
This works how I intend in Firefox, but in Chrome, whenever I console log the data on success, the order is always the same, despite the console indicating the response from my API is in the correct order.
What am I missing? I can't tell if this is a caching issue or if I am just overlooking something in my javascript.
Object properties order is not guaranteed in JavaScript. You would rather use Array for that
Format you json to look like this:
{"data":[{"id":"3","name":"whatever","color":"blue"},{"id":"2","name":"That","color":"red"},{"id":"1","name":"This","color":"blue"}]}
I have a object district_boundaries which is leaflet geojson object
var district_boundary = new L.geoJson();
and the data is added through ajax call to a geojson file of district
$.ajax({
dataType: "json",
url: "data/district.geojson",
success: function(data) {
$(data.features).each(function(key, data) {
district_boundary.addData(data);
district_boundary.setStyle(district_boundary_styles["default"]);
});
}
});
So in the _layers there are 75 values, one example of such values is the one in the picture with key 149.
I need to loop through all these 75 values and get the values from features key. i.e the name of districts and use them to label the districts.
I tried with this
_test = district_boundary._layers;
for (var aht in _test) {
console.log('inside the loop');
var b = _test[aht];
console.log(b.feature.properties.NAME_3);
}
This works fine when tried in the console and shows the result
But when i tried with by running in the script of my page this doesnot work the though _test is populated with the values in district_boundary._layers, loop is not executed. What could be the reason can anyone please help me with this?
the output of msg and msg.d is
I am guessing your JSON data is getting wrapped in a d variable. Try the following -
$.ajax({
dataType: "json",
url: "data/district.geojson",
success: function(msg) {
//console.log(msg); //try this to see whether the data is really getting wrapped in d
var data = msg.d; //msg.d contains the actual data
$(data.features).each(function(key, data) {
district_boundary.addData(data);
district_boundary.setStyle(district_boundary_styles["default"]);
});
}
});
Solved. Everything in the code is fine except the flow of execution. I was trying to use the data which would be defined later according to the flow, so in the part of script where i tried to loop through _test it is not populated yet, but when i tried in console it was after all the data was loaded and hence it worked.
I have this code snippet in .js file
$(function () {
// KeyDates
var url = "http://localhost:8732/Design_Time_Addresses/Intel.IIP.MDF.WCF/ProgramCalendarService/GetKeyDatesCalendarNew";
$.ajax({
url: url,
data: null,
type: 'POST',
contentType: 'application/json',
dataType: 'json',
success: function (GetKeyDatesCalendarDataNew) {
alert(GetKeyDatesCalendarDataNew);
$(document).ajaxStop($.unblockUI);
}
});
});
How do i process the key value pair in GetKeyDatesCalendarDataNew?
You probably want to know how to access an object's props. For that, use the for in loop to iterate over the object's values:
success: function (GetKeyDatesCalendarDataNew) {
for(var key in GetKeyDatesCalendarDataNew)
{
var value = GetKeyDatesCalendarDataNew[key];
// do somehitng based on the key and/or value iterated
}
}
For this case, the argument of the success function is the evaluated JSON that was returned from the Ajax request. Therefore GetKeyDatesCalendarDataNew, which you should rename to something like data, becomes the actual data that your server returned.
You can only process the data if you know its structure. One simple way of knowing this would be to do console.log(GetKeyDatesCalendarDataNew) and then easily process it with a for loop if it's an array or for x in.. if it's an object.
You can use JQuery "getJSON" function where you need to pass the url and specify a callback function.Your ajax call will be handled by the getJSON function. In the callback function, you can access the Keys as properties. A nice example
Lav G
$.each(GetKeyDatesCalendarDataNew,function(key,value){
//do something here
})