I have this jquery autocomplete code.Everything works fine data is loaded etc.Success is working.But when i have error...error handling is not working in below code.
$("#autocomplete").on("filterablebeforefilter", function (e, data) {
if (value && value.length > 0) {
//$ul.listview("refresh");
$('.ui-responsive-panel').enhanceWithin();
$.ajax({
type: "GET",
url: "http://domain.com/food.php",
dataType: "jsonp",
crossDomain: true,
data: $(this).serialize(),
success: function (data) {
alert("success");
},
error: function () {
alert("an error occurred!");
},
beforeSend: function () {
// This callback function will trigger before data is sent
},
complete: function () {
setTimeout(function () {}, 1);
}
})
.then(function (response) {
$.each(response, function (i, val) {
//do something with data
});
}
});
As the jQuery doc states for jQuery.ajax error handler functions:
Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
It is related to the technique of JSONP where the actual request is injected as a <script> tag. So a standard jqXHR object including an ajax error event isn't available. There's some plugin as workaround available. This plugin and solutions for dealing with network timeouts are discussed e.g. in this and this stackoverflow questions.
Try handling the error in the then (or use done() and fail() )
$.ajax({
//... code omitted ...
})
.then(
function (response) {
$.each(response, function (i, val) {
//do something with data
});
},
function (error) {
//do something with error
}
});
Related
My Example works, but I want to now if it is a good way to send empty request like my example below.
$(document).ready(function () {
$("#home").click(function (e) {
// Prevent default form action
e.preventDefault();
// AJAX Request
$.ajax(
{
url: "/command/home",
type: "GET",
success: function (response) {
alert(response);
},
error: function (error) {
alert("Error!" + error);
}
});
});
});
Thank You!
I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.
Javascript code:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
var jsonStr = JSON.stringify(data);
alert(jsonStr['password']);
}
});
});
})
The response JSON code looks like this:
{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn#mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}
When im running this I only get the error function. Any suggestions or solution is appreciated :)
Basically you are converting the JSON to string and trying to access the string as object. Please don't stringify the data, and for JSON why using long code, your code should be:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.getJSON( "http://website/api/user/Mikkel1337", function( data ) {
// do something on success
alert(data.password);
});
});
});
Cheers !!!
dont need to JSON.stringify of data simple use
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
alert(data.password);
}
});
});
})
You should pass two argument for error:function(jqXHR, exception) as below.
And check once your API Url using proper way, may be your API is not show you proper result and you not get any of data from that API so that may be a reason you get error message.
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function (data) {
var jsonStr = JSON.stringify(data);
//also try this way to get JSON data:
// var jsonStr =JSON.parse(data);
alert(jsonStr['password']);
},
error: function (jqXHR, exception) {
alert("An error had occurred");
},
});
});
});
I have the following ajaxSetup configuration:
$.ajaxSetup({
type: 'GET',
headers: headers,
error: function (data, par1, par2) {
//Error handling code here
}
});
One of the members of my team wanted to handle errors in a different way in his ajax call
$.ajax({
url: url,
}).done(function (result) {
//Success code here
}).fail(function (e) {
//Error handling code here
});
The problem is that the error is getting handled in both sides, error (from ajaxSetup) and fail
To avoid double handling we add an empty Error function, like this
$.ajax({
url: url,
error: function () {},
}).done(function (result) {
//Success code here
}).fail(function (e) {
//Error handling code here
});
But it seems a bit dirty, for my mind one of them should be executed not both, so my question is how should I configure my ajaxSetup in order to avoid this "issue"?
When I pass function() { location.reload(); } as a callback - it doesn't get invoked.
$('#swapLanguageLink').click(function() {
$.post('#Url.Action("SwapLanguage", "Language")', function() { location.reload(); });
//location.reload();
});
If I un-comment //location.reload(); (instead of passing callback) - it works nice, but I am not sure if it is async or not.
It can happen that my document will be reloaded before async operation is finished, right? So why my callback doesn't work?
Edit:
$.post('#Url.Action("SwapLanguage", "Language")', null, function () {
location.reload();
}).done(function () {
location.reload();
}).error(function () {
alert('error');
});
I've tried the code above. error get invoked. But "SwapLanguage" invokes. Something really strange to me!
Something like this:
jQuery.ajax({
type: "POST",
async: true,
url: '#Url.Action("SwapLanguage", "Language")',
success: function (data) {
location.reload();
},
error: function (err)
{
alert("error");
}
});
OR
$.post('#Url.Action("SwapLanguage", "Language")', null)
.done(function(data) {
location.reload();
});
I have this problem where not all of my ajaxComplete calls are getting fired.
My Code
$(document)
.ajaxStart(function () {
$.blockUI();
})
.ajaxComplete(function () {
$.unblockUI();
});
Here's the code where ajaxComplete didn't fire :
$('body').on('click', '.actTimeSheetApprove', function () {
var node = $(this).parents('tr');
$.ajax({
url: '/TimeSheet/Approve/',
type: 'POST',
context: this,
data: {
__RequestVerificationToken: fnGetToken(),
id: $(this).data('id')
},
success: function (data) {
if (data == 'success') {
var table = $('#tblTimeSheetApprove').DataTable();
table.row(node).remove().draw();
console.log('SUCCESS'); //I already made sure this is called
}
}
})
})
Note that I already make sure SUCCESS log is called.
Any idea why?
UPDATE :
Here's my controller
[HttpPost]
[ValidateAntiForgeryToken]
[ClaimAuthorize("Role", "Manager")]
public ActionResult Approve(int id)
{
_uow.TimeSheet.Approve(id, User.Identity.Name);
_uow.Save();
return Content("success");
}
And here's my console log :
I guess that you have incorrect the "syntax" in the $.ajax call, you miss the complete...
success !== complete
https://api.jquery.com/Ajax_Events/
With ajaxStart you can use load or ajaxSetup for make the request and define the behaviour of the success/error methods;
Also for debug, try to ajaxStop() and see if everything works well.
Check the done, fail and always callbacks below.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
}).fail(function (data) {
debugger;
}).always(function(data) {
alert("complete");
});
.ajax().always(function(a, textStatus, b){});
Replaces method .complete() which was deprecated in jQuery 1.8. In response to successful transaction, arguments are same as .done() (ie. a = data, b = jqXHR) and for failed transactions the arguments are same as .fail() (ie. a = jqXHR, b = errorThrown). This is an alternative construct for the complete callback function above. Refer to deferred.always() for implementation details.
please check this link : firing in Ajax call