ajax call not working with in ajax - javascript

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

Related

Is it possible to execute nested ajax on click event?

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

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

Can I use jquery's .done() more than once?

I have 2 JS literals:
var obj1 = {
Add: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/add",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
var obj2 = {
List: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/list",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
And this is my document.ready:
$(document).ready(function () {
obj1.Add(1).done(function (data) {
alert('you added ' + data);
});
obj2.List().done(function (data) {
$.each(jQuery.parseJSON(data), function (i, item) {
// fill a combo box
});
});
});
jQuery just executes the first call and obj2.List() ain't called at all.
How to properly use the deffered objects in this case?
Change your Add and List function to RETURN the ajax object.
Add: function (id) {
return $.ajax({..
and
List: function (id) {
return $.ajax({...
This way - it will return the jqXHR obj which will return the deferred object.
This implement the Promise interface which has : the callbacks you are looking for.
edit :
look at this simple example which does work :
var obj1 = {
Add: function (id) {
return $.ajax({
type: "get",
data: JSON.stringify({
"id": 1
}),
url: "http://jsbin.com/AxisAmi/1/quiet",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("at success --"+data.data)
}
});
}
};
obj1.Add(2).done(function (a){alert("at done --"+a.data);});

Ajax doesn't execute success function

My code looks like this. The problem is, PHP side does it job and returns right value. But ajax doesn't execute things inside success: function. What am I missing?
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
$(this).removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" + $(this).data("id") + "]").toggleClass("SelectedDiv");
}
}
});
return false;
});
Try to cache $(this) before ajax call
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
thisElem=$(this),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
thisElem.removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" +thisElem.data("id")+ "]").toggleClass("SelectedDiv");
return false;
}
}
});
});

jQuery parallel AJAX call mixes up return values

In the following JavaScript code I repeatedly make AJAX calls to my FastCGI module to query some values. At some point the code terminates when the data variable for the div2 case is not 0 but contains the value that should go into div1 while the div1 displays the value that was supposed to go into div2.
I am using the Chromium Browser (14.0.835.202 (Developer Build 103287 Linux) Ubuntu 10.10) but it also happens with FireFox. I also tried using the XMLHttpRequest object alone and I got the same results.
How can this be and how can this be solved?
function TimerEvent() {
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=s#SYSDATETIME",
success: function(data) {
document.getElementById("div1").innerHTML = data;
}
});
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=#LOGINSTATE",
success: function(data) {
document.getElementById("div2").innerHTML = data;
if (data == "0")
setTimeout("TimerEvent()", 50);
}
});
}
Maybe try have them sequential:
function TimerEvent() {
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=s#SYSDATETIME",
success: function(data) {
document.getElementById("div1").innerHTML = data;
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=#LOGINSTATE",
success: function(data) {
document.getElementById("div2").innerHTML = data;
if (data == "0")
setTimeout("TimerEvent()", 50);
}
});
}
});
}
If your requirements allows, try this:
function TimerEvent() {
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=s#SYSDATETIME",
success: function(data) {
document.getElementById("div1").innerHTML = data;
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=#LOGINSTATE",
success: function(data) {
document.getElementById("div2").innerHTML = data;
if (data == "0")
setTimeout("TimerEvent()", 50);
}
});
}
});
}
Try to execute the calls synchronously by adding the async=false option.

Categories