Ajax doesn't execute success function - javascript

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

Related

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 Ajax working on localhost (xammp) but not working on Server (cpanel)?

Jquery Ajax working fine on localhost (xammp) but not working on Server (cpanel) !
also ajax with Javascript working fine , but throught JQuery it has problem ! (on server)
i changed send method to POST but problem same.
this is my website :
concert20.ir
an this is js code:
var arr=[];
function func1(id,status){
var str;
var a=id.split('-');
// a[0] = chair number
// a[1] = singer id
// a[2] = place
length=arr.length;
if(status=='رزور شده')
{
// check that who resereved it?
var index=jQuery.inArray(parseInt(a[0]), arr);
if(index>=0)
{
// unreserved ...
//arr[index]=-1;
arr.splice(index, 1);
length=arr.length;
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({reservefunc:0,chairnum:a[0],singerid:a[1],place:a[2]}),
success: function(result){
$("#drawtable").html(result);
}
});
if(length==0)
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:0,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
else
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:1,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
}
}
else if(status=='قابل خرید')
{
// reserve ...
arr.push(parseInt(a[0]));
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({reservefunc:1,chairnum:a[0],singerid:a[1],place:a[2]}),
success: function(result){
$("#drawtable").html(result);
}
});
sts=$("input#checksts").val();
if(sts==-1)
{
var index=jQuery.inArray(parseInt(a[0]), arr);
arr.splice(index, 1);
alert('این صندلی قبلا خریداری شده است');
}
length=arr.length;
if(length==0)
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:0,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
else
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:1,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
}
}
UPDATE
i found the problem!
the server was context-sensitive and i did not observe it
i changed ServerReply.php to serverReply.php and it worked fine ...
try to write absolute url save to versions of ulr in var and comment , un comment respectively
var mainurl = "http://localhost/project/serverReply.php"
var mainurl = "http://xeample.com/project/serverReply.php"
try if it can solve the problem
Try this:
$.ajax({
type : "GET",
url : "ServerReply.php",
cache : false,
async : true,
global : false,
data : {
"showdetails":0,
"chairnum":arr
}
}).done(function(msg) {
//Do something
});

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.

Load up javascript files after ajax call

Hi how do i go about loading up my javascript files after an ajax call has been made, reason being it seems once i click submit, some javascript functions do not end up working. I tried using "$getscript" however it was a bit buggy especially in google chrome? This is what my call looks like;
function InsertStatus() {
var fStatus1 = document.getElementById('<%=txtStatus.ClientID %>').value;
$.ajax({
type: "POST",
url: "WebServices/UserList.asmx/InsertUserStatus",
data: "{ 'fStatus': '" + fStatus1 + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d == "Successful") {
$("#col-3").load(location.href + " #col-3>*", "");
$.getScript('scripts/script.js', function () {
});
}
else {
alert("its false");
$.getScript('scripts/script.js', function () {
});
}
}
});
};
Replace $.getScript('scripts/script.js', function () {});
With:
$.ajax({
dataType: 'script',
url: 'scripts/script.js',
crossDomain:true,
success: function(response)
{
//Whatever
}
});

How to group rules in jquery

Hi I've got a simple question. I've this code below, i use ajax three times in very similiar ways the only things that change are the data passed and the id of the target. Is there a way to group these instructions in a simple one?
Thx
D.
$('#fld_email').focusout(function() {
var request_email = $(this).val();
$.ajax({type:"GET",
url: "autocomplete.asp",
data: "fld=firstname&email="+request_email,
beforeSend: function(){$('#fld_firstname').addClass('ac_loading');},
success: function(msg){$('#fld_firstname').val(msg);$('#fld_firstname').removeClass('ac_loading'); }
});
$.ajax({type:"GET",
url: "autocomplete.asp",
data: "fld=lastname&email="+request_email,
beforeSend: function(){$('#fld_lastname').addClass('ac_loading');},
success: function(msg){$('#fld_lastname').val(msg);$('#fld_lastname').removeClass('ac_loading');}
});
$.ajax({type:"GET",
url: "autocomplete.asp",
data: "fld=phone&email="+request_email,
beforeSend: function(){$('#fld_phone').addClass('ac_loading');},
success: function(msg){$('#fld_phone').val(msg);$('#fld_phone').removeClass('ac_loading');}
});
}
);
try:
$('#fld_email').focusout(function() {
var request_email = $(this).val();
processAjax("fld=firstname&email="+request_email, '#fld_firstname');
processAjax("fld=lastname&email="+request_email, '#fld_lastname');
processAjax("fld=phone&email="+request_email, '#fld_phone');
});
function processAjax(data, id){
$.ajax({type:"GET",
url: "autocomplete.asp",
data: data,
beforeSend: function(){$(id).addClass('ac_loading');},
success: function(msg){$(id).val(msg).removeClass('ac_loading');}
});
}
Use an object and the for control structure:
var fields = {firstname:1, lastname:1, phone:1};
for (field in fields) {
$.ajax({
type:"GET",
url: "autocomplete.asp",
data: "fld=" + field + "&email=" + request_email,
beforeSend: function() {
$('#fld_'+field).addClass('ac_loading');
},
success: function(msg) {
$('#fld'+field).val(msg);
$('#fld'+field).removeClass('ac_loading');
}
});
}

Categories