jquery exit function in ajax call - javascript

Is there a way to exit a function, depending on the result of an GET request.
For example, in the below function, hi, if the GET results in data, where data === '1', I want to exit the function.
function hi () {
$.ajax({
url: "/shop/haveItem",
type: "GET",
success: function (data) {
if (data == '1') {
// exit hi() function
}
}
});
// some executable code when data is not '1'
}
How can I go about accomplishing this?

I think the solution can be something like this
function hi () {
$.ajax({
url: "/shop/haveItem",
type: "GET",
success: function (data) {
if (data == '1') {
ifData1();
} else {
ifDataNot1()
}
}
});
}
function ifData1 () { /* etc */ }
function ifDataNot1 () { /* etc */ }
If you have an ajax function, you should always work with callback functions. If you make an ajax function synchronous, then the browser will be blocked for the duration of ajax call. Which means that the application will remain non-responsive during the duration of the call.

You should be able to return false to simulate "exit".
function hi()
{
$.ajax({
url: "/shop/haveItem",
type: "GET",
async:false,
success: function(data){
if(data == '1')
return false
}
});
//some executable code when data is not '1'
...
}

One thing you can do is have a flag variable. Assign it to true or false, depending on if you want to exit or not.
function hi()
{
var flag=false;
$.ajax({
url: "/shop/haveItem",
type: "GET",
async:false,
success: function(data){
if(data == '1')
flag=true;
}
});
if ( flag ) return;
//some executable code when data is not '1'
...
}

Creating a global flag variable I think would work the best. Tested and working!!
window.flag = [];
function hi()
{
$.ajax({
url: "/shop/haveItem",
type: "GET",
async:false,
success: function(data){
if(data == '1')
flag = true;
}
});
if (flag) {
return false;
}
//some executable code when data is not '1'
...
}

Related

How to return false to global variable inside Ajax function

How can I pass true or false outside of this Ajax function? I need to return false on something and I cannot do that within Ajax
var zip = $('#order-zip').val();
var zipvalidated;
$.ajax({
type: 'POST',
url: 'checkzip.php',
data: {post:zip},
dataType: 'json',
success: function(data) {
zipvalidated = true;
if (data.response !== "success"){
console.log(data);
console.log ("sorry, we are not delivering in your area right now");
zipvalidated = false;
}
}
});
console.log (zipvalidated);
if (zipvalidated == false) {
return false;
}else{
console.log ("pass!")
}
You can force your request to be syncronous with async: false , but that's not recommended because it will cause the browser to lock up while waiting for results.
You can use callback function instead
const zip = $('#order-zip').val()
var zipvalidated = true
function getZip(zip,callback) {
$.ajax({
type: 'POST',
url: 'checkzip.php',
data: {post:zip},
dataType: 'json',
success: function(data) {
callback(data)
}
})
}
getZip(zip,function(data) {
if (data.response !== "success"){
console.log(data);
console.log ("sorry, we are not delivering in your area right now");
zipvalidated = false;
}
})
console.log (zipvalidated)
Ajax is by default async,
So your if statement runs before zipvalidated variable is updated.
Use async/await or try setting async: false on your ajax request.
Just put the checking in your callback function
$.ajax({
type: 'POST',
url: 'checkzip.php',
data: {post:zip},
dataType: 'json',
success: function(data) {
zipvalidated = true;
if (data.response !== "success"){
console.log(data);
console.log ("sorry, we are not delivering in your area right now");
zipvalidated = false;
console.log (zipvalidated);
if (zipvalidated == false) {
return false;
}else{
console.log ("pass!")
}
}
}
});

Jquery ajax request increases exponentially on each request

