Jquery poll request only if variable != 'something' - javascript

I have this code:
<script>
$(function() {
(function poll(){
setTimeout(function(){
var process_id = $("#form3_progress_process_id").val();
if(process_id != 'undefined') {
$.ajax({
type: "POST",
url: "grab.php",
data: "action=step3_progress&process_id=" + process_id,
success: function(data){
console.log("successful");
}, dataType: "json", complete: poll, timeout: 30000 });
}
}, 2000);
})()
});
</script>
<input type="hidden" id="form3_progress_process_id" value="undefined">
What i want is that it only sends the query if the value from the input form3_progress_process_id is not 'undefined'.
At the start it is "undefined" but after some time it get's changed with jquery.
However, the above code does not work for any reason. It does not start sending the request after the value has been changed.
What did i wrong?

Your code will fire only if the input changes in the first 2 seconds from the begining. You should add a call to the poll method in your else, so the cycle doesn't break:
$(function() {
(function poll(){
setTimeout(function(){
var process_id = $("#form3_progress_process_id").val();
if(process_id != 'undefined') {
$.ajax({
type: "POST",
url: "grab.php",
data: "action=step3_progress&process_id=" + process_id,
success: function(data){
console.log("successful");
}, dataType: "json", complete: poll, timeout: 30000 });
}else{
poll(); ////Add this!!
}
}, 2000);
})()
});
Cheers, from La Paz, Bolivia

Unless your hidden input changes within the 2 seconds, the timer will not fire again.
change to setInterval
setInterval(function(){
var process_id = $("#form3_progress_process_id").val();
if(process_id != 'undefined') {
$.ajax({
type: "POST",
url: "grab.php",
data: "action=step3_progress&process_id=" + process_id,
success: function(data){
console.log("successful");
}, dataType: "json", complete: poll, timeout: 30000 });
}
}, 2000);
})()
});

Related

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

jQuery AJAX: Uncaught SyntaxError: Unexpected token

I am trying to update my div content with new content when the user uses the search textbox:
$('#business_request_filter_search_textbox').on('input propertychange paste', function () {
$.ajax({
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name";
type: "GET",
cache: false,
data: { search: $('input#business_request_filter_search_textbox').val() },
beforeSend: function(xhr) {
$('#request_area').html('<center>Please wait while we gather results...</center>');
},
success: function(data) {
$('#request_area').html(data);
},
});
});
Now I have a dropdown selecting what they want to filter the search by, the username or the business name. This is the line that is throwing the error.
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name";
Am I doing something wrong?
You should have a comma ',' at the end of the url line:
$('#business_request_filter_search_textbox').on('input propertychange paste', function () {
$.ajax({
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name",
type: "GET",
cache: false,
data: { search: $('input#business_request_filter_search_textbox').val() },
beforeSend: function(xhr) {
$('#request_area').html('<center>Please wait while we gather results...</center>');
},
success: function(data) {
$('#request_area').html(data);
},
});
});
You don't have dataType defined for the ajax call.
Add dataType which is the expected format of your ajax request which can be text, json etc
Try This Code
$('#business_request_filter_search_textbox').on('input propertychange paste', function () {
$.ajax({
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name",
type: "GET",
cache: false,
data: { search: $('input#business_request_filter_search_textbox').val() },
beforeSend: function(xhr) {
$('#request_area').html('<center>Please wait while we gather results...</center>');
},
success: function(data) {
$('#request_area').html(data);
},
});
});
Hope This help You :) Enjoy :)

how do to polling in jquery?

I have a Post call. After the result I want to do another get CALL to check the status. But only if the status is FINISHED.
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
.. now I want to do the polling on the status
jQuery.ajax({
type: "GET",
dataType: "json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
// to continue only if status if Finished
},
error: function() {
}
});
}
});
$.ajax returns a deferred object.
You can do something like below. More info here
var doSomething = $.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
function doneCallback(){
// Handle exit condition here.
doSomething();
}
function failCallback(){
// Handle failure scenario here.
}
doSomething.then(doneCallback, failCallback)
Just set your code in a function:
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
doPoll();
}
});
var doPoll = function() {
jQuery.ajax({
type: "GET",
contentType: "application/json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
//do stuff
doPoll();
},
error: function() {
//handle error
}
});
}
You can try to export the ajax call to a function and use recursion to pool.
Note: You should have a max counter so that you do not flood server with infinite calls.
var max_count = 20;
var counter = 0;
function getStatus() {
jQuery.ajax({
type: "GET ",
contentType: "application / json ",
url: " / getStatusUrl,
success: function(data, textStatus, response) {
// to continue only if status if Finished
if (textStatus != "status" && ++counter < max_count) {
getStatus();
}
},
error: function() {}
});
}

