jQuery Ajax raising TypeError - javascript

I'm having quite a hard time to figure this out. I would like to know if TypeError is caused by the second AJAX call (or the osmtogeojson.js)?
I made sure that my data in the first success function is not null by alerting it.
function sendQueryData(url, query){
url =url.replace('query' , query);
if (query === ""){
alert("City Input Required");
}else{
$.ajax({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
type: "POST",
url: "/search/pass/",
data: {
'query' : query
},
success: function(data){
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: url,
data: {
'feature': osmtogeojson(data)
},
success: function (data) {
window.location.href = url
}
});
}
});
}
}
This is the what the browser console outputs:
TypeError: e.elements is undefined
[Learn More]
osmtogeojson.js:4:2503
n http://localhost:8000/static/js/osmtogeojson.js:4:2503
u http://localhost:8000/static/js/osmtogeojson.js:4:14818
success http://localhost:8000/:235:36
i https://ajax.googleapis.com/ajax/libs/jquery/3.2.1
/jquery.min.js:2:28012
firewith https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js:2:28783
A https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js:4:14033
c/< https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js:4:16323

Related

Doing a validation check on a AJAX post and returning the error message

I have an AJAX post that does this.
$.ajax({
type: "POST",
url: "#MyWebSite.Url/myController/myView",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ myModel: myData }),
dataType: "json",
traditional: true,
success: function () {
alert('Success!');
},
error: function () {
alert('Error! ');
}
})
My controller does the validation check but it is not correctly returning the error message.
This is what my controller looks like:
if (totalQty < part.QtyInItem) {
//ModelState.AddModelError("", "My ERROR Message");
//RedirectToAction("myControler", myModel);
return this.Json(new { success = false, message = "My Error Message" });
}
When I tried adding an error to the model state it just returned "ERROR!" and not the error message I had associated with it. And when I try doing the this.JSON return it returns "success" to the view and not the error message.
How can I do this validation check for my AJAX post
You have to add data object to your function.
$.ajax({
type: "POST",
url: "#MyWebSite.Url/myController/myView",
contentType: "application/json; charset=utf-8",
data:
JSON.stringify({ myModel: myData }),
dataType: "json",
traditional: true,
success: function (data) {
alert(data.message);
},
error: function () {
alert('Error! ');
}
If you are still getting error, you should check your console for any server errors.

Jquery - $.When not trigger ajax on done menthod

Was try to implement another ajax call based on the first two results with Jquery $.When method. Basically, all three Ajax will populate a carousel on the page based on the results. Therefore I choose $.When for continuous checking. But the third Ajax which under Done() method is not called even there was no result from above two APIs or with initial values zero(0). Not sure if I missed anything!
jQuery:
let itemCat1Count = 0;
let itemCat2Count = 0;
$.when(
$.ajax({
url: "/webmethod/GetItemsCatOne",
type: "POST",
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (typeof (data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat1Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function (jqXHR, status, error) {}
}),
$.ajax({
url: "/webmethod/GetItemsCatTwo",
type: "POST",
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (typeof (data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat2Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function (jqXHR, status, error) {}
}),
).done(function (xhrSavedRings, xhrShoppingBagItems) {
if (itemCat1Count == 0 && itemCat2Count == 0) {
$.ajax({
url: "/webmethod/GetItemsSpecial",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (jObject) {
console.log(jObject);
// carousel inital codes
},
error: function (jqXHR, status, error) {}
});
}
});
Few things to highlight - $.when() requires promises as arguments. $.when does not have the powers to know when functions you passing are done or completed
From the official documentation of $.when You have return promises or return something from your ajax calls.
Here what its says => In the case where multiple Deferred objects are passed to jQuery.when(), the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed.
I have assigned a retrun value from each $.ajax call you are making. $.when will know check if there is something coming from return and is resolved then it will go to .done
Run snippet below to see the console log on .done
let itemCat1Count = 0;
let itemCat2Count = 0;
function first() {
return $.ajax({
url: "/webmethod/GetItemsCatOne",
type: "POST",
data: '',
contentType: "application/json; charset=utf-8",
success: function(data) {
if (typeof(data.ResponseObject) !== undefined && data.ResponseObject !== null) {
console.log(data.ResponseObject.Items.length)
itemCat1Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function(jqXHR, status, error) {}
});
}
function second() {
return $.ajax({
url: "/webmethod/GetItemsCatTwo",
type: "POST",
data: '',
contentType: "application/json; charset=utf-8",
success: function(data) {
if (typeof(data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat2Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function(jqXHR, status, error) {}
});
}
$.when.apply(first(), second()).done(function() {
console.log("First and Second is done running - I am from done");
if (itemCat1Count == 0 && itemCat2Count == 0) {
return $.ajax({
url: "/webmethod/GetItemsSpecial",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(jObject) {
console.log(jObject);
// carousel inital codes
},
error: function(jqXHR, status, error) {}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

how do to polling in jquery?

I have a Post call. After the result I want to do another get CALL to check the status. But only if the status is FINISHED.
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
.. now I want to do the polling on the status
jQuery.ajax({
type: "GET",
dataType: "json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
// to continue only if status if Finished
},
error: function() {
}
});
}
});
$.ajax returns a deferred object.
You can do something like below. More info here
var doSomething = $.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
function doneCallback(){
// Handle exit condition here.
doSomething();
}
function failCallback(){
// Handle failure scenario here.
}
doSomething.then(doneCallback, failCallback)
Just set your code in a function:
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
doPoll();
}
});
var doPoll = function() {
jQuery.ajax({
type: "GET",
contentType: "application/json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
//do stuff
doPoll();
},
error: function() {
//handle error
}
});
}
You can try to export the ajax call to a function and use recursion to pool.
Note: You should have a max counter so that you do not flood server with infinite calls.
var max_count = 20;
var counter = 0;
function getStatus() {
jQuery.ajax({
type: "GET ",
contentType: "application / json ",
url: " / getStatusUrl,
success: function(data, textStatus, response) {
// to continue only if status if Finished
if (textStatus != "status" && ++counter < max_count) {
getStatus();
}
},
error: function() {}
});
}

AJAX success call back not working

Here is the code I am using to access my web API controller named Owner; the success function is not being called. Any ideas?
$.ajax({
type: "GET",
url: 'http://localhost:26533/api/Owner',
contentType: "application/json",
dataType: "jsonp",
success: function (response) { alert("yes"); }
});
Remove the contentType and dataType and check the response..
Here an example:
$.ajax({
type: 'GET',
url: 'http://localhost:26533/api/Owner',
success: function(data){
alert(data);
},
error: function(xhr, type, exception) {
// if ajax fails display error alert
alert("ajax error response type " + type);
}
});
With this you can see what's wrong...

Jquery Ajax Call, doesn't call Success or Error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I return the response from an asynchronous call?
I am using Jquery Ajax to call a service to update a value.
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;//doesn't go here
},
error: function (textStatus, errorThrown) {
Success = false;//doesn't go here
}
});
//done after here
return Success;
}
and Service:
[WebMethod]
public string SavePurpose(int Vid, int PurpId)
{
try
{
CHData.UpdatePurpose(Vid, PurpId);
//List<IDName> abc = new List<IDName>();
//abc.Add(new IDName { Name=1, value="Success" });
return "Success";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
the service is being called Successfully from the AJAX. Value is also being Changed. But after the Service, success: or error: functions are not being called, in this case success should have been called but it is not working.
I used firebug and found that, the success or error functions are being skipped and goes directly to return Success;
Can't seem to find what's the problem with the code.
Update:
adding async: false fixed the problem
change your code to:
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async: false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;
},
error: function (textStatus, errorThrown) {
Success = false;
}
});
//done after here
return Success;
}
You can only return the values from a synchronous function. Otherwise you will have to make a callback.
So I just added async:false, to your ajax call
Update:
jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.
A better approach will be:
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
and call the ajax as:
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);
Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.
function foo() {
var myajax = $.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
});
return myajax.responseText;
}
You can do this also:
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
}).done(function ( data ) {
Success = true;
}).fail(function ( data ) {
Success = false;
});
You can read more about the jqXHR jQuery Object

Categories