convert json response to javascript array - javascript

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.

Related

Access post data from inside ajax error function

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
},
}
);
};

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

Have JavaScript method return the result of jQuery AJAX call [duplicate]

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()

jQuery: Calling a function from AJAX request

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/

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