Access post data from inside ajax error function - javascript

I have the below javascript function that takes POST data and sends post request to server using Ajax
function postData(post_data) {
console.log(post_data, "----------->");
var data = post_data;
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (data) {
debugger;
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
// Can we access the post_data inside this error function ?
},
}
);
};
So what my actual point is, because of some reason the server is sending a 500 response and so the execution point is coming to error: function (jqXHR, textStatus, errorThrown, data), here I want to access post_data to display something to the user.... So can we access the post_data inside ajax error function above?

In case someone looks for a generic way to do this, here is how i did it: In case your handler functions are defined where their scope don't allow you to access some variables, you can add them to the ajax object itself in the function beforeSend. You can then retreive it in the ajax object by using this.
$.ajax({
url:'/dummyUrl',
beforeSend: function(jqXHR, plainObject){
plainObject.originalUrl = 'myValue';
},
success: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
$('#myValue').html(this.originalUrl);
},
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">waiting result</div>
<div id="myValue"></div>

function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function (jqXHR, textStatus, errorThrown, data) {
// handle error
console.log(post_data); // and the magic happens
},
}
);
};

Above this issue you were having wrong key "dataType" i have modified it. Secondly, "post_data" is in your scope you can access it without any issue.
function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataType: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function ( jqXHR jqXHR, textStatus, errorThrown) {
// post data is in your scope you can easily access it
console.log(post_data); // and the magic happens
},
}
);
};

Related

Cannot return whole JSON object back to calling function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am new to AJAX and I need to find a way to return an AJAX JSON response back to the calling function. Is there any way to achieve this.
My code snippet:
function requestAjaxWebService(webServiceName, method, jsonData) {
var returnData;
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: function (data) {
returnData = data;
},
error: function(error){
returnData = "Server error";
}
});
return returnData;
}
jQuery.ajax() performs asynchronous HTTP request. Hence, you can't return its response synchronously (which your code is trying to do).
If the request succeeds, the success(data, textStatus, jqXHR) handler will get called at some point (you don't know when).
Here is one way you could modify your code:
function requestAjaxWebService(webServiceName, method, jsonData, callback) {
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: function (data, textStatus, jqXHR) {
callback(true, data); // some method that knows what to do with the data
},
error: function(jqXHR, textStatus, errorThrown){
callback(false, errorThrown);
}
});
}
callback should be a reference to a method like:
function onData(isSuccess, dataOrError)
{
if (isSuccess) {
// do something with data
} else {
console.error(dataOrError);
}
}
Update If the settings object is needed in the callback for some reason:
function onData(isSuccess, settings, jqXHR, errorThrown)
{
if (isSuccess) {
// do something with the data:
// jqXHR.responseText or jqXHR.responseXML
} else {
// do something with error data:
// errorThrown, jqXHR.status, jqXHR.statusText, jqXHR.statusCode()
}
}
function requestAjaxWebService(webServiceName, method, jsonData, callback) {
var settings = {
url: webServiceName,
type: method,
data : jsonData,
dataType: "json"
};
settings.success = function(data, textStatus, jqXHR){
callback(true, settings, jqXHR);
};
settings.error = function(jqXHR, textStatus, errorThrown){
callback(false, settings, jqXHR, errorThrown);
};
$.ajax(settings);
}
requestAjaxWebService("name", "POST", "json", onData);
You can also use .done() and .fail() callbacks of jqxhr object instead of callbacks in settings object, as obiTheOne's answer suggests. It may look neater, but is not actually important here.
jQuery.ajax is an asynchronous function, so normally it doesn't return anything.
You can anyway return a value to the original function by setting the async option to false, but is not recommended, because a synchronous request will block the rest execution of the rest of your code until a response will be returned.
function requestAjaxWebService(webServiceName, method, onSuccess, onFail) {
var returnData;
$.ajax({
url: webServiceName,
type: method,
async: false,
data : jsonData,
dataType: "json",
success: function (data) {
returnData = data;
},
error: function(error){
returnData = "Server error";
}
});
}
take a look at this example: jsbin sync ajax example
You should instead use a callback (the standard way) to handle the response
function onSuccess (data) {
console.log(data);
}
function onFail (error) {
console.log('something went wrong');
}
function requestAjaxWebService(webServiceName, method, onSuccess, onFail) {
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: onSuccess,
error: onError
});
}
Or you can return a Promise (a sort of async object) that will change value as soon as the request will be fullfilled
function requestPromise (webServiceName, method) {
return $.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json"
});
}
requestPromise('...', 'GET').done(function (data) {
console.log(data);
});
refs:
jquery.ajax params

Internal Server Error when response text from ajax POST call is big