Not refreshing data each time

I have weired problem in my project.I have 2 tabs and in one tab i have chekboxes and submit button and user will select from checkboxes and on button click he will get what he has selected from checkboxes in another tab.It runs perfectly.But sometimes it does not refresh the data from ajax ,jquery and i have to complete refresh my page.I am not able to identify the problem as i am not getting any error. Atleast i have to click for more than 15 times then it will not refresh the data otherwise it works fine.
Here is my js code:
function getFahrzeuge() {
var opts = [];
$("#fahrzeuge input[type='checkbox']").each(function () {
if ($(this).is(':checked'))
{
opts.push($(this).attr("id"));
}
});
return opts;
}
function saveFahrzeugeWidget(opts){
if(opts.length == 0) return false;
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {'filterOpts' :opts, 'aktion' : 'save-widget-vehicle'},
success: function(data){
//getFahrzeugeWidget();
$('#fahrzeuge').html(data['html']);
},
error: function(data){
console.log(data);
}
});
}
function getFahrzeugeWidget(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts:opts, 'aktion' : 'get-widget-vehicle'},
success: function(data){
$('#fahrzeuge').html(data.html);
},
error: function(data){
console.log(data);
}
});
}
function getFahrzeugeWidgetEdit(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts:opts, 'aktion' : 'get-widget-vehicle-edit'},
success: function(data){
$('#fahrzeuge').html(data.html);
},
error: function(data){
alert('error' + data);
}
});
}
$('#fahrzeuge .butt-rahmen').live('click', function(){
var opts = getFahrzeuge();
if($(this).attr('id') == 'saveId')
{
saveFahrzeugeWidget(opts);
if($('#fahrzeuge input[type="checkbox"]:checked').length <=0) {
alert('überprüfen Sie bitte atleast ein fahrzeuge');
//getFahrzeugeWidgetEdit(opts);
}
}
});
The answer is getting cached. And you are receiving the same answer. Try to add a new parameter to data as timestamp.
So your data should look like this.
data: {'filterOpts' :opts, 'aktion' : 'save-widget-vehicle', 'timestamp': new Date().getTime()},

jQuery / Javascript - run AJAX request after X seconds

so I have this code:
$('input.myinput').each(function(){
var id = $(this).val();
var myajax = function(){
$.ajax({
url: ajax_url,
type: "GET",
data: ({
code: id
}),
beforeSend: function() { },
error: function(request){ },
success: function(data) { alert(data); }
});
setTimeout('myajax()', 10000);
}
myajax();
});
I wanted the ajax() request above to run 10 seconds after the page was loaded, so I used setTimeout, but it doesn't work :(
the ajax thingy runs right after the page loads, not 10 secs after...
what am I doing wrong?
$('input.myinput').each(function(){
var id = $(this).val();
var myajax = function() {
$.ajax({
url: ajax_url,
type: "GET",
data: ({
code: id
}),
beforeSend: function() { },
error: function(request){ },
success: function(data) { alert(data); }
});
//if you need to run again every 10 seconds
//setTimeout(myajax, 10000);
};
setTimeout(myajax, 10000);
});
I'd do a few things differently..
function myajax(id) {
$.ajax({
url: ajax_url,
type: "GET",
data: ({
code: id
}),
error: function(request){ },
success: function(data) { alert(data); }
});
setTimeout('myajax(id)', 10000); // you really want it to run AGAIN in another 10 seconds?
}
...
$(document).ready(function() {
$('input.myinput').each(function(){
var id = $(this).val();
setTimeout('myajax(' + id + ')',10000);
});
});
There's no reason to redeclare myajax as a new function for every input, when you can declare it once and pass in a new ID variable each call.

Categories