Jquery stop function - javascript

I have a jquery function like this:
function get()
{
$.ajax({
url: 'get.php',
success: function(data) {
$('#get').html(data);
$('#get').fadeIn(2000);
setTimeout(posts,2000);
}
});
}
get();
I want to stop this function when i click on a certain element in a webpage, how would i do this.
Thanks

Set a variable for your AJAX request.
var getajax;
function get() {
getajax = $.ajax({
......
});
}
When you want to abort it, simply
getajax.abort();

In a situation where you may not be able to globaly define all of your .ajax() call variables (as shown by another answer by #uzyn), this might be a suitable solution.
You could simply wrap your success callback with a flag indicating whether you want to cancel the result.
var ajax_canceled = false;
function get(){
$.ajax({
url: 'get.php',
success: function(data) {
if (!ajax_canceled){
//...
}
}
});
}
get();
$("#cancel_ajax").on('click',function(){
ajax_canceled = true;
});

Related

ajax in ajax and NEED return value to first ajax

I have looking for the solution with my case. In other question variable from ajax success will execute like this:
$.ajax({
...,
success: function(data) {
myFunction(data);
});
myFunction(data){
// process the data here ..
}
But in my case I call another ajax(2) with ajax(1). And really need that variable from ajax(2) to ajax(1) for process. My code look like this:
$("#formVerify").submit(function(event) {
$.ajax({
....
success: function(data){
var result= call_id(data.id);
console.log(result);
}
});
});
function call_id(data) {
var output = null;
$.ajax({
....
success: function(result){
output = result;
}
});
return output;
}
the result will always null because I set output to, or sometimes it is undefined if I don't set the value to null. I tried async: false but in my machine it wouldn't work. Need help thank you
Remember Ajax call doesn't return result, you can't use return statement in ajax call. You can get the result only using callback/promises.
Change you first ajax call to pass the callback instead of trying to get the return value:
$("#formVerify").submit(function(event) {
$.ajax({
....
success: function(data){
call_id(data.id, function(result){
console.log(result);
});
}
});
});
and change your second ajax call_id function to take callback as parameter like this:
function call_id(data, callback) {
$.ajax({
....
success: callback
});
}

How to pass variable from one JS file to the other from within a deferred function

I'm trying to call json object in another JS file but there seems to be a timing issue. So I put a setTimeout below but the setTiemout runs twice, first with the object populated, then again with the object undefined and then undefined the passed to the second JS file. I also tried clearTimeout but then it didn't run at all. Then I tried a boolean but it still ran twice. I think the issue might be cause of the deferred, is there any way around this?
var json = {};
$('.submit').on('click', function (e) {
e.preventDefault();
var input = $('.url-input');
var def = $.Deferred();
$.ajax({
type: "GET",
url: $(input).val(),
data: input.serialize(), // serializes the form's elements.
success: function(data) {
var category;
$(data).find('a[href*="categories"]').filter(function(){
var data = $(this);
category = data.text().trim();
json.category = category;
});
def.resolve();
return def.promise;
}
}).then(function () {
$('.cust-viz.viz-2').html('<iframe class="bubble_chart" src="bubble_chart.html" height="500"></iframe>');
if (json.category) {
hideShowViz('show');
}
});
});
}
setTimeout(function () {
json = json;
}, 5000);
based on answers, I did
var json ={};
$('.submit').on('click', function (e) {
e.preventDefault();
var input = $('.url-input');
$.ajax({
type: "GET",
url: $(input).val(),
data: input.serialize(), // serializes the form's elements.
}).then(function (data) {
var category;
$(data).find('a[href*="categories"]').filter(function(){
var data = $(this);
category = data.text().trim();
json.category = category;
});
if (json.category) {
$('.cust-viz.viz-2').html('<iframe class="bubble_chart" src="bubble_chart.html" height="500"></iframe>');
hideShowViz('show');
}
});
});
}
Still returning empty.
There are multiple issues with the code.
Regarding timing, you are likely to have issues with this pattern ...
$.ajax({
...
success: fnA
})
.then(fnB);
... especially if fnB is dependent on something done by fnA.
In practice, it's never good to mix a success handler written as an $.ajax() option with one written as a .then() callback.
So refactor as follows :
$.ajax({
...
})
.then(fnA)
.then(fnB);
Now,
if fnA is asynchronous, it must return a promise to inhibit progress to fnB until that promise resolves.
if fnA is wholly synchronous, as appears to be the case, you can return a value or , more typically, you would merge fnA with fnB.
Note: A success handler written as an $.ajax() option does not possess the same power, and that's the reason why we don't mix success: fn with .then().
$.ajax({
...
})
.then(fnAB);
With those rules in mind, you should be able to better debug the other issues.

jquery modular ajax call

