Call ajax.fail() from ajax.success() - javascript

So all I want to do is conditionally call the .fail method from within the .success method, how?
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { ajaxCall.fail(); return; }
alert("success");
})
.fail(function () {
alert("fail");
});

$.ajax return a promise so you can't do it directly. Your best shot is that :
var fail = function () {
alert("fail");
};
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { fail(); return; }
alert("success");
})
.fail(fail);

You can simply call as this.fail(); as shown below :-
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail")
{
this.fail();
return;
}
alert("success");
})
.fail(function () {
alert("fail");
});
For more information :-
http://www.youlikeprogramming.com/2013/07/jqueryajax-conditionally-call-error-method-fro-success/

just use the "this" keyword to actually call any other method of the ajax call, I have made a sample for error method.
$.ajax({
url: 'url',
dataType: 'json',
contentType: 'application/json; charset=utf-8;',
type: 'GET',
success: function (dataReturn) {
this.error('error called explicitly');
},
error: function (errorMessage) {
if(errorMessage.ResponseText) // or directly compare as errorMessage !== "error called explicitly" if u send the same message elsewhere
//actual error code
else
alert(errorMessage);
}
});
hope this helps :)

Related

Check(validate) send form data with ajax

I,m try check(validate) form data by using AJAX.
First i create callback function with AJAX request(in my example it's field time)
When i found same record in database, my NodeJS server response with value false, it's means we have record and we don't need add second record with that time).
My problem is that the form is still sent, regardless of the server response.
here my code(front end)
function funABC(mdata,callback){
console.log(mdata);
$.ajax({
url:'/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data:mdata,
success: callback ,
// error:callback,
});
}
$('.addForm').on('submit', function (event) {
let form = $('.addForm');
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
// return false;
}
event.preventDefault();
checkdata = {
time_show : document.querySelector('.addForm').elements.time_show.value
}
functABC(checkdata,function(result) {
console.log(result);
if (result == 'true') {
alert(`For time: ${checkdata. time_show} there is already an event, choose a different time`);
return false;
}
})
form.addClass('was-validated');
some operations with form data, then send with ajax
$.ajax({
type: "POST",
url: "/dashboard/materials/add",
dataType: "json",
contentType: "application/json",
success: function (data) {
setTimeout(location.href = '/dashboard/materials', 10000);
},
data: JSON.stringify(formdata)
});
});
How and where did you call that post request ?
May be you would need to move post request into the callback
function funABC(mdata, callback) {
console.log(mdata);
$.ajax({
url: '/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data: mdata,
success: callback,
// error:callback,
});
}
$('.addForm').on('submit', function(event) {
let form = $('.addForm');
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
// return false;
}
event.preventDefault();
checkdata = {
time_show: document.querySelector('.addForm').elements.time_show.value
}
functABC(checkdata, function(result) {
console.log(result);
if (result == 'true') {
alert(`For time: ${checkdata. time_show} there is already an event, choose a different time`);
return false;
} else {
$.ajax({
type: "POST",
url: "/dashboard/materials/add",
dataType: "json",
contentType: "application/json",
success: function(data) {
setTimeout(location.href = '/dashboard/materials', 10000);
},
data: JSON.stringify(formdata)
});
}
})
form.addClass('was-validated');
});
Or you could async false for validation request
$.ajax({
url: '/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data: mdata,
success: callback,
async: false,
// error:callback,
});

Html for response when i want a string

I have the function below:
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
const dataValue = { "markdownFormat": markdownFormat }
$.ajax({
type: "POST",
url: requestUrl,
data: dataValue,
contentType: "application/json: charset = utf8",
dataType: "text",
success: function (response) {
alert(response);
document.getElementById("generatedPreview").innerHTML = response;
},
fail: function () {
alert('Failed')
}
});
}
And i have this on my server:
[WebMethod]
public static string GenerateHtmlFromMarkdown(string markdownFormat)
{
string htmlFormat = "Some text";
return htmlFormat;
}
I have on response html code, not the string that i want. What am I doing wrong?
And if i change the "dataType: json" it doesn't even enter either the success nor fail functions
Your data type of ajax must be json like this
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
var dataValue = { "markdownFormat": markdownFormat }
$.ajax({
type: "POST",
url: requestUrl,
data: JSON.stringify(dataValue),
dataType: "json",
success: function (response) {
alert(response);
document.getElementById("generatedPreview").innerHTML = response;
},
error: function () { alert("Failed"); }
});
}
try with this.
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
var obj={};
obj.markdownFormat=markdownFormat;
$.ajax({
type: "POST",
url: requestUrl,
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
document.getElementById("generatedPreview").innerHTML = response.d;
},
failure: function () {
alert('Failed')
}
});
}