I use Jquery-ajax calls to get information from a api and store it. The problem I encounter is the following:
When first call is made call everything seems normal. When the call is made 2nd time (after 1 min )again one only call takes place but with 3rd call 2 times sendData function is getting called ,4th time 4 times sendData function is called.
Please tell me where i am going wrong.Thanks in advance.
$(document).ready(function() {
$(function ajaxCall() {
$.ajax({
url: "https://blockchain.info/ticker",
method: "GET",
dataType: "json",
crossDomain: true,
processData: true,
async: false,
success: function(resp) {
if (resp != null) {
alert(resp);
var myJSON = JSON.stringify(resp);
alert(myJSON);
sendData(myJSON);
setInterval(ajaxCall, 1000 * 60);
} else {
alert("something went wrong");
}
}
});
});
I would suggest you to move calling method to Ajax's complete method:
$(document).ready(function () {
$(function ajaxCall() {
$.ajax({
url: "https://blockchain.info/ticker",
method: "GET",
dataType: "json",
crossDomain: true,
processData: true,
success: function (resp) {
if (resp !== null) {
alert(resp);
var myJSON = JSON.stringify(resp);
alert(myJSON);
sendData(myJSON);
} else {
alert("something went wrong");
}
},
complete: function () {
setInterval(ajaxCall, 1000 * 60);
}
});
})
});

Two Ajax onclick events

So I have had to modify some old existing code and add another ajax event to onclick
so that it has onclick="function1(); function2();"
This was working fine on our testing environment as it is a slow VM but on our live environment it causes some issues as function1() has to finished updating some records before function2() gets called.
Is there a good way to solve this without modifying the js for function2() as this the existing code which is called by other events.
Thanks
Call function2 upon returning from function1:
function function1() {
$.ajax({
type: "POST",
url: "urlGoesHere",
data: " ",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//call function2
},
error:
});
}
Or wrap them in a function that calls both 1 and 2.
You need to use always callback of ajax method, check out always callback of $.ajax() method http://api.jquery.com/jquery.ajax/.
The callback given to opiton is executed when the ajax request finishes. Here is a suggestion :
function function1() {
var jqxhr = $.ajax({
type: "POST",
url: "/some/page",
data: " ",
dataType: "dataType",
}).always(function (jqXHR, textStatus) {
if (textStatus == 'success') {
function2();
} else {
errorCallback(jqXHR);
}
});
}
I'm assuming you use Prototype JS and AJAX because of your tags. You should use a callback function:
function function1(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function function2(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function both() {
function1(function() {
function2();
});
}
Then use onclick="both();" on your html element.
Example: http://jsfiddle.net/EzU4p/
Ajax has async property which can be set false. This way, you can wait for that function to complete it's call and set some value. It actually defeats the purpose of AJAX but it may save your day.
I recently had similar issues and somehow calling function2 after completing function1 worked perfectly. My initial efforts to call function2 on function1 success didn't work.
$.ajax({
type: "POST",
url: "default.aspx/function1",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // to make function Sync
success: function (msg) {
var $data = msg.d;
if ($data == 1)
{
isSuccess = 'yes'
}
},
error: function () {
alert('Error in function1');
}
});
// END OF AJAX
if (isSuccess == 'yes') {
// Call function 2
}

While ajax, async:true,deferred

3 hours i cant resolve the problem and found solution in internet. Some one please help me.
How i can create loop of ajax requests, while the data from ajax not equally "stop" using while and async:true?
This is not work example:
do {
promise = json('json.php');
promise.success(function again(data) {
if(data === 'stop') {
return false;
} else {
console.log('data');
}
});
} while (again());
function json(url) {
return $.ajax({
type: "GET",
dataType: 'text',
url: url
});
}
function again(data) {
if (data !== 'stop') {
alert(data);
sendReq();
}
}
function sendReq() {
json(location.href).success(again);
}
function json(url) {
return $.ajax({
type: 'GET',
dataType: 'text',
url: url
});
}
sendReq();

Variable is undefined error (even if console.log shows variable)

My function looks like that
var mail_ntfy=$("#nav_mail"), question_ntfy=$("#nav_question"), users_ntfy=$("#nav_users");
function CheckAll(){
var data=checkFor("m,q,u");
if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0)
mail_ntfy.attr("data-number", data.m_count);
if(question_ntfy.attr("data-number")!=data.q_count && data.q_count!=0)
question_ntfy.attr("data-number", data.q_count);
if(users_ntfy.attr("data-number")!=data.u_count && data.u_count!=0)
users_ntfy.attr("data-number", data.u-count);
showNotes(data.msg);
chngTitle(data.msg);
}
$(document).ready(function () {
setInterval(CheckAll(), 10000);
})
function checkFor(param){
$.ajax({
url: "core/notifications.php",
type: "POST",
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
return data;
}
}
});
}
I got 2 questions:
1) I see that, checkFor function returns result (console.log shows result) but still getting data is undefined error message on line if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0). What am I missing?
2) I want to execute, CheckAll in every 10 seconds. But it doesn't start more than 1 time. why setinterval doesn't work properly?
checkFor() does not return any result. The console.log() statement is in the anonymous function attached to the success handler of your AJAX request; its return does not return from the checkFor() function.
If you want checkFor to return the data the AJAX call has to be synchronous. This is, however, bad Javascript practice (for example, it will hang the execution of scripts on the page until the request is complete). Unfortunately this whole design is flawed, but you could use this code if you REALLY have to:
function checkFor(param){
var result;
$.ajax({
url: "core/notifications.php",
type: "POST",
async: false,
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
result = data;
}
}
});
return result;
}
You can't return data from success callback. Instead you can call CheckAll from success callback like this
success: function (data) {
if(data.status!="error") {
console.log(data);
//return data;
CheckAll(data);
}
}
To run checkFor instead every 10 seconds you can set the timer from within success callback too. That will call the checkFor 10 seconds after every successful ajax request. Using setInterval can end up with multiple simultaneous ajax calls.
success: function (data) {
if(data.status!="error") {
console.log(data);
//return data;
CheckAll(data);
setTimeout(checkFor,10000);
}
}
And your updated checkAll would be like
function CheckAll(data){
if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0)
mail_ntfy.attr("data-number", data.m_count);
if(question_ntfy.attr("data-number")!=data.q_count && data.q_count!=0)
question_ntfy.attr("data-number", data.q_count);
if(users_ntfy.attr("data-number")!=data.u_count && data.u_count!=0)
users_ntfy.attr("data-number", data.u-count);
showNotes(data.msg);
chngTitle(data.msg);
}
You are calling Ajax asynchronously therefore the system wont wait for ajax to end in order to continue proccessing. You'll have to add
async:false,
To your ajax call, like this:
function checkFor(param){
$.ajax({
url: "core/notifications.php",
type: "POST",
async:false,
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
var ret=data;
}
}
});
return ret;
}
Hope it helps!

Categories