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

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;

Related

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);
}
});

Uncaught TypeError: Cannot read property 'Surname' of undefined [duplicate]

This question already has answers here:
React - uncaught TypeError: Cannot read property 'setState' of undefined
(20 answers)
Closed 5 years ago.
I have error although console dispays value of $("#surname").val().
May be script works before form is dynamic building?
$(function () {
$("#addEmployeForm").submit(function (event) {
event.preventDefault();
$.ajax({
url: "/api/values/",
type: "POST",
data: {
Name: $("#name").val(),
Surname: $("#surname").val(),
Age: $("#age").val(),
Salary: $("#salary").val(),
PhoneNumber: $("#phoneNumber").val(),
Department: $("#department:selected").val()
},
success: function (data) {
$("#resultSpan").html(data[1].Surname)
},
error: function () {
console.log($("#surname").val());
}
});
console.log("after ajax: " + $("#surname").val());
});
});
The error you're getting suggests the AJAX call was successful, but there is no such object as data[1] being referenced in the following code: $("#resultSpan").html(data[1].Surname). I recommend console.log(data) where you're trying to access data[1] to see what data is actually being returned from your AJAX call.

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.

How To Load JSON Data from Web Service in Ajax Url Property [duplicate]

This question already has answers here:
Populate JQuery DataTable with my json data
(4 answers)
Closed 7 years ago.
I have problem when I try to load JSON Data from web service in ajax url. So far, I code this:
<script type="text/javascript">
$('#kategoriTable').dataTable({
ajax: {
url : "http://localhost:90/kugi_deployment/api/json/reply/KategoriRetrieve",
dataSrc : function(json) {
console.log(json);
return json.Kategoris
}
},
//data : testData.Kategoris,
columns: [
{ data: "KodeKategori"},
{ data: "Nama"},
{ data: "Definisi"},
{ data: "UnsurAbstrak"},
{ data: "Alias"},
{ data: "SumberDefinisi"},
{ data: "Tanggal"},
{ data: "TipeTanggal"},
{ data: "Edisi"},
{ data: "Role"},
{ data: "OtherCitationDetail"},
{ data: "NamaKatalog"},
{ data: "NamaOrganisasi"}
]
});
</script>
The url property in ajax did not response and load the data. Here is my browser showed the error:
Can anyone help me to fix this thing? Thanks
SOLVED by myself
The main mistake I do is put the file_get_contents in function index (I am using CodeIgniter). When I put all things to another function it successfully show the data I want. Thanks

How to process JSON post response [duplicate]

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

Categories

Resources