Nested Promise structure

I have a javascript function with two promises:
uploadDocument = function (formData, order) {
$.ajax({
type: "POST",
url: "/API/Documents/addDocument",
data: formData,
contentType: false,
processData: false
}).then(function (documentID) {
order.referenceID = documentID;
return $.ajax({
type: "POST",
url: "/API/Documents/addOrder",
data: ko.toJSON(transaction),
contentType: "application/json"
});
}).then(function (result) {
return 'success';
});
}
That works perfectly, the API calls success.
the call to the function is:
uploadDocument(formData, order).then(function (data) {
console.log('success');
})
At this point I'm getting an error:
Uncaught TypeError: Cannot read property 'then' of undefined
What am I doing worng?
You need to return your $.ajax() and then use then on it. Without return the function returns undefined by default, so why you get an error. See return before $.ajax(...).then(...).
uploadDocument = function (formData, order) {
return $.ajax({
type: "POST",
url: "/API/Documents/addDocument",
data: formData,
contentType: false,
processData: false
}).then(function (documentID) {
order.referenceID = documentID;
return $.ajax({
type: "POST",
url: "/API/Documents/addOrder",
data: ko.toJSON(transaction),
contentType: "application/json"
});
}).then(function (result) {
return 'success';
});
}

Ajax method to a webmethod in asmx is not firing

I have a strange problem with the below AJAX jQuery method to call a webmethod in an asmx service. It's not firing when I try to call it, but the moment I uncomment any of the alert in code to debug, it works all of sudden.
It confuses me, what would be the problem? Am I missing something here..
Code:
var endXsession = function() {
var fwdURL = "";
$.ajax({
type: "POST",
url: "Session.asmx/RemoveSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msge) {
//alert(msge.d);
fwdURL = msge.d;
},
error: function(response) {
//alert(response.responseText);
fwdURL = response.responseText;
}
});
//alert(fwdURL);
return fwdURL;
};
response.responseText is undefined ... it's response.statusText ..
function endXsession() {
var fwdURL = "";
$.ajax({
type: "POST",
url: "Session.asmx/RemoveSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msge) {
// alert(msge.d);
fwdURL = msge.d;
}
,
error: function (response) {
// alert(response.statusText);
fwdURL = response.statusText;
}
});
// alert(fwdURL);
return fwdURL;
}
console.log(endXsession());

Ajax Response is not defeined

I am quite green when it comes to AJAX and am trying to get an email address from an ASP.Net code behind function
When using the below code I am getting the error as per the title of this issue.
This is the code I am using
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: '{id: "' + $("txtRequester").val + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
});
which is an adaptation of the code from this site.
ASP.Net Snippets
When changing the line
success: OnSuccess to success: alert(response) or success: alert(data)
I get the error up, but if I use success: alert("ok") I get the message saying ok so I suspect that I am getting into the function as below.
<System.Web.Services.WebMethod()> _
Public Shared Function FindEmailAddress(ByVal id As String) As String
Dim response As String = GetEmail(id)
Return response
End Function
I would be extremely grateful if someone to help me and let me know where I am going wrong on this one.
thanks
I think you have can check the state of failure by using this code below as I think there is wrong syntax used by you.
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: JSON.stringify({id: ' + $(".txtRequester").val() + ' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status, header){
console.log(data);
},
error: function (response) {
alert(response.d);
}
});
}
});
then definitely you will get error response, if your success won't hit.
You have not called the function thats why its never get called.
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
ShowCurrentTime();
});
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: '{id: "' + $("txtRequester").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
Onsuccess(response);
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
This will help :)
use ajax directly ,
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
var cond = $(".txtRequester").val();
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: {id:cond},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response){
alert(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});
Change $('.txtRequester') to $('#txtRequester')
and
Change $("txtRequester").val to $('#txtRequester').val()

Categories

Resources