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.
Related
I have a chat app that show the previous messages by fetching the datas repeatedly using setInterval(). So as most of the chatting apps do, I also want to keep the scroll bar at the last message(i.e at the bottom). But here comes the problem ,as I am using setInterval to fetch The data repeatedly it also execute that code which keep the scroll bar at the bottom and hence it become impossible to scroll up to check the previous messages.
<script>
var currentID = null;
var chatTimer = null;
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
//fetch_chat();
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$("#messages").show();
$('#messages').html(data);
$("div.area").show();
//chatTimer = setTimeout(fetch_chat, 500); //request the chat again in 2 seconds time
$("#messages").animate({ scrollTop: $(document).height() }, "fast");
}
});
}
$(document).ready(function() {
fetch_data();
$(document).on('click', '.first_name', function() {
currentID = $(this).data("id1");
//immediately fetch chat for the new ID, and clear any waiting fetch timer that might be pending
//clearTimeout(chatTimer);
fetch_chat();
});
function scrollToBottom() {
$("#messages").scrollTop(1e10); // Lazy hack
}
setInterval(function() {
fetch_chat();
}, 500);
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
scrollToBottom();
});
// alert(text);
});
//this will also trigger the first fetch_chat once it completes
});
</script>
plz tell me the correct way to do this.
Keep a variable outside the setInterval method that sets if it is the first time that the data is fetched. Scroll only the first time. Then, change it and it will never scroll again.
var currentID = null;
var chatTimer = null;
var firstTime = true;
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
//fetch_chat();
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$("#messages").show();
$('#messages').html(data);
$("div.area").show();
//chatTimer = setTimeout(fetch_chat, 500); //request the chat again in 2 seconds time
if (firstTime) {
firstTime = false;
$("#messages").animate({ scrollTop: $(document).height() }, "fast");
}
}
});
}
I have the following code but it doesn't seem to work properly. I cant understand why.
JS
var updateBoard = function() {
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response);
}
});
setTimeout(updateBoard, 1000);
};
PHP
if(isset($_POST['codes'])) {
echo "test";
}
You can try with following approach:
var updateBoard = function() {
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response);
setTimeout(updateBoard, 1000); //calling the function after 1 sec after we get the response
}
});
};
updateBoard(); //calling it right away
As #Smiranin said, just call setTimeout outside of the function:
var updateBoard = function(){
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response)
}
})
};
setTimeout(updateBoard, 1000);
Or just use setInterval instead of SetTimeout
setInterval(updateBoard, 1000);
You can try setInterval() if you want to run this in every seconds.
var updateBoard = function() {
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response);
}
});
};
setInterval(updateBoard, 1000);
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I want to refresh the countdown timer of multiple items on my page. Each timer has the class "refresh-item". It works well with just one item, but if I've multiple items (that means different countdown timers also), it seems to only pick the latest id.
This is my JQuery code:
function timeLeft()
{
var data = $(".refresh-item").attr("data-content");
var dataString = 'case=refresh_item&' + data;
$.ajax({
type: "GET",
url: "ajax.php",
dataType: "html",
data: dataString,
success: function(result)
{
$(".refresh-item").html(result);
}
});
}
window.setInterval(function(){
timeLeft();
}, 1000);
Each item also has the attribute "data-content" where the specific id of an item is saved. How is it possible to select the specific id of a specific item (to show the individual countdown timer then)?
Use each() method in jQuery to iterate
function timeLeft() {
$(".refresh-item").each(function() {
$this = $(this);
var data = $this.attr("data-content");
var dataString = 'case=refresh_item&' + data;
$.ajax({
type: "GET",
url: "ajax.php",
dataType: "html",
data: dataString,
success: function(result) {
$this.html(result);
}
});
});
}
window.setInterval(function() {
timeLeft();
}, 1000);
Use $.each function of jquery:
function timeLeft()
{
$.each($(".refresh-item"), function(){
$this = $(this);
var data = $this.attr("data-content");
var dataString = 'case=refresh_item&' + data;
$.ajax({
type: "GET",
url: "ajax.php",
dataType: "html",
data: dataString,
success: function(result)
{
$this.html(result);
},
complete: function(){}
});
)
}
window.setInterval(function(){
timeLeft();
}, 1000);
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);
})()
});
I have the following code which work fine in case of success and error. But what I want to do is make another ajax call in case of error. to some other URL . what is the correct way of doing it. I tried calling the ajax function again but it resulted in a javascript error
this is the sample of working code.
$('#save-walkin').die('vclick').live('vclick', function(e) {
e.preventDefault();
$.mobile.showPageLoadingMsg();
$.ajax({
url: 'http://www.someurl.com',
method: 'POST',
data: $('#form-createwalkin').serialize(),
success: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
},
error: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
}
});
return false;
});
Where as what I am trying to do is something like this. but It's not working
$('#save-walkin').die('vclick').live('vclick', function(e) {
e.preventDefault();
$.mobile.showPageLoadingMsg();
$.ajax({
url: 'http://www.someurl.com',
method: 'POST',
data: $('#form-createwalkin').serialize(),
success: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
},
error: function(){
$.ajax({
url: 'http://www.someotherurl.com',
method: 'POST',
data: $('#form-createwalkin').serialize(),
success: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
},
error: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
}
}
});
return false;
});
It's just not formed correctly. It should look like this:
$('#save-walkin').die('vclick').live('vclick', function(e) {
e.preventDefault();
$.mobile.showPageLoadingMsg();
$.ajax({
url: 'http://www.someurl.com',
method: 'POST',
data: $('#form-createwalkin').serialize(),
success: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
},
error: function(){
$.ajax({
url: 'http://www.someotherurl.com',
method: 'POST',
data: $('#form-createwalkin').serialize(),
success: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
},
error: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
}
});
}
});
return false;
});
Use Deferred objects, those are objects to manipulate async calls, you can solve :
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
.then(myFunc, myFailure);
This way myFunc executes after the 2 ajax calls are made, and myFailure if either one has an error.
You can read more about it in the jquery official documentation:JQuery Deferred Object
Something like this, storing the Ajax in an object gives you a lot more flexibility, and in the error (fail) function, just call the function again with a different URL.
Will probably need some adjusting, and a counter if it's only suppose to repeat once!
runAjax('http://www.someurl.com');
funcion runAjax(url) {
var jqXHR = $.ajax({
url: url,
method: 'POST',
data: $('#form-createwalkin').serialize()
});
}
jqXHR.done(function() {
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
}.fail(function() {
runAjax('http://www.someotherurl.com');
});
I think first you have to check your callback,, or error what you are getting..
may be it will help you..
$.ajax({
statusCode: {
404: function() {
alert('page not found');
}
}
});
you can also try to give
var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
url: "script.php",
type: "POST",
data: {id : menuId},
dataType: "html"
});
request.done(function(msg) {
$("#log").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});