Is it possible to execute nested ajax on click event? - javascript

I am using nested ajax in my code and wanted to execute it on click of a button. but when I try to add any event listener inner ajax never gets success. when I remove on click event or event listener it works fine.
$("#Id1").click(function() {
$.ajax({
url: 'url1',
type: 'get',
data: {
method: 'method1',
id: id1
},
datatype: 'json',
success: function(a) {
console('ajax1');
if (a == 1) {
$.ajax({
url: 'url2',
type: 'post',
data: {
arg1: p,
arg2: q
},
datatype: 'json',
success: function(b) {
console('ajax2');
}
}
else {
alert('hello');
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This code fails and never executes success part of inner ajax. whereas code mentioned below works fine.
$.ajax({
url: 'url1',
type: 'get',
data: {
method: 'method1',
id: id1
},
datatype: 'json',
success: function(a) {
console('ajax1');
if (a == 1) {
$.ajax({
url: 'url2',
type: 'post',
data: {
arg1: p,
arg2: q
},
datatype: 'json',
success: function(b) {
console('ajax2');
}
}
else {
alert('hello');
}
}
});
Can somebody please help me on this? I am very to new to ajax and javascript. I tried putting error and failure inside second ajax but it do not enter in that callbacks.

I got that working just by doing this:
$("#Id1").click(function(e) {
e.preventDefault();
$.ajax({
url: 'url1',
type: 'get',
data: {
method: 'method1',
id: id1
},
datatype: 'json',
success: function(a) {
console('ajax1');
if (a == 1) {
$.ajax({
url: 'url2',
type: 'post',
data: {
arg1: p,
arg2: q
},
datatype: 'json',
success: function(b) {
console('ajax2');
}
}
else {
alert('hello');
}
}
});
});

Related

Nested ajax function calls inside a for loop

I have looked into many solutions which uses deffered and promises.Tried those solutions in my scenario but couldn't got a solution.I have been fighting with through out the entire day.My scenario is.
I have array of customers.And i need to do some certain actions to each customer one by one which are defined as ajax.
private function main()
{
customers=["customer1","customer2"]
customers.forEach(function(customer) {
function1();
function2();
function3();
}
}
private function function1()
{
$.ajax({
type: "POST",
url: Url1,
data: {},
success: function (data) {
console.log("a");
},
dataType: 'JSON'
});
}
private function function2()
{
$.ajax({
type: "POST",
url: Url2,
data: {},
success: function (data) {
console.log("b");
},
dataType: 'JSON'
});
}
private function function3()
{
$.ajax({
type: "POST",
url: Url3,
data: {},
success: function (data) {
console.log("c");
},
dataType: 'JSON'
});
}
When the main function is called .My desired output is
a
b
c
a
b
c
But the output i am getting is
a
a
b
b
c
c
Please help me find a solution.
Ajax call by default is the async. action.
function send() {
fetch(
url,
{
method: 'post',
header: {'Content-Type' : 'application/text'},
body: 'a'
}
).then(
() => {
console.log('a is sended');
fetch(
url,
{
method: 'post',
header: {'Content-Type' : 'application/text'},
body: 'b'
}
).then(
() => {
console.log('b is sended');
fetch(
url,
{
method: 'post',
header: {'Content-Type' : 'application/text'},
body: 'c'
}
).then( () => console.log('c is sended') )
}
)
}
)
}
Finally i solved my issue by making a recursive function call without using loop.
var customers=["customer1","customer2"];
var currentIndex=0;
private function main()
{
if(customers[currentIndex]){
function1().done(function(data) {
console.log("a");
function2().done(function(data) {
console.log("b");
function3().done(function(data) {
console.log("c");
currentIndex++;
main();
});
});
});
}
}
private function1()
{
return $.ajax({
type: "POST",
url: url1,
data: {},
dataType: 'JSON'
});
}
private function2()
{
return $.ajax({
type: "POST",
url: url2,
data: {},
dataType: 'JSON'
});
}
private function3()
{
return $.ajax({
type: "POST",
url: url3,
data: {},
dataType: 'JSON'
});
}
And current output is
a
b
c
a
b
c

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.

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

jQuery fade-in-out animation

I need to add a fade-in-out transition animation to this ajax loading code. Could someone explain me how to do it please?
JS :
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Use beforeSend() function of ajax request to fadeIn() and in success fadeOut()
$('#loading').css('visibility', 'visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page=' + url,
dataType: "html",
beforeSend: function () {
$('#loading').fadeIn();
},
success: function (msg) {
if (parseInt(msg) != 0) {
$('#pageContent').html(msg);
$('#loading').fadeOut();
}
}
});
I hope you want to show the effects on success of the ajax result. You may try this.
$.ajax({
type: "POST",
url: "institutions-filter.action",
data: data,
cache: false,
success: function(msg)
{
if(parseInt(msg)!=0)
{
$('#loading').css('visibility','hidden');
$("#pageContent").fadeOut(400, function()
{
$("#pageContent").html(msg).fadeIn(400);
});
}
}
});

ajax call not working with in ajax

I using the mvc controller with ajax. I perfom the task using the jquery confirm box. when i click the "ok" button its needs to the call another ajax and its link to the another controller but its not working
Sample code:
function button_click() {
$.ajax({
type: 'POST',
url: 'url',
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { call(data); }
else { alert(data.data); }
}
});
}
function call(data)
{
var ans = confirm(data)
if(ans)
{
$.ajax({
type: 'POST',
url: '#(Url.Action("StudentList", new { Area = "Mec", Controller = "HOD" }))',, // this url not goes to the controller
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { alert(data.data); }
else { }
}
});
} else { }
}
i have tried your code but it worked for me.the difference is that
you need to pass data in correct format. data:data or data:{ data:data } but not data:{data}
function button_click() {
$.ajax({
type: 'POST',
url: 'Demo/Demo_action',
data: { data: "what you want to pass" },
//dataType: 'json',
//contentType: 'application/json',
success: function (data) {
if (data == "hello") {
call(data);
}
}
});
}
function call(data) {
var ans = confirm(data)
if (ans) {
$.ajax({
type: 'POST',
url: '#(Url.Action("Demo_action2", new { Area = "Mec", Controller = "Home" }))',
//url: 'Home/Demo_action2', // this url not goes to the controller
data: { data: data },
dataType: 'json',
success: function (data) {
alert(data);
}
});
}
else
{ }
}

Categories