Accessing Ajax Response JSON Data in javascript - 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

Related

Deserialize JSON data and trim off the name and return only values

I have a JSON data loaded from database using AJAX, it has name and value pair after serializing using JavaScriptSerializer, but I need to use it without the names, only the values is needed, how can I serialize the same data without the names
AJAX CALL
$.ajax({
url: 'RhemaServices.asmx/GetMapData',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset-utf-8",
success: function (data) {
},
error: function (err) {
console.log(err)
},
complete: function () {
}
});
JSON data returned
[{"Code":"af","Total":16.63},{"Code":"al","Total":11.58},{"Code":"ve","Total":285.21},{"Code":"vn","Total":101.99}]
I need to re-serialize this data to get the below maybe looping through the data to read only the values
[{"af":"16.63","al":"11.58","ve":"285.21","vn":"101.99"}]
This is what I am trying to do with the AJAX JSON data, but its not working
var datas = [];
data.map(function (item) {
var newdata = item.Code + ":" + item.Total;
datas.push({ newdata });
})
Since your requested data is an object, I suggest you use forEach instead of map and create your properties as such:
let data = [{"Code":"af","Total":16.63},{"Code":"al","Total":11.58},{"Code":"ve","Total":285.21},{"Code":"vn","Total":101.99}];
var datas = {};
data.forEach(item => datas[item.Code] = item.Total);
console.log(datas);
// {"af":16.63,"al":11.58,"ve":285.21,"vn":101.99}
Is data coming all together as a single string? Then it's as simple as
var datas;
...
success: function (data) {
datas = JSON.parse(data);
}
Not sure what you mean by trim off the name ,only values - but you can do with the JavaScript object whatever you want

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 to set values to array when async webservice responce is called

Friends,
I have declared array in javascipt
var Answer1 = new Array(50);
I want to call webserivce using $ajax & i want to store its response at appropriate index of array.
& want to use that array immediately after all the values are set.
Currently i am doing this by using async:false property of $ajax .
Does anyone know way with asynchrnous way because when i use asynchronous values of array remains undefined.
for(var j=0;j < mycollection.length-1;j++)
{
$.ajax({
type: 'GET',
url: webserviceURL,
dataType: 'json',
error: function(data)
{
//alert(data.error);
},
success: function(data)
{
if(data.error!=null)
{
console.log('data error');
Answer1[j] = data.name;
}
},
complete: function(data)
{
alert('completed:');
},
data: {},
async: false
});
Well you are using the wrong index for Answer1:
Answer1[i] = data.name;
should be:
Answer1[j] = data.name;
But if that still doesn't work, pass j as a parameter to your webservice and get the webservice to return it as part of the response so you know the index to assign to.
Also you are only assigning if data.error is not null? Is that what you want, didn't you want to assign if there is no error (i.e. data.error is null)?
Put whatever code uses the array into a function. Call that function from the success handler for your Ajax call.

Passing a javascript array to a php page using post method

I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.

Categories