I am using an ajax call like the following:
$(function () {
$.ajax({
type: 'POST',
url: 'frmHistoryReportFinal.aspx/GetDataTable',
data: json_data,
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (responseText) {
if (responseText.d == "")
return;
parsedData = JSON.parse(responseText.d);
alert(parsedData);
count = 0;
},
error: function (xhr, textStatus, errorThrown) {
//process the error
alert(xhr);
alert(textStatus);
alert(errorThrown);
}
});
});
When I have a small set of data returned from my C# codebehind. The ajax call functions well. But when I have a json string with larger data, say 200 records returned then the ajax call gives error("Internal Server Error").
Please help me resolve the issue as I usually need to handle large datasets.

Jquery - Ajax: Get-posted "data" inside "error"

Minor question (solution seems simple but i can't seem to find it on google). I would like to use the data-setting inside my error: function. I know this may sound cryptic but allow me to use an example.
I have the following Ajax-Call (Jquery).
$.ajax({
type: "GET",
url: "Search.aspx",
data: {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
},
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
// RIGHT HERE, i want to use action,userSearchString,Docbase that were passed to Search.aspx
// Prefferably i would like to use the data as a whole object and pass it too LogException
$("#FindUsersModal").modal("hide")
LogException(errStatus, thrownError, "SearchUsersByInput", params);
}
})
Would anyone care to point me in the right direction?
Thnx for your time.
why not creating the data as an object on the function level and then access it from error callback? for example:
function foo(){
var jsonData = {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
}
$.ajax({
type: "GET",
url: "Search.aspx",
data: jsonData,
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
// RIGHT HERE, i want to use action,userSearchString,Docbase that were passed to Search.aspx
var something = jsonData.action;
$("#FindUsersModal").modal("hide")
LogException(errStatus, thrownError, "SearchUsersByInput", params);
}
})
}
The idea here is simple, just store your data in a variable outside the scope of the function, and you can use it where ever you want it within the function.
Here is what you need to do
var myData = {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
}
$.ajax({
type: "GET",
url: "Search.aspx",
data: myData,
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
console.log(myData);
//You can perform any action with myData here
}
})

convert json response to javascript array

I'm currently getting a json response which is:
[{"id":1,"title":"Test 1 "},{"id":2,"title":"Test 2"}]
and I want to convert it to a javascript array called 'events' like below so I can return it: e.g:
return {
events : [
{
"id":1,
"title":"Test 1"
},
{
"id":2,
"title":"Test 2"
}
]
};
I'm getting the response from a jquery ajax call:
jQuery.ajax({
type: "POST",
url: "calendar.aspx/get_all_events",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
document.write(msg.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error getting events from database.');
}
});
Anyone know how I can convert the msg or msg.d into what is needed?
Thanks,
You can use:
return {events: JSON.parse(msg.d)};
or, for better compatibility:
eval("var result = "+msg.d);
return {events: result};
or jQuery solution
return {events: $.parseJSON(msg.d)};
if msd.d is
[{"id":1,"title":"Test 1 "},{"id":2,"title":"Test 2"}]
then you could return it like this:
return {
events : msg.d
};
But you would have to do a callback in order to return it. Because ajax is asynchronous. I added the return because that is what you wanted. The alternative would be to make the ajax call synchronous.
I think you just need this:
success: function (msg) {
// The event object is what you require
var eventObj = {events:msg.d};
document.write(eventObj);
},
function doXHR( callback ) {
jQuery.ajax( {
type: "POST",
url: "calendar.aspx/get_all_events",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function ( event ) {
callback && callback( event );
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error getting events from database.');
}
});
}
doXHR( function( event ) {
var data = { events: event.d };
// Do other stuff with data here (processing, displaying, etc.).
// You can call other functions here and feed them with data.
} );
Note that XHR requests are asynchronous. You cannot simply return XHR request data. You have to put all your further code into callback function so it can process your array when it's available.

Conditionally adding option to jQuery Ajax call

I have the following working Ajax call -
$.ajax({
url: ajaxUrl,
type: sendHttpVerb,
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
complete: function () {
setTimeout($.unblockUI, 2000);
},
success: function (response, status, xml) {
clearTimeout(delayLoadingMsg);
$.unblockUI();
callbackFunction(response);
},
error: function (jqXHR, textStatus, errorThrown) {
clearTimeout(delayLoadingMsg);
$.unblockUI();
dcfForm.ajaxErrorDisplay(jqXHR, textStatus, errorThrown)
}
});
My problem is the I conditionally want to add an option when I invoke the Ajax call. For example, adding data: sendRequest before I issue the Ajax request.
My problem I cannot find an example for the syntax on how to do this without completely duplicating the entire function.
what about a ternary operation:
$.ajax({
data: condition ? sendRequest : undefined,
... the rest
});
If that's not your taste, some people seem to forget $.ajax doesn't take a long group of paramters, but an object:
var ajax = {};
ajax.success = function (data) { ... };
ajax.type = 'GET';
if (myCondition) {
ajax.data = sendRequest;
}
$.ajax(ajax);

Categories

Resources