How to process JSON post response [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I am receiving the following successful response :
{"123abc": {"lat": 101.45, "lon": 777.87},"uid345":{"lat":12.09,"lon":98.08}}
After posting this jquery ajax request :
$.ajax({
url: postUrl,
type: 'POST',
beforeSend: function () {
$.mobile.loading('hide');
},
complete: function () {
$.mobile.loading('hide');
},
crossDomain: true,
data: {
lat: 101.45,
lon: 777.87,
uid: '123abc'
},
dataType: 'json',
success: function (dataString) {
alert(dataString);
},
error: function (error) {}
});
alert(datastring); prints [object object] in a alert window.
How can I process the received response?
p.s: I just completed a udacity web development course and this is new to me.

Use the console to check your response, that way you can expand the object out and what fields are available:
console.log(dataString);
There are a number of options for processing depending on what you want to do. The most used is iterating over your objects keys and displaying the appropriate info via a for in or $.each loop.
To iterate the lat and lon of each object, something like below will work:
for (var key in dataString) {
console.log(dataString[key].lat);
console.log(dataString[key].lon);
}

access properties as datastring.lat Or datastring.[0].lat. You'll get the gist how to access other's
If the later is true,
Do loop on datastring till datastring.length

Related

unable to fetch the JSON Data using jquery in ajax [duplicate]

This question already has answers here:
JavaScript "cannot read property "bar" of undefined [duplicate]
(4 answers)
Closed 4 years ago.
I am unable to fetch the JSON data using jquery in ajax.Getting Uncaught TypeError: Cannot read property 'customers' of undefined error.
<script type="text/javascript">
$("#savechanges").click(function(e) {
e.preventDefault();
jQuery.ajax({
url: "<?=base_url()?>customers/updatecustomerorderdetail",
data: $('#savecustomer input').serialize(),
type: "POST",
dataType: 'json',
beforeSend: function() {
//$("#update_"+id).html('');
$("#savechanges").html('<i class="fa fa-spinner fa-spin"></i>updating...');
},
success:function(data){
var customer_name = data[0].customers[0].customer_name;
alert(customer_name);
console.log(data);
},
error:function (error){
console.log(error);
}
});
});
JSON response from the above code
{
"customers":[
{
"customer_id":22,
"customer_name":"fggfd",
"customer_email":"fggd",
"customer_mobile":"dfgf",
"updated_user_id":"5",
"updated_datetime":"2018-07-30 21:00:57"
}
]
}
I want to alert customer_name from the JSON data in the success function of ajax. can anyone please tell me what I am doing wrong here?
Your data is an object clearly not an array so do this:
data.customers[0].customer_name;

Cannot consume web service with JQuery (console issues cors but xml is returned) [duplicate]

This question already has answers here:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
(13 answers)
Closed 5 years ago.
I am trying to consume a web service with JQuery and I am getting the weird result of the browser showing cors error on the console while in the response tab I can see the returned XML.
See my console
See my response
The web service that I am trying to access calculate the freight of products.
I don't know how web services work, It's strange that it is blocked somehow, as the purpose of web services is to provide access to applications.
Here is the code I am trying to execute:
<script>
$().ready(function () {
var sendjson = {
"nCdEmpresa": "",
"sDsSenha": "",
"nCdServico": "41106",
"sCepOrigem": "37540000",
"sCepDestino": "37540000",
"nVlPeso": "1",
"nCdFormato": "1",
"nVlComprimento": "20",
"nVlAltura": "5",
"nVlLargura": "15",
"nVlDiametro": "0",
"sCdMaoPropria": "s",
"nVlValorDeclarado": "200",
"sCdAvisoRecebimento": "s"
}
$.ajax({
type: "GET",
cors: true,
url: "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx/CalcPrecoPrazo",
data: sendjson,
dataType: "application/xml",
success: function (data) {
console.log(data);
},
error: function (data, err)
{
alert(err);
}
});
});
</script>
If someone can give me directions how to consume this web services I will be very glad. The answer can be in C# too, using HttpClient or whatever.
you need to replace your ajax call parameters
cors : true to crossDomain: true,
dataType: 'application/xml' to contentType : 'application/xml'
Ajax Call :
$.ajax({
type: "GET",
crossDomain: true,
url: "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx/CalcPrecoPrazo",
data: sendjson,
contentType : 'application/xml',
success: function (data) {
console.log(data);
},
error: function (data, err)
{
alert(err);
}
});

Handling Facebook response [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 10 months ago.
I've got this code to handle Facebook response:
if (response && !response.error_message) {
alert('Posting completed with Post ID:' + response.post_id);
FB.api( '/' + response.post_id, function( response ) {
x$().xhr('<?php echo Yii::app()->createUrl('survey/saveSocialMediaPost', array('answer_id'=>$answer->id, 'social_network'=>1)); ?>', {
method: 'POST',
async: true,
meta: response,
});
console.log( response );
});
} else {
alert('Error while posting.');
}
}
As you can see, after a right post what I want to do is call an ajax to do some actions in my database. The problem here is that I don't know how to handle the response. console.log(response) throws something like that:
Object { created_time: "2016-03-05T01:27:27+0000", message: "Prueba de comentarios.", id: "xxxxxx_xxxxx" }
Exactly what I need to get is message. id is solved with response.post_id.
How about this:
console.log(response.message);
It´s a simple JSON object, you should get familiar with JSON - it´s very important in the JavaScript world.

JSON parsing in javascript, the data is always undefined [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
I am currently trying to parse a random JSON file online, you can try the link and look at it for yourself. No matter what I look for, I always get 'undefined' when accessing the data. I just want to get some sort of output from the json. For example, how can I get the list of names ('nm') in the file? No matter what I do, it always gives me undefined.
$.ajax(
{
type: 'GET',
url: 'http://mysafeinfo.com/api/data?list=englishmonarchs&format=json',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(r)
{
alert(r.example);
}
});
The data fetched from that API is an array of objects like this.
[{
nm: "Edward the Elder",
cty: "GB",
hse: "House of Wessex",
yrs: "899-925"
}, {
nm: "Athelstan",
cty: "GB",
hse: "House of Wessex",
yrs: "925-940"
}]
One of the ways to iterate over the array of objects is $.each
success: function(r)
{
$.each(r, function(index, value){ // iterating over each object
console.log(value.nm); // <---- accessing nm of each object
});
}
You are not iterating upon the result set.
This is much shorter and readable.
$.getJSON("http://mysafeinfo.com/api/data?list=englishmonarchs&format=json", function (data) {
$.each(data, function (index, value) {
alert(index + ": " + value.nm);
});
});
http://jsfiddle.net/5skony7y/2/
Open the Chrome console and you will see the following:

Unable to get value from json object

I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id

Categories

Resources