I'm trying to call a function when I get success from my ajax call, but it's not working. This is what I've tryed so far.
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d) {
console.log(dt);
console.log(msg.d);
buildTableBody(dt, msg.d);
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
function buildTableBody(dt, obj) {
dt.fnClearTable();
data = [];
$(obj).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
}
Thanks in advance!
Edit #1
I used console.log in order to show you what I got from dt and msg.d (Image)
Edit #2
If I paste the commands from buildTableBody function in the success: handler instead of calling buildTableBody function in the success: handler it actually works:
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
dt.fnClearTable();
data = [];
$(msg.d).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
But it makes no sense to me, since this actually should work in both ways.
Pretty sure you have a typo on your function call
buildTableBody(td, msg.d);
should be
buildTableBody(dt, msg.d);
Also what is the return type from Index.aspx/getMRPReasonCodeReport? If it is string, you've got to unescape the string before you can treat it as JSON.
Try removing contentType : "application/json utf-8" from your AJAX call. That is the type of the data sent to the server. It is likely that you want the default content type.
Unless your server-side resource was configured to accept json it likely accepts application/x-www-form-urlencoded
http://api.jquery.com/jQuery.ajax/
Related
I am posting some JSON info using the code below. Currently, if it is successful (200 response) the alert pops up, but if it is unsuccessful nothing happens.
What I would like to do is basically say if successful do X, else do Y.
I have try using an if / else statement within the function, but it doesn't seem to work.
Apologies if this is a silly question, I am new to working with JSON, XHR etc. Any assistance would be greatly appreciated.
jQuery["postJSON"] = function(url, data, callback) {
if (jQuery.isFunction(data)) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify(data),
success: callback
});
};
$.postJSON(
"https://test.com",
data,
function(data, status, xhr) {
alert("Success");
}
);
EDIT: Working Code:
jQuery["postJSON"] = function(url, data, callback) {
if (jQuery.isFunction(data)) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify(data),
success: callback,
error: function(xhr, ajaxOptions, thrownError){
alert(thrownError);
});
};
$.postJSON(
"https://test.com",
data,
function(data, status, xhr) {
alert("Success");
}
);
add this line to your return jQuery.ajax({}) function:
error: function(xhr, ajaxOptions, thrownError){
window.alert(thrownError);
}
hope this helps~
Hello everyone and thanks for your time.
Here is my javascript:
$('.sender').click(function (e) {
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: { firstName: 'stack', lastName: 'overflow' },
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: function (response) {
alert('success');
},
error: function (response) {
alert('error: ' + response);
console.log('err: '+response);
}
});
});
And here is the code in my .ashx handler:
public void ProcessRequest(HttpContext context)
{
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//to fix the allow origin problem
context.Response.ContentType = "text/plain";
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
While the click event is working, my Ajaxrequest doesn't seem to get any response as the alert at success doesn't popup. I've debugged using the browser's network console and it return the expected response but it doesn't seem to reach the success function in the JavaScript code. Any insights or suggestions are welcome. Thanks.
In case you are still interested in the answer, try this before doing the request
var data = { firstName: 'stack', lastName: 'overflow' };
var jsonData = JSON.stringify(data);
and change your AJAX request to
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: jsonData,
dataType: 'json',
contentType: 'application/json; charset-utf-8'
})
.done(function (response) {
// do something nice
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("request error");
console.log(textStatus);
console.log(errorThrown);
});
Explanation
You are trying to send the plain data object. You must transform it into a Json string using JSON.stringify(object).
Changing the dataType isn't really a solution but a workaround.
Additional Notes
Also, I think you should use .done() and .fail(). See here for further details.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return the response from an AJAX call from a function?
function Run(someJsonObject) {
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
return true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
return false;
}
});
}
var result = Run({dummy:'dummy'});
If I'm not mistaken, the above function will not return true or false, but rather it will be undefined. I want to return the result of the AJAX call, I'd prefer to make it synchronous (I realize I'm using AJAX). How would I accomplish this?
You are backwards, let your ajax run first.
$(function () {
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
DoStuffWithResult(data.d);
return true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
return false;
}
});
});
function DoStuffWithResult(result){
//time to rock, i have my result
}
If you add the async option to your jquery call, it stops being asynchronous.
That being said, this is usually a bad idea and can probably be handled a better way. Usually, this is done by doing your ajax call first and working with your data in your success function.
If you are really adamant about doing it this way, though, this is what you want:
function Run(someJsonObject) {
var result;
$.ajax({
async: false,
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
result = true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
result = false;
}
});
return result;
}
var result = Run({dummy:'dummy'});
If you want to make an ajax request in jquery synchronous and have it be the return value of Run:
function Run(someJsonObject) {
var returnValue;
$.ajax({
type: "post",
async: false,
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
returnValue = true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
returnValue = false;
}
});
return returnValue;
}
I added async: false to the ajax options and used a local variable (accessible to the success and error handlers) as the return value.
You can't just return $.ajax(/* snip */) because that returns a promise object.
You can simplify
$.post('/MyWebService', JSON.stringify(someJsonObject), function(r) {
if(r.success) {
// do something (1)
} else {
// do else something (2)
}
},'json').error(function() {
alert('comunication error');
});
If you get any response like this
{ "success": true, data: "my_data" }
execute something (1)
else (2)
If not a valid json or timeout trigger .error()
I have the code to prevent postback but failed. Basically I have an asp.net button.
<asp:Button ID="btnSave" runat="server" Text="SaveChanges" OnClick="btnSave_Click"
CssClass="saveButton" ValidationGroup="answer" OnClientClick="return ValidateUserNameBeforeSubmitting();" />
And ajax call web service.
function ValidateUserName() {
$.ajax({ type: "POST",
url: "../UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': '" +JSON.stringify( $("#<%=TextUserName.ClientID%>").val()) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
return data.d;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function ValidateUserNameBeforeSubmitting() {
var isValid = ValidateUserName();
return isValid;
}
The web service will return a boolean value and it does when I step into the code.
However when I stepped into the javascript code, I found that "isValid" is not a boolean value. It is "undefined".
Why?
Thanks.
Ajax is asynchronous.
var isValid = ValidateUserName();
this line executes, but function you're calling has no return (hence undefined)
if you want to access a variable returned from ajax, it needs to be in the success handler.
function ValidateUserName() {
var returnValue;
$.ajax({ type: "POST",
...
async: false,
success: function (data) {
returnValue = data.d;
},
...
});
return returnValue;
}
isValid is undefined because ValidateUserName() doesn't actually return anything.
Change the ajax call to this
function ValidateUserName() {
var results = $.ajax({ type: "POST",
url: "../UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': '" +JSON.stringify( $("#<%=TextUserName.ClientID%>").val()) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false
});
return results;
//or results.d; if thats what you need for the boolean
}
When the ajax is marked as async:false the result of the ajax call contains your result. Rather than it being passed to a success function
Scope a return variable so all paths return and make sure your ajax call return a bool:
function ValidateUserName() {
var result = false; //default
$.ajax({ type: "POST",
url: "../UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': '" +JSON.stringify( $("# <%=TextUserName.ClientID%>").val()) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
result = data.d; //make sure this is a bool
//result = Boolean(data.d); //use this if returning a string, not recommended though
alert(result); //are you a bool?
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
return result;
}
function ValidateUserNameBeforeSubmitting() {
var isValid = ValidateUserName();
return isValid;
}
I have a javascript function which makes a JSON call to a web service using jQuery.
In the success function I need to evaluate the JSON response and if necessary make another call to a different method in the same web service.
Here is how I do it:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
end = endFunction(aid);
if (end) {
// do some other stuff
}
}
},
failure: function (errorMsg) { alert(errorMsg.toString()); }
});
}
and the endFunction which is being called from within the ajax success function:
function endFunction(aid) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return hasEnded;
}
Here is the weird stuff. The ajax-call is made all right. The code on the server is running according to plan. However, if I try to set a firebug breakpoint in the success function of endFunction(aid) is is not hit, but the alert box is shown displaying the word true. This is somewhat good since it seems that we are actually reaching the success function. The hasEnded variable however is never set to true so it always returns false.
Calling endFunction(1) from the Firebug console displays an alert box with the word true and returns value false.
What's going wrong?
AJAX is asynchronous — the $.ajax call will not wait for the server to reply.
Therefore, the return hasEnded; line runs before the AJAX callback.
You need to make your endFunction take a callback parameter, like $.ajax does.
http://api.jquery.com/jQuery.ajax/
It looks like you're using "failure" in the documentation you have "error":
error(XMLHttpRequest, textStatus, errorThrown)
also you should do something like this:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
endFunction(aid,function(endv){
if (endv) {
// do some other stuff
}
});
}
},
error: function (errorMsg) { alert(errorMsg.toString()); }
});
}
function endFunction(aid,endcallback) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
endcallback(hasEnded);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
endcallback("?");
}
});
//return hasEnded;
}