How delay ajax call by few seconds - php

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

Related

Trying to pass a variable from JQuery to PHP

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/

Simple Ajax Post to PHP echo

I have the following code on product.php .. can't seem to echo post variable from ajax post. Alert displays fine. Please help
JQUERY
document.getElementById("LBTest").onchange = function(){
var lbtest = $('#LBTest :selected').val();
$.ajax({
type: "POST",
url: "product.php",
data: {test: lbtest},
success: function()
{
alert("Successful");
}
});
}
PHP
if(isset($_POST['test'])){
$data = $_POST['test'];
echo $data;
}
You need to do something with the data you receive from the ajax call. For example, to put the result into a <div> called resultDiv:
success: function(data)
{
$('#resultDiv').html(data);
alert("Successful");
}
$.ajax({
type: "POST",
url: "product.php",
data: {test: lbtest},
success: function(data)
{
alert("Successful");
}
});
You need to add the data to the success function that is called. You can do this locally or reference another function meant to handle responses coming back from the server.
success: function(data)
{
console.log(data);
alert(data + " was returned from the server");
}
It is a good idea on the server side to json_encode the objects that are being returned and using error codes that can be more appropriately handled on the client.
handleResponse(data) {
var data = $.parseJSON(data);
if(data.code >= 200 || data.code < 300) {
// modify the dom, add data to a model, take over the world with your web app.
}
}

Adding Setinterval and clear interval to my query

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.

Ajax call a number of times

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

Jquery AJAX response not working

For some reason this jQuery function is not working properly. Here's my code... the response div is not updating with my response.
WHEN AJAX FUNCTION IS CALLED
if ($action == 'sort') {
echo 'getting a response';
return 0;
}
JQuery FUNCTION
function sort() {
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data:"sort_by=" + document.getElementById("sort_by").value +
"&view_batch=" + document.getElementById("view_batch").value,
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
}
DIV TO REPLACE
<div id="ajaxPhotographSortResponse"></div>
Move the action=sort into the data property of the $.ajax function. You're making a POST request, but appending data onto your query string like a GET request. Data only appends to the query string if it's a GET request.
Example:
$.ajax({
type: "POST",
url: "contributor_panel.php",
data: {action:'sort', sort_by: $('#sort_by').val(), view_batch: $('#view_batch').val()},
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
http://api.jquery.com/jQuery.ajax/
Instead of concatenating the arguments you are passing to your server side script I would recommend you using the following syntax. Also if you already use jQuery you no longer need the document.getElementById function:
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data: { sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() },
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
or even shorter using the .load() function:
$('#ajaxPhotographSortResponse').load('contributor_panel.php?action=sort',
{ sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() });

Categories