jQuery ajax in ajax request - javascript

We have some code(simplified) that looks like bellow. We run function x which does an ajax call. When the call is done we call a different function recalculateOrderObjects which also does an ajax call. When this one is completed, it should output the data that which is obtained via the second call. However, what actually happens is that only the first ajax call is made and the second is not executed (or at least immediately goes to done) but does show the data obtained from the first call as the data obtained from the second one.
When running only the recalculateOrderObjects function the function does work as expected.
Edit 1
The subscription variable is a global
There are no errors on the console
Also, when I first call recalculateOrderObjects independent the function work when first x is called and after that I call recalculateOrderObjects independently the function will not work and shows the same behaviour as when called from `x.'
Edit 2
I tried the suggestion to use successinstead of doneas well. With the same result. recalucateOrderObjects is called succesfully, thought after one executing x the whole ajax call in recalucateOrderObjects is never requested again but instead thinks that it is succesfully executed.
function recalculateOrderObjects() {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription}
})
.done(function (data) {
console.log('Data ' + data);
});
}
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
async: false
}).done(function (response) {
recalculateOrderObjects();
}
});}
x();

You can't get success responce by ".done" function.
"success" function gives you responce after ajax load.
Please try below code
function recalculateOrderObjects() {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription},
success: function(data) {
console.log('Data ' + data);
}
});
}
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
success: function(data) {
recalculateOrderObjects();
}
});
}
x();
OR
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
success: function(data) {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription},
success: function(data) {
console.log('Data ' + data);
}
});
}
});
}
x();

Related

Getting Certain values from an AJAX return JSON object

I am trying to retrieve certain values in a JSON object retrieved from AJAX.
Using console.log(), I was able to view these:
0: Object
title: "First post"
body: "This is a post"
id: 1
userId: 27
.
.
.
100: //same format of data as object 0
Now I want to try storing the whole JSON object above so that I can use the userId and match it with another list of data to find the user who made the post. Problem is, I can't store it to a global variable. Here is my jscript snippet:
var postJson; //global variable
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
console.log(response);
}
});
I also tried doing postJson = $.ajax but nothing happened and postJson continues to be undefined.
$.ajax is async function, you need to use callback or do all the code in success function
var postJson; //global variable
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
//do something with postJson or call function doSomething(response)
}
});
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
doSomething(response);
//do something with postJson or call function doSomething(response)
}
});
You can do directly via calling function from response no need to declare variable. Hope it will also helps you

Ajax redirect on error

I'm calling php file through ajax call and if it returns nothing i want to redirect user to another page (It's for error reports, if it doesn't return anything it means that user logged in). Tried to add error section but it doesn't work. Any suggestions will help. Thanks! Btw, I have small jQuery function at the top of the ajax function, why it breaks my whole ajax call?
ajax.js
function loginAjax() {
//$("#email_errors").empty(); //This function doesnt work and kills whole ajax call. Here is loginAjax function call line - <button type = "submit" id = "push_button" onclick = "loginAjax(); return false">PushMe</button>
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
}
});
}
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
},
error: function(){
window.location.replace("http://stackoverflow.com");
}
});
}
To redirect using javascript all you need to do is override the location.href attribute.
function loginAjax() {
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
// the success method is deprecated in favor of done.
done: function(data) {
$("#login_error").html(data.login_message);
},
fail: function(data) {
location.href="path/to/error/page";
}
});
}

Jquery set HTML via ajax

I have the following span:
<span class='username'> </span>
to populate this i have to get a value from PHP therefor i use Ajax:
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
}
})
}
Now when i debug i see that the returned data (data) is the correct value but the html between the span tags stay the same.
What am i doing wrong?
Little update
I have tried the following:
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html('RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRr');
}
})
}
getUsername();
Still there is no html between the tags (no text) but when i look at the console the method is completed and has been executed.
Answer to the little update
The error was in my Ajax function i forgot to print the actual response! Thank you for all of your answers, for those of you who are searching for this question here is my Ajax function:
public function ajax_getUsername(){
if ($this->RequestHandler->isAjax())
{
$this->autoLayout = false;
$this->autoRender = false;
$this->layout = 'ajax';
}
print json_encode($this->currentClient['username']);
}
Do note that i am using CakePHP which is why there are some buildin methods. All in all just remember print json_encode($this->currentClient['username']);
The logic flow of your code is not quite correct. An asynchronous function cannot return anything as execution will have moved to the next statement by the time the response is received. Instead, all processing required on the response must be done in the success handler. Try this:
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: { },
success: function(data){
$('.username').html(data); // update the HTML here
}
})
}
getUsername();
Replace with this
success: function(data){
$('.username').text(data);
}
In success method you should use something like this:
$(".username").text(data);
You should set the html in callback
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html(data);
}
})
}
Add a return statement for the function getUsername
var result = "";
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
result = data;
}
})
return result;
}
You can use .load()
Api docs: http://api.jquery.com/load/
In your case:
$('.username').load(myBaseUrl + 'Profiles/ajax_getUsername',
{param1: value1, param2: value2});

Why can't I do .ajax ( return data; )? jQuery

I'm trying to get my function to return the data it got into another function but it doesn't seem to work? How can I get it to return the data?
function playerid(playername) {
$.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
success: function(data) {
//$("#test").text(data);
return data;
}
});
}
I want to use it in another function like this
showBids(playerid(ui.item.value));
function showBids(playerid) {
$.ajax({
type: "POST",
url: "poll.php?",
async: true,
dataType: 'json',
timeout: 50000,
data: "playerid="+playerid,
success: function(data) {
//.each(data, function(k ,v) {
//})
//$("#current_high").append(data);
setTimeout("getData()", 1000);
}
});
First of all, your playerid() does not return anything, so what do you want to use? It has only $.ajax() call in it, no return statement (one of the callbacks in $.ajax() has return statement, but see below).
Secondly, JavaScript does some things asynchonously, otherwise every interface element would need to wait to react to user action until the AJAX call returns from the server.
Use event-based approach, by passing callbacks to some functions. Then, after they finish, just call the callbacks passing them the result:
function getplayerid(playername, callback) {
$.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
success: function(data) {
//$("#test").text(data);
callback(data);
}
});
}
and then use it like that:
getplayerid(ui.item.value, showBids);
(notice function name change since it does not actually return player ID, it gets it and passes it to callback)
You could try to use syncronous Ajax:
function playerid(playername) {
return $.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
async : false //making Ajax syncronous
}).responseText;
}
Otherwise you need to use showBids function as callback:
function playerid(playername, callback) {
$.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
success: function(data) {
callback(data);
}
});
}
//Usage
playerid(ui.item.value,showBids);

"undefined" for alerting an ajax call response , why?

i am trying to alert the return value captured by the ajax request. The web method it is refering is returning a boolean value of true or false, and when i am trying to access it outside the ajax method it gives a message "undefined" :?
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var authInfo;
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
authInfo = msg.d;
},
});
alert(authInfo);
});
</script>
why is the alert(authInfo) giving me as "undefined" ?? Please help !
where does this piece of code fit on the above context ?
if(auhthInfo){
$(".ansitem").editable('FetchUpdate.aspx', {
style: 'background-color:inherit;',
type: 'textarea',
indicator: '<img src="spinner.gif">',
event: 'dblclick',
onblur: 'submit',
submitdata: function (value, settings) {
return { orgval: value};
},
});
};
Your "$.ajax()" call is asynchronous, and thus the results are not available until the response is returned from the server.
If you put your "alert()" inside the "success" callback, it should work (if the HTTP transaction works).
EDITED TO HANDLE YOUR NEW CODE:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var authInfo;
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// alert(msg.d); // here it will work as it is only called when it succeeds.
MyHanlder(msg);
},
});
// alert(authInfo); // here authinfo has no value as the AJAX call may not have returned.
});
function MyHandler(msg) {
if(msg.d){
$(".ansitem").editable('FetchUpdate.aspx', {
style: 'background-color:inherit;',
type: 'textarea',
indicator: '<img src="spinner.gif">',
event: 'dblclick',
onblur: 'submit',
submitdata: function (value, settings) { return { orgval: value}; },
});
};
}
</script>
The request and the response that you get via ajax calls are asynchronous. I think it is not possible to alert the value that you get in response at the end of ready function because you are not assured that you will be getting your response before the function completes execution.
You are alerting the authInfo variable before the actual ajax call have returned. If you try this:
success:function(msg) {
authInfo = msg.d;
alert(authInfo);
}
I think you will get the correct result.
Because the AJAX call is done asynchronously, the alert does not have the value at the time of execution. If you place the alert inside the success function you should see the appropriate results. I also noticed you have an extra comma in the $.ajax parameters after the success function parameter.
It appears:
alert(authInfo);
Is running immediately when your document is ready.
However, the variable is not being initialized until after the AJAX call completes.
Try moving the alert to:
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
authInfo = msg.d;
alert(authInfo);
},
});
If you need to do anything more complex with the value, you can try re-factoring the code into another function:
function onSuccess(msg)
{
if(msg.d)
{
window.alert('The value is true!');
}
else
{
window.alert('The value is false!')
}
}
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
});

Categories