I have a counter where in member can add or remove his number which gets saved in mysql.
i am using the following jquery/ajax to call the function when member clicks on adding or removing. But sometimes removing does not give the exact count, am planning to use setinterval and clearinterval. And also I need to use set interval once, for example, it should query the file only once with in 5 seconds or exact 5 seconds. but below setinterval and clearinterval does not seem to work,
$(function () {
var checkit = function () {
$(".addid").click(function () {
var add_id = $(this).attr("id");
var dataString = 'add_id=' + add_id;
$(".add_show" + add_id).fadeIn(400).html('Updating...');
$.ajax({
type: "POST",
url: "num_check.php",
data: dataString,
cache: false,
success: function (html) {
$(".add_show" + add_id).html(html);
window.clearInterval(nre);
}
});
return false;
});
}
var nre = setInterval(checkit, 5000);
});
Advise and help will be much appreciated
You can modify the Ajax call as -
$.ajax({
type: "POST",
url: "num_check.php",
data: dataString,
cache: false,
async : false,
success: function (html) {
$(".add_show" + add_id).html(html);
window.clearInterval(nre);
}
});
With this, the next Ajax call will not start until the current one has been completed. It should do the trick.
Related
I'm not sure this is the best way to send 2 ajax togheter for facebook api.
But it works, the problem is that sometimes i get the second ajax (result_flow.php) before the first (result.php)
Will be helpful delay second ajax (url:result_flow.php) for 3 seconds or change this code in someway to give a order.
I tried setTimeout but didn't work.
$('#sub').click(function () {
var data = $("input#dataInput").val();
console.log(data);
var total = $("input#totalInput").val();
var subscriber_id = $("input#subscriber_id").val();
var res_name = $("input#res_name").val();
var dataString = 'data='+ data + '&total=' + total + '&subscriber_id=' + subscriber_id+ '&res_name=' + res_name;
console.log(dataString);
$.ajax({
type: "POST",
url: "result.php",
data: dataString,
success: function(data) {
console.log(data);
if(data==='success'){
//localStorage.clear();
MessengerExtensions.requestCloseBrowser(function success() {
console.log("Webview closing");
}, function error(err) {
console.log(err);
});
}
}
});
$.ajax({
type: "POST",
url: "result_flow.php",
data: dataString,
success: function(data) {
setTimeout(function(){
console.log(data);
if(data==='success'){
}
},3000);
}
});
}
I would suggest to use async/await nowadays, it is quite easy to use AJAX calls sequencially:
$('#sub').click(async () => {
...
try {
let data = await $.post({
url: "result.php",
data: dataString
});
if (data === 'success') {
...
}
data = await $.post({
url: "result_flow.php",
data: dataString
});
if (data === 'success') {
...
}
} catch (err) {
console.log(err);
}
});
Not tested, as i donĀ“t work with jQuery - but it should give you the idea. Since $.ajax/$.post supports Promises, it should work with async/await. Be aware that you may need to transpile your code with Babel for older browsers, but i suggest using Babel anyway.
If you want to use both AJAX calls in parallel, use Promise.all (because they do not depend on each other) - the results will be in order, so you can make sure the callback code is called in order.
First, setTimeout() is not working because you put it inside the callback, which means it will be executed when the request is already done. Anyway that's not a proper way to handle such a task, you should put the second request inside the first's callback, so that it will be executed as the first one finishes.
The code looks like this:
$('#sub').click(function() {
var data = $("input#dataInput").val();
console.log(data);
var total = $("input#totalInput").val();
var subscriber_id = $("input#subscriber_id").val();
var res_name = $("input#res_name").val();
var dataString = 'data=' + data + '&total=' + total + '&subscriber_id=' + subscriber_id + '&res_name=' + res_name;
console.log(dataString);
$.ajax({
type: "POST",
url: "result.php",
data: dataString,
success: function(data) {
console.log(data);
if (data === 'success') {
//localStorage.clear();
MessengerExtensions.requestCloseBrowser(function success() {
console.log("Webview closing");
}, function error(err) {
console.log(err);
});
$.ajax({
type: "POST",
url: "result_flow.php",
data: dataString,
success: function(data) {
console.log(data);
}
});
}
}
});
}
Note that in my code the second request is sent just if the first one is successful because it's placed within the if (data === 'success') {...} statement.
You should call them in chain. Success... then... using promise is the best way.
Never trust the order you receive if is not explicitly written by you.
JQuery Ajax
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete()
callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
You can do something like this:
// First Ajax call
$.ajax({
// Do the request
// Remove success to use new promise
})
.done(function( data ) {
// Add the success here
// Add the Second Ajax call here or create a function to call it, whatever you want
});
So, I've looked at several questions and answers here, and they all seem to point in the same direction, but I just can't make it work. . .
I want to read a variable from a file in JQuery, add one to it, then pass it to php to write the new value to the file. I have separate HTML/JavaScript and PHP files.
In the Javascript, I have:
$(document).ready(function(){
var data
$.get('scoredir/data.txt', function(data) {
count = parseInt(data);
count = count +1;
});
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
In the php file (savedata.php), I have:
<?php
$data = $_POST['numberOfPlays'];
file_put_contents("scoredir/data.txt", $data);
?>
It seems like the php file just isn't getting the variable. Anyone know what's wrong?
You're having typical asynchronous AJAX issues. You're $.ajax command is running before your $.get command has completed it's request.
For a quick-fix, try something like this instead:
$(document).ready(function(){
var data;
$.get('scoredir/data.txt', function(data) {
count = parseInt(data);
count = count +1;
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
});
Also, look into deferred objects and promises.
I think behavior of ajax is async so one is getting completed and other is not or may be vice-versa, so you can do this:
$(document).ready(function(){
$.get('scoredir/data.txt', function(data) {
var count = parseInt(data); // you can declare your variable here
count = count + 1;
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
});
One thing I noticed is, $.get is just a shorthand, it is already an asynchronous ajax call. Therefore, in order to work with the result (e.g. count) of that request, your second ajax call needs to go inside the callback of $.get like so:
$(document).ready(function(){
var count;
$.get('http://echo.jsontest.com/key/22', function(data) {
count = parseInt(data.key);
count = count +1;
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
});
Demo: http://jsfiddle.net/3Pykx/
I'm using jquery to load an external page and display it in a DIV called View.
I have 2 buttons Go & Stop.
This is working, but when I click stop it can take a few seconds.
Any way to make it stop straight away ?
$("#Go").click(function () {
$("#view").load("test.php");
refreshId = setInterval(function() {
$("#view").load("test.php"); }, 1000);
});
$("#Stop").click(function () {
clearInterval(refreshId); $("#view").stop();
$.ajax({ url : 'new.php' });
} });
Thanks :)
you can try:
var xhr = $.ajax({
type: "POST",
url: "test.php",
data: "name=John&location=Boston",
success: function(msg){
$("#view").html(msg);
}
});
and stop call:
//kill the request
xhr.abort()
I need to call an ajax a number of times to write to a named pipe in linux.
Here's my code.
Javascript and ajax
var count = 0;
var status = "online";
while(status=="online" && count!=25){
$.ajax({ url: 'http://192.168.5.10/Command.php',
data: {cmd: 'GORIGHT'},
type: 'post',
success: function(data) {
console.log(data);
}
});
count++;
}
Command.php
if($_POST['cmd']==="GORIGHT"){
$fd = fopen("/tmp/myFIFO","w");
fwrite($fd, "GORIGHT\n");
fclose($fd);
echo "SUCCESS";
}
Is this the right way of doing it?. Or is there a much faster way of doing it?.. Will this create a delay?
EDIT: Change the ajax url. sorry about that.
If you need it to be synchronous, you will need to make sure that every calls are waiting completion of the previous one. Something like this should do the trick, untested thought:
var count=0;
var N=25;
loop();
function loop() {
$.ajax({ url: 'http://192.168.5.10/Command.php',
data: {cmd: 'GORIGHT'},
type: 'post',
success: function(data) {
console.log(data);
}
})
.done(function(data){
if (count < N) {
count++;
loop();
}
});
}
Another idea (faster) could be to add an extra parameter in Command.php to allow you to specify how many time a predefined action must be done. You could have something like this instead:
var N=25;
$.ajax({ url: 'http://192.168.5.10/Command.php',
data: {cmd: 'GORIGHT', repeat:N},
type: 'post',
success: function(data) {
console.log(data);
}
});
I want to auto refresh "result" div with ajax & setInterval function.
But there is a one problem. I want auto-refresh in 500ms but sometimes ajax loading more than 500ms. In this cases consists problem. I want to if ajax loading time 750ms then interval time 750 (or any time longer 500ms) else 500. How can I do this ?
var refreshId = setInterval(function()
{
var number=$("#number").html();
$.ajax({
type: 'GET',
url: 'ajax.php',
data: 'num='+number,
success: function(ajaxResult) {
$('#result').html(ajaxResult);
}
});
if(number<100){
number++;
$("#number").html(number);
}
}, 500);
Use setTimeout instead of setInterval. Set timeout function inside ajax response function, and you won't have problems with syncronizing server calls.
(function pollStep(){
var number=$("#number").html();
$.ajax({
type: 'GET',
url: 'ajax.php',
data: 'num='+number,
success: function(ajaxResult) {
$('#result').html(ajaxResult);
setTimeout(pollStep, 500);
}
});
if(number<100){
number++;
$("#number").html(number);
}
})();
Try the condition within success function.
success: function(ajaxResult) {
$('#result').html(ajaxResult);
if(number<100){
number++;
$("#number").html(number);
}
}