Ajax Call not working - is the call right - ajax

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

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

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

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!');
}
}
}

asp.net mvc ajax driving me mad

how come when I send ajax request like this everything works
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
But when I add the anonymous function to the success It always showes me the error message although the song is still deleted
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: function () { ShowMsg("Song deleted successfully"); },
error: function () {
ShowMsg("There was an error therefore song could not be deleted, please try again");
},
dataType: "json"
});
});
what if i wanted few things on success of the ajax call, I need to be able to use the anonymous function and I know that's how it should be done, but what am I doing wrong?
I want the success message to show not the error one.
function ShowMsg(parameter) {
$("#msg").find("span").replaceWith(parameter);
$("#msg").css("display", "inline");
$("#msg").fadeOut(2000);
return false;
}
Make sure your action is returning Json data.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
http://api.jquery.com/jQuery.ajax/
Your action method should surely return Json data. I have the similar code see if that helps.
public ActionResult GetAllByFilter(Student student)
{
return Json(new { data = this.RenderPartialViewToString("PartialStudentList", _studentViewModel.GetBySearchFilter(student).ToList()) });
}
$("#btnSearch").live('click',function () {
var student = {
Name: $("#txtSearchByName").val(),
CourseID: $("#txtSearchByCourseID").val()
};
$.ajax({
url: '/StudentRep/GetAllByFilter',
type: "POST",
data: JSON.stringify(student),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result) {
$("#dialog-modal").dialog("close");
RefreshPartialView(result.data);
}
, error: function() { alert('some error occured!!'); }
});
});
Above code is used to reload a partial view. in your case it should be straight forward.
Thanks,
Praveen

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