jQuery AJAX post callback doesn't seems to work - ajax

I did this lots of times:
var url = '/offers/1/voting';
var params = { 'direction': 'up' };
$.post(url, params, function() {
alert('callback');
}); // post
(I'm hardcoding the values for this example, but nothing)
So, through firebug I receive the desired JSON response (200 status), but the callback doesn't execute. It's pretty much the only javascript I'm using. Tried with jquery 1.6.4 and 1.7.1 and it's the same thing with both. I don't know what I'm missing.
Help me, Stack Overflow. You're my only hope.

If you use $.ajax instead of $.post ($.post is really an overwrite of $.ajax with fewer parameters), you can add a handler for error and see if it fires:
jQuery.ajax({
type: "POST",
async: true,
url: '/offers/1/voting',
data: { 'direction': 'up' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});

try this
$.post(url, params, function(callback) { alert(callback); });

Related

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

Keep loading AJAX request

I have an AJAX request which gets data from the database and then populates the page with the data collected. The problem I am having is that currently the ajax request is in a setInterval which is being called every second.
setInterval(function () {
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
}
});
}, 1000);
This is fetching the data every second which is a huge strain on the server as it's making a request and then I am calling it again even when the data hasn't come through first time.
Is there a way that I can call the same AJAX request over and over but only after it's finished fetching the data first time and not keep going up?
There are better architectures to accomplish this type of scenario (websockets as mentioned in the comments would be one example), but to do strictly what you're asking, sure! Wrap it in a function that calls itself:
function getData(){
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
getData();
}
});
}
Replace the setInterval with a setTimeout only once you're done:
function fetchAjax() {
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
setTimeout(fetchAjax, 1000);
}
});
};
Add a variable to distunguish if ajax call is already underway. If it is, don't do anything. If not, go ahead.
var isAjaxInProgress = false;
setInterval(function () {
if (!isAjaxInProgress){
isAjaxInProgress = true;
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
isAjaxInProgress = false;
}
});
}
}, 1000);

Ajax Success Function not working

I am using Ajax to add contents on my database. And here's the code:
function addToFavorites(){
var recipe_id = $("#recipe_id").val();
var url = connect_url+'addFavorite.php?user_id='+user_id+'&recipe_id='+recipe_id;
$.ajax({
type: 'POST',
data: [{
user_id: user_id,
recipe_id: recipe_id
}],
url: url,
async: true,
jsonpCallback: 'userCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (data) {
alert("HELLO!!!");
},
error: function (e) {
alert("ERROR!");
}
});
}
The Ajax call was successful and I was able to add records on the database but I'm just wondering why is it not displaying the alert message if the calling was successful? Is there something wrong with my code? Or is there something wrong with my understanding? Thanks!
you must give a response with some info to the ajax or it won't know the response succeeded

Function Execution order when ajax included in jQuery mobile

I got a doubt regarding the way of execution of functions having ajax calls in jQuery.
Consider two functions.
function auth() {
$.ajax({
type: "POST",
dataType: "json",
url: API_URL,
data: {....
},
success: function (response) {}
});
};
function getData() {
$.ajax({
type: "POST",
dataType: "json",
url: API_URL,
data: {....
},
success: function (response) {}
});
};
and i call these functions one after other as show below...
auth();
getData();
My situation is, I want to execute the getData() only after completing 'auth()' .I know we can call the getData() inside the success function of auth. But what i want to know is, how these functions will be executed if i call the one after another, like i shown above.
Any kind of help would be appreciated :)
Thanks.
You can use deferred objects in jQuery. Simply return the ajax() result.
function auth() {
return $.ajax({
type: "POST",
dataType : "json",
url: API_URL,
data: { .... },
success: function (response) {
}
});
};
auth.done(getData);
This will call getData when auth is complete.
They will execute Asynchronously. You can make them wait (Synchronous), if that is what you want, by setting "async=false" in the call.
function auth() {
$.ajax({
**async: false,**
type: "POST",
dataType: "json",
url: API_URL,
data: {....
},
success: function (response) {}
});
};
function getData() {
$.ajax({
**aysnc: false,**
type: "POST",
dataType: "json",
url: API_URL,
data: {....
},
success: function (response) {}
});
};
This will make the call finish before moving on to the next call, BUT will lock the browser usually when making the calls:
async (default: true)
Type: Boolean By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
Src JQM Site: http://api.jquery.com/jQuery.ajax/

jQuery.ajax returns 400 Bad Request

This works fine:
jQuery('#my_get_related_keywords').click(function() {
if (jQuery('#my_keyword').val() == '') return false;
jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
function (data) {//do something}
This returns 400 Bad Request (Just a reformulation of the above jQuery using .ajax to support error handling).
jQuery('#my_get_related_keywords').click(function()
{
if (jQuery('#my_keyword').val() == '') return false;
jQuery('#my_loader').show();
jQuery.ajax(
{
url: "http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
success: function(data)
{//do something}
I think you just need to add 2 more options (contentType and dataType):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
Add this to your ajax call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
===============
and for post
$.ajax({
type: 'post',
must be met with
app.post('/', function(req, res) {
I was getting the 400 Bad Request error, even after setting:
contentType: "application/json",
dataType: "json"
The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.
This was my initial code:
var data = {
"TestId": testId,
"PlayerId": parseInt(playerId),
"Result": result
};
var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
url: url,
method: "POST",
contentType: "application/json",
data: JSON.stringify(data), // issue with a property type in the data object
dataType: "json",
error: function (e) {
console.log(e); // logging the error object to console
},
success: function () {
console.log('Success saving test result');
}
});
Now after making the request, I checked the console tab in the browser development tool.
It looked like this:
responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.
Changing the data object creation like below fixed the issue for me:
var data = {
"TestId": String(testId), //converting testId to a string
"PlayerId": parseInt(playerId),
"Result": result
};
I assume other possible errors could also be identified by logging and inspecting the error object.
Your AJAX call is not completed with the following two params.
contentType: "application/json; charset=utf-8",
dataType: "json"
contentType is the type of data you're sending
dataType is what you're expecting back from the server
In addition try to use JSON.stringify() method. It is used to turn a javascript object into json string.

Resources