How do I get JSON result from jquery .ajax call in done()? - ajax

I am trying to use the newer .done() syntax for a call to .ajax(), but I don't see how to get the data returned from the server into my .done() function. Here is my code:
function checkLink(element) {
var resultImg = $(element).parent().parent().find("img");
resultImg.attr("src", "/resources/img/ajaxLoad.gif");
$.ajax({
type: 'POST',
url: '/services/Check.asmx/CheckThis',
data: '{somedata: \'' + whatever + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: onSuccess,
error: onFailure
}).done(function () { success2(resultImg); });
}
function success2(img) {
img.attr('src', '/resources/img/buttons/check.gif');
}
function onSuccess(data) {
// The response from the function is in the attribute d
if (!data.d) {
alert('failed');
}
else {
alert('hurray!');
}
}
checkLink is called from a simple button push. Both onSuccess() and success2() are firing just fine. But... what I need is the "data" parameter from onSuccess passed to success2... or alternately, be able to pass "resultImg" to onSuccess (although I would prefer using .done instead of the deprecated method). It seems I can either pass my own parameters, or access the JSON result from the AJAX call... but not both. How do I accomplish this?

You can close over the resultImg variable:
function checkLink(element) {
var resultImg = $(element).parent().parent().find("img");
resultImg.attr("src", "/resources/img/ajaxLoad.gif");
$.ajax({
type: 'POST',
url: '/services/Check.asmx/CheckThis',
data: '{somedata: \'' + whatever + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: onSuccess,
error: onFailure
}).done(success2);
function success2(data) {
resultImg.attr('src', '/resources/img/buttons/check.gif');
// do whatever with data
}
function onSuccess(data) {
// The response from the function is in the attribute d
if (!data.d) {
alert('failed');
}
else {
alert('hurray!');
}
}
}

Related

Go to new view on AJAX success using ActionResult

I have an AJAX call that posts data to the server to save to the DB. When this is complete, I want to call another ActionResult in the success callback to switch the user to a brand new view. This needs no data passed to it, I just need the success in the Ajax to call this method. Is this possible? I played with some of the URL helpers but I can seem to make this work, it just does nothing.
$.ajax({
url: 'Mapping/',
type: 'POST',
data: JSON.stringify({
data
}),
contentType: 'application/json; charset=utf-8',
success: function(result) {
if (result.success === true) {
alert('Yes');
} else {
alert('No');
}
},
failure: function() {
alert('No');
}
So this would be in the first part of the success callback where it is currently set at aler('Yes').
Do something like this:
$.ajax({
url: 'Mapping/',
type: 'POST',
data: JSON.stringify({
data
}),
contentType: 'application/json; charset=utf-8',
success: function(result) {
if (result.success === 'true') {
window.location.href = 'Success/';
} else {
//handle the failure from the response
}
},
failure: function() {
//handle the failure of the request itself
}

Weird object returned from AJAX request

I have this method:
var chineseCurrency = getChinese();
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
});
}
That is what printed when console.log(chineseCurrency);:
I am not able to make chineseCurrency equal to "price", so it would be "6.80071377". How can I do that? Tried chineseCurrency.responseText, nope, chineseCurrency['responseText'], nope. Tried to JSON.parse(chineseCurrency), nope. Nothing works!
Sorry if repeated, couldn't find any answer at Stackoverflow.
How do I return the response from an asynchronous call?
Data that is received as response to asynchronous ajax call cannot be returned from the function that calls $.ajax. What you are returning is XMLHttpRequest object (see http://api.jquery.com/jquery.ajax/) that is far from the desired data.
var chineseCurrency = null;
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny",
success: function(data) {
alert("success1: chineseCurrency=" + chineseCurrency);
chineseCurrency = data.ticker.price;
alert("success2: chineseCurrency=" + chineseCurrency);
// do what you need with chineseCurrency
}
});
}
You are not taking the data from that is returned from the Ajax call. instead you are just returning the ajax object.
Change your code to :
$.ajax(
{
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
data :{},
error : function(data)
{
console.log('error occured when trying to find the from city');
},
success : function(data)
{
console.log(data); //This is what you should return from the function.
}
});

Replace Ajax Callback with Jquery callback

How to replace the following ajax callback method with a jquery callback method ?
function PostCall() {
$('#txtRes').val('Please Wait......');
var reqval = $('#txtReq').val();
$.ajax({
url: "myPage",
type: 'post',
data: "{'name':'" + reqval + "'}",
async: true,
contentType: "application/json",
success: function (result) {
$('#txtRes').val(result);
}
});
}
Just append the success at the end of your ajax statement (for example):
}.success(function(){
})
If you want to stick with Ajax go the jQuery 1.8 way and try this:
function PostCall() {
$('#txtRes').val('Please Wait......');
var reqval = $('#txtReq').val();
$.ajax({
url: 'myPage',
type: 'post',
data: "{'name':'" + reqval + "'}",
dataType: 'json',
async: true,
contentType: "application/json",
})
.done(function(result) {
$('#txtRes').val(result);
})
.fail(function(jqXhr, textStatus) {
console.log('Error: ...' + textStatus);
})
.always(function() {
});
}
The .done() function replaces your success callback.
If Ajax is not an option for you check out:
WebSockets
Http POST Requests (requires the whole page to be reloaded)

Ajax Call not working - is the call right

I am trying to send an ajax call with json array
the call function is
if(objHasValue) {
alert(JSON.stringify(objArray));
alert("before ajax call");
$.ajax({
type: 'POST',
url: 'http://www.web2222.net/Test/test.php',
dataType: 'json',
data: { json: JSON.stringify(objArray) },
success: function(data) {
alert('did it-'+data);
return false;
},
error: function(data){
alert('failure'+data.json);
}
});
}
return false;
somehow it doesn't work
Do I have any mistake there?
Thanks
i am not sure if this is the problem but try something like :
data: { "json": JSON.stringify(objArray) }

MVC2: Ajax call runs always in error function. Why? Whats wrong?

aspx site:
<script type="text/javascript">
function AjaxTest() {
var codeVal = "hello world";
if (codeVal) {
$.ajax({
type: "POST",
url: "CheckAge",
data: { code: codeVal },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("in ajax success");
},
error: function () {
alert("error");
}
});
}
}
Its double checked that the javascript function is called.
Controller:
[HttpPost]
public JsonResult CheckAge(String code)
{
return Json("abc");
}
It ended up always in the ajax - error - function.
The Controller function isnt called anyway. Why?
Why get I always an error?
What is wrong?
Check your url that you are posting to. It seems that you are missing the controller part. E.g. it should read /{controller}/{action}.
If that script is directly in the view (i.e. not in an external javascript file) you could have something like:
$.ajax({
type: "POST",
url: <%= Url.Action("CheckAge", "ControllerName") %>,
data: { code: codeVal },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("in ajax success");
},
error: function () {
alert("error");
}
});
Also, I find it advantageous to use firebug to debug ajax stuff. You can set break points in your javascript and also see all the requests and responses.
HTHs,
Charles
EDIT: Try simplifying things... e.g.
$.post('<%= Url.Action("CheckAge", "ControllerName") %>',
{ code: codeVal },
function (data) {
alert("in ajax success");
},
"json");

Resources