I have the following jQuery which does not give the most descriptive error messsages...
url: 'server_page.aspx',
type: 'POST',
data: { intID:$(this).attr("id"), strState:"1" },
error: function() { alert('Error'); },
success: function() { }
How do I get more descriptive error messages if it is possible?
EDIT:
This is the full javascript:
$(document).ready(function(){
$("input:checkbox").change(function() {
var that = this;
if($(this).is(":checked")) {
$.ajax({
url: 'favorite_on_off.aspx',
type: 'POST',
data: { strFavoriteID:$(that).attr("id"), strState:"1" },
timeout: 1000,
error: function(xhr, status, error)
{
alert("values: strFavoriteID: " + $(that).attr("id") + " strState: " + "1");
alert('Error: ' + status + '\nError Text: ' + error);
},
success: function() { }
});
} else {
$.ajax({
url: 'favorite_on_off.aspx',
type: 'POST',
data: { strFavoriteID:$(that).attr("id"), strState:"0" },
timeout: 1000,
error: function(xhr, status, error)
{
alert("values: strFavoriteID: " + $(that).attr("id") + " strState: " + "0");
alert('Error: ' + status + '\nError Text: ' + error);
},
success: function() { }
});
}
});
});
These are the error messages:
values: strFavoriteID: c:\folder\document.doc strState: 1
Error: error
Error Text: undefined
You can use all of the arguments passed to the error callback, for example:
error: function(xhr, status, error) {
alert('Error: ' + status + '\nError Text: ' + error);
},
The second argument provided to the error callback is textStatus, which should contain a description of the error:
error: function(xhr, textStatus) { alert(textStatus); }
Note that you should probably not provide this information to your users. Parse the message using Javascript and give them a nice friendly message explaining the error.
I have this method:
function HandleAjaxError(request, status, error) {
var ex = eval("(" + request.responseText + ")");
$('body').addClass("ui-widget-overlay");
alert(ex.Message);
$('body').removeClass("ui-widget-overlay");
}
$.ajax({
type: "POST",
url: window.location.pathname + "/DoStuff",
data: "{}",
success: Success,
error: HandleAjaxError
});
This way, I can gracefully handle the error message (and possibly the status code) on the ASP.NET side. I usually log the original error, then throw a custom/descriptive one for the client.
Related
I have a function to add a record to database that uses Ajax with C# web service. Prior to updating DB I call another function to validate input that also uses Ajax. So, I need the validate function to finish before continuing with the one adding the record.
I know due to asynchronous nature of ajax I have to use promise/deferred but just can't get my head wrapped around it to set it up properly.
Updated
function validate() {
var deferred = $.Deferred();
$.ajax({
url: "path/to/web/service",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: params,
}).done(function (result) {debugger
if (!result || result.d === "") {
isValid = false;
}
else {
var duplicate = JSON.parse(result.d);
switch (duplicate) {
case DuplicateData.Name:
isValid = false;
break;
case DuplicateData.ID:
isValid = false;
break;
}
}
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
deferred.resolve(isValid);
return deferred.promise();
//return isValid;
}
$(document).on("click", "#btnAdd", function (event) {debugger
$.when(validate())
.then(function(isValid) {
if (isValid) {
$.ajax({
url: "path/to/another/webservice",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: some_param,
}).done(function (result) {
addNewRecord();
)}.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
}
})
});
function addNewRecord(){
// add record to DB
}
As you are only dealing with a boolean result, there is no reason to return a value, you can just resolve or reject the deferred.
function validate() {
var $defer = $.Deferred(function() {
$.ajax({
url: "path/to/web/service",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: params,
})
.done(function (result) {
// If there's no result
if (!result || !result.d) {
$defer.reject();
}
else {
// This call shouldn't be necessary, as dataType: "json" will call it for you
// Unless you double-encoded it.
var duplicate = JSON.parse(result.d);
// Not sure about this part, what's DuplicatedData and what does result.d contain?
switch (duplicate) {
case DuplicateData.Name:
case DuplicateData.ID:
$defer.reject();
}
}
// Everything checks out, resolve the promise
$defer.resolve();
})
.fail(function (jqXHR, textStatus, errorThrown) {
// If there was a network or server error
// alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
$defer.reject();
});
});
return $defer;
}
$('form').on("click", "#btnAdd", function (event) {
validate()
.done(function() {
// If the validation passes
$.ajax({
url: "path/to/another/webservice",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: some_param,
})
.done(function (result) {
// Creation successful
addNewRecord();
}).fail(function (jqXHR, textStatus, errorThrown) {
// Creation failed
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
})
.fail(function(reason) {
// Called in case of a validation error
console.log("Validation error");
});
});
Hi this code is working great, i am new in javascript ,what i am trying to do , print js default error message in my div.
<script type="text/javascript">
$(document).ready(function () {
var contranumber = <?php echo json_encode($data); ?>;
debugger;
if(contranumber)
{
$.ajax({
url: ApiUrl+'ActivateUser?contraNumber='+contranumber,
type: 'get',
success: function (data, xhr) {
alert(data.ErrorMessage);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
}else
{
}
});
</script>
<div><center>javascript message</center></div>
<center><h3> Check your Email</h3></center>
A few quick things first:
Remove center tags, as it is deprecated. (Official example is "No, really, don't use it.")
Remove debugger;, unless you want your browser to stop.
Give your elements some sort of identification, be it a class or ID.
$(document).ready(function() {
var contranumber = '{ "hello": "world" }';
var message = $('.message'); // the element the message will go in
if (contranumber) {
$.ajax({
url: ApiUrl + 'ActivateUser?contraNumber=' + contranumber,
type: 'get',
success: function(data, textStatus, xhr) { // you missed the textStatus parameter
message.text('it was successful'); // why log an error on success?
},
error: function(xhr, textStatus, errorThrown) {
message.text('Error in Operation:' + errorThrown); // give the actual error text
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message"></div>
<h3>Check your Email</h3>
$('#example center').text(data.ErrorMessage);
I usually do this:
$.ajax({
type: 'POST',
url: validateAjaxURL,
success: function (data) {
var returnData = data;
if (returnData.match("^selectedUno-")) {
$('#new_caregiver_popup_div').dialog('close');
} else {
$("#new_caregiver_popup_div").html(data);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
UPDATE :
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#DivID').text(errorThrown);
}
Here is the link for your reference :
Show Error
Hi I have a JQuery Function that is calling a controller when
Controller Response (success()) it is loading an iFrame;
Basically; converter is returning success function after 30 seconds, for that reason I am trying to display a loading image using
beforeSend: function()
{
},
Function I tried a lots but its not working; Could you please give me advice how can I achieve it. My code are given bellow:
var callController = function (FirstName, documentId, fileName, packet) {
$.ajax({
type: "POST",
url: "http://localhost:63902/Home/Preview?DocumentId=" + documentId + "&FileName=" + fileName + "&packet=" + packet,
cache: false,
async: false,
//controller happens...
success: function (returnedValue) {
rememberDocumentId(documentId);
location.reload("#mainIframe");
setTimeout(function () {
}, 3000);
document.getElementById("mainIframe").style.display = "none";
document.getElementById("documentIframe").style.display = "block";
document.getElementById("documentIframe").src = "http://localhost:63902/FileProcessing/PDFProcessing/TempPDF/" + returnedValue;
event.preventDefault();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + " " + textStatus + " " + errorThrown);
}
});
};
you can show your loader right after or before $.ajax({...}) but you should never use async:false, this is the root of evil, it will freeze the browser while the request has not succeeded.
like this:
var callController = function (FirstName, documentId, fileName, SL) {
//here
showLoader();
$.ajax({
type: "POST",
url: "http://localhost:63902/Home/Preview?DocumentId=" + documentId + "&FileName=" + fileName + "&SL=" + SL,
cache: false,
//controller happens...
success: function (returnedValue) {
rememberDocumentId(documentId);
location.reload("#mainIframe");
setTimeout(function () {
}, 3000);
document.getElementById("mainIframe").style.display = "none";
document.getElementById("documentIframe").style.display = "block";
document.getElementById("documentIframe").src = "http://localhost:63902/FileProcessing/PDFProcessing/TempPDF/" + returnedValue;
//hide Here
hideLoader();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + " " + textStatus + " " + errorThrown);
//hide Here
hideLoader();
}
});
}
So I have an ajax script that runs, it looks like this:
jQuery.ajax({
url: 'http://localhost/?page_id=104256',
type: 'POST',
data: { name : 'name2' },
success: function (data) {
alert(data);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details0: " + desc + "\nError:" + err);
},
});
This runs fine but returns a 404 from the page set as the 'url'
If I remove 'type: post'
Here your method: 'Post', Type is something what you want to get in return like text
jQuery.ajax({
url: 'http://localhost/?page_id=104256',
method: 'POST',
data: { name : 'name2' },
success: function (data) {
alert(data);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details0: " + desc + "\nError:" + err);
},
});
If type: 'POST' is omitted, jQuery is treating it like a GET request, which it defaults to see the docs, where the resource may not exist therefore resulting in a the 404 you're seeing.
It turns out I forgot to add the name="" parameter in my input types. Doh!
How can i checkstatus of ajax response to wait and check that it has changed from 200 -->500 -->200?
it has to be checked and recheck. Mine isnt working correctly here my code below.
NoTe: On succesfull form submission it will always be 200 .. so it need to check and recheck for 500 and then for 200 before redirecting to the mainpage again.
I tried to create checkstatus function so i can resuse. how can this be done correctly?
// setTimeout(function() { location.reload(true);}, 3000);
function checkStatus() {
/*** Re check bit ***/
var restartCheck = window.setInterval(
$.ajax({
// dataType : 'jsonp',
//jsonp : 'js',
url: "../../../../../rest/configuration",
beforeSend: function (jqXHR, settings) {
console.info('in beforeSend');
console.log(jqXHR, settings);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(" 500 top data still loading " + jqXHR + " : " + textStatus + " : " + errorThrown);
console.info('in error');
console.log(jqXHR, textStatus, errorThrown);
},
complete: function (jqXHR, textStatus) {
alert(" complete " + jqXHR + " : " + textStatus);
console.info('in complete');
console.log(jqXHR, textStatus);
},
success: function (data, textStatus, jqXHR) {
window.clearInterval(restartCheck);
alert(" success " + jqXHR + " : " + textStatus);
console.info('in success');
console.log(data, textStatus, jqXHR);
}
}), 3000); //This will call the ajax function every 3 seconds until the clearInterval function is called in the success callback.
/*** recheck bit **/
}
/**
On initial success form submission the success values is 200.
After that I need to wait sometimes to check and recheck for 500 for server starts, when the Server restarts or is restarting it gives a 500 internal server message, it take about 30 to 40 sec or more to restart the server so i have await time for 30 sec.. Once the server restarts it gives a 200 success server message. and then redirect the page . SO i am trying to checkstatus until it changes from 200 --> 500 -200
**/
$.ajax({
type: "POST",
url: "foo.json",
data: json_data,
contentType: 'application/json',
success: function (data, textStatus, xhr) {
console.log(arguments);
console.log(xhr.status);
alert("Your changes are being submitted: " + textStatus + " : " + xhr.status);
$('#myModal').modal('hide');
$('#myModal-loading').modal('show');
//call function checkstatus not currently workign
//statsu val ==200 server inital form success val from server
setTimeout(function () {
count=0;
var statusval = checkStatus();
while(statusval == 200 and count <=5) {
statusval = checkStatus();
//statsu val has changed to 500 server is restarting
if (statusval==500) {
//wait for 30 sec to recheck if the server has restarted and changed to success ie 200
setTimeout(function () { checkStatus();}, 30000);
}
count++;
}, 3000);
alert("restartCheck " + restartCheck)
setTimeout(function () {
location.reload(true);
}, 3000);
// $('#myModal-loading').modal('hide');
$('<div id="loading">Loading...</div>').insertBefore('#myform');
//location.reload(true);
},
error: function (jqXHR, textStatus, errorThrown) {
// alert("Warning and error has occured: "+errorThrown + " : " + jqXHR.status);
alert(jqXHR.responseText + " - " + errorThrown + " : " + jqXHR.status);
}
});
});
});
Give this fiddle a try.
HTML:
<div></div>
Code:
function waitForStatus(url, status, maxRetries, success, failure) {
var count = 0;
var restartCheck = setInterval(function() {
count++;
if (count <= maxRetries) {
$.ajax({
url: url,
type: "POST",
complete: function (jqXHR, textStatus) {
if (jqXHR.status == status) {
clearInterval(restartCheck);
success(status);
}
}
});
} else {
clearInterval(restartCheck);
failure();
}
}, 3000);
}
var successCallback = function(status) {
$("div").append('<p>SUCCESS: returned ' + status + '</p>');
};
var failureCallback = function() {
$("div").append('<p>FAILURE: max attempts reached</p>');
};
// This will succeed
waitForStatus('/echo/xml', 200, 5, successCallback, failureCallback);
// This will fail
waitForStatus('/echo/xml/404', 200, 5, successCallback, failureCallback);