Can someone shed a light on this, so I have multiple GET ajax calls and its only a few lines of codes but I'm basically repeating $.ajax({}) on every function.
Can I have 1 function of $.ajax({}) instead and use this on the functions so I don't need to repeat $.ajax({}) every time?
Something like this maybe but I'm sure its not right but its just a concept.
function ajaxCall(url, method) {
$.ajax({
url: url,
method: method,
success: function(){ } // however this should come in the below function
})
}
function firstCall() {
var url = 'www.urlsample.com';
var methodType = 'GET'
ajaxCall(url, methodType).success() // get the data from this function?
}
Is this somehow possible to do? its to avoid repeating ajax call for every function.
jQuery's .ajax() method returns a Promise-Wrapper.
function ajaxCall(url, method) {
// return promise
return $.ajax({
url: url,
method: method
});
}
function firstCall() {
var url = 'www.urlsample.com';
var methodType = 'GET'
ajaxCall(url, methodType).then(function( result ) {
// success handler
}, function( error ) {
// error handler
});
}

ajax request rely on the previous one

I want to do something like this:
$.ajax({
url: SOMEWHERE,
...
success: function(data){
// do sth...
var new_url = data.url;
$.ajax({
url: new_url,
success: function(data){
var another_url = data.url;
// ajax call rely on the result of previous one
$.ajax({
// do sth
})
}
})
},
fail: function(){
// do sth...
// ajax call too
$.ajax({
// config
})
}
})
the code looks awful for me.
I wonder how to make it looks pretty. Some best practice?
I would consider breaking it up, maybe something like this.
function initialSuccessHandler(data) {
$.ajax({url:data.url, success:secondarySuccessHandler});
}
function secondarySuccessHandler(data) {
//do stuff
}
function initialFailHandler() {
$.ajax({...});
}
$.ajax({url:"whatever.com", success:initialSuccessHandler, fail: initialFailHandler});
There's not a whole lot you can probably do about it other than if the success function are similar (just need different URL's to new AJAX calls for example) you might be able to define a common function to call recursively, like this:
function do_something(data) {
// some logic
$.ajax({
url: data.url,
success: do_something(data);
fail: function (){
// handle failure
}
});
}
Use $.post instead of $.ajax that's lot easier and clean
$.post('yourAjaxUrl.com/index.html',(newVal:'val'), function(data) {
$.post('yourSecondAjaxUrl.com/index.html',{newVal1:data}, function(data) {
//do something
});
});
Or if you want to use GET request use like this.
$.get('yourAjaxUrl.com/index.html',(newVal:'val'), function(data) {
$.get('yourSecondAjaxUrl.com/index.html',{newVal1:data}, function(data) {
//do something
});
});
Other answers are mostly fine too as using functions in a lot of case will definitely help your code. The problem of your function is that it's doing to much things all in once. Decreasing the complexity of the function will help a LOT (separating different action in different functions).
There's some good training videos of Bocoup here which can help you decrease a function complexity: http://training.bocoup.com/screencasts/
Although, a basic answer to the callback inferno:
You could use jquery Deffered who do a good job in certain case by preventing the "indentation pyramid of doom". (But won't decrease the complexity of your function)
$.ajax({
url: SOMEWHERE
})
.pipe(function() {
// First success callback
return $.ajax({
url: new_url
});
}, function() {
// First error callback
$.ajax({
// config
});
// we ain't returning anything so this end here.
})
.done(function( data ) {
// Second success callback
var another_url = data.url;
// ajax call rely on the result of previous one
$.ajax({
// do sth
})
});
Deferred can fit in a whole lot more of context, and learning about them is really useful. That's only the basic idea behind them.
Hope this help!

Ajax jquery synchronous callback success

I have this function that makes an ajax call. I'm describing the problem in the last chunk of code comments.
function doop(){
var that = this;
var theold = "theold";
var thenew = "thenew";
$.ajax({
url: 'doop.php',
type: 'POST',
data: 'before=' + theold + '&after=' + thenew,
success: function(resp) {
if(resp == 1) {
$(that).siblings('.theold').html(thenew);
}
}
});
// I have some code here (out of the ajax) that **further** changes
// the .theold's html beyond what it was changed inside ajax success
// but the change depends on whether the resp (inside the success
// function) returned 1 or not, so this code out here depends on the ajax
// so it looks like I have to turn this ajax call into a sync ajax
return false;
}
Based on the problem as described in the code comments, what changes are best for this situation?
You need to set async: false for synchronous requests like this:
function doop(){
var that = this;
var theold = $(this).siblings('.theold').html();
var thenew = $(this).siblings('.thenew').val();
$.ajax({
async: false,
url: 'doop.php',
type: 'POST',
data: 'before=' + theold + '&after=' + thenew,
success: function(resp) {
if(resp == 1) {
$(that).siblings('.theold').html(thenew);
}
}
});
// some other code
return false;
}
see here for details
Either set the Ajax call to synchronous as stefita pointed out, or just move your code into the success callback. Why can't you do this? Even if it's another Ajax call it still can be done - you can nest them. With the information given by you so far (I can't see the problematic code, nor I have enough domain knowledge about your project) I don't see a problem, really.
I prefer to use callback to do the job because it achieves exactly the same result without actually making it synchronous. I use success:callback and then pass in the callback as a parameter.
function getData(callback) {
$.ajax({
url: 'register/getData',
data: "",
dataType: 'json',
success: callback
});
}
I then call this function like this:
getData(function(data){
console.log(data); //do something
});

Categories