Nested Ajax Want to Running in Sequence - javascript

My code is as follows
$.ajax({
type: 'post',
dataType: 'json',
url: '123.123.0.1',
success: function (result) {
for (var i = 0; i < 2; i++) {
console.log('OUTSIDE');
$.ajax({
type: 'post',
dataType: 'json',
url: '123.123.0.1',
success: function (result) {
console.log('INSIDE');
}
});
}
}
});
Result of that code is :
OUTSIDE
OUTSIDE
INSIDE
INSIDE
My Objective here is I want to outside AJAX wait inside AJAX until inside AJAX done then inside AJAX continue. So I wanna the result look
like :
OUTSIDE
INSIDE
OUTSIDE
INSIDE
My question :
How to do that? How to fix my code?

You have to wait the ajax request to be finished before you go to the next step.
Below an recursive example.
// Code goes here
$.ajax({
type: 'post',
dataType: 'json',
url: '123.123.0.1',
success: function(result) {
function processResult() {
if (i >= 2) return;
console.log('OUTSIDE');
$.ajax({
type: 'post',
dataType: 'json',
url: '123.123.0.1',
success: function(result) {
console.log('INSIDE');
}
}).then(function() {
processResult(++i);
});
}
processResult(0);
}
});

Related

Issue with nested ajax call in jQuery

I have a situation where I make an ajax call, on returning from which (successfully), I make an another ajax call with the returned data and submit the page. The pseudo code looks something like this:
$.ajax({
url: 'first_page.jsp',
type: 'POST',
dataType: 'JSON',
data: {...}
}).done(function(response) {
$.ajax({
url: '2nd_page.jsp',
type: 'POST',
dataType: 'JSON',
data: {...}
});
thisPage.submit();
});
The inner ajax call is not executed if I do not comment out the 'submit' line. I do not understand the behaviour. Can someone please help me with this.
Thanks
You need to execute submit on second ajax sucess.
For example
$.ajax({
url: '',
type: 'GET',
data: {
},
success: function (data) {
$.ajax({
url: '',
type: 'GET',
data: {
},
success: function (data) {
//do your stuff
}
$("input[type='submit']").click(function(event){
event.preventDefault();
$.ajax({
url:'abcd.php',
method:'post',
type:'json',
async:false,
success:function(response){
$.ajax({
url:'abcde.php',
method:'post',
type:'json',
data:{res:response},
success:function(response){
console.log(response);
}
});
$("form").submit();
}
});
});
Try this one.Its working correctly.

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

ajax - return and prevent deferred.then() execution

I have a AJAX request like this:
$.ajax({
type: 'GET',
url: url,
dataType: "json",
success: function(data) {
// ...
callbak(true);
},
})
.then(
function( response ) {
// ...
});
I'd like to run that callback function and so exit from that ajax request in success function and prevent deferred.then() execution.
In my case the callback is fired but after that deferred.then() is also executed and I don't want this to happen.
Any idea?
Thanks
Use a flag like so:
var executeThen = true;
$.ajax({
type: 'GET',
url: url,
dataType: "json",
success: function(data) {
// ...
executeThen = false;
callbak(true);
},
})
.then(function(response) {
if(executeThen){
// ...
}
});

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

Do something after window load

I'm doing a (simple) ajax call on window load:
$(window).load(function () {
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
...........
How can I do something, for instance a function or event after this ajax proces is finished. The problem is I have to append something to the data recieved by the ajax call. But I can't append on window load because the data is still being processed.
Put it in the success handler of the ajax call:
$(window).load(function () {
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
// do whatever you want with data
}
});
});
You can call that in the success callback function of Ajax request
success: function(data) {
myFunction() ; // If function
$('#elementID').click() // If you want to trigger a click event
}
You may use the
`$(document).ready`
So it will be similar to this:
$(document).ready(function(){
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
//Your code should be here
After
success: function(data) {
for (var ii = 0; ii < data.length; ii++){
building html here
}
your code here
}
you want to enter in your functions within the success function for the ajax call but before the call is complete.
You could also do
$.ajax({
url: someUrl,
type: "get",
dataType: "",
context: document.body
}).done(function() {
// do whatever when is done
onCompleteFunction();
});
this should execute your request when page is just loaded.
$(function(){
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
// do whatever you want with data
}
});
});
or you can do:
$(function(){
$.ajax({
url: someUrl,
type: "get",
dataType: "",
complete: function(data) {
// do whatever you want with data
}
});
});

Categories