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);
}
});
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 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.
}
}
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.
I try to receive a PHP response in my JavaScript.
My PHP looks like this:
some code
if(...) echo "1";
else echo "2";
JavaScript:
function GetChoice() {
var returned="";
$.ajax({
async: false,
cache: false,
url: "http://mydomain.com/script.php",
type: "POST",
dataType:"text",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);
But GetChoice() returns nothing. What's wrong?
UPD: It works if javascript and php script are on the same server. My scripts in different domains.
Try this :
temp1.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function GetChoice() {
var returned = "";
$.ajax({
async: false,
cache: false,
type: "POST",
url: "http://localhost/temp2.php",
data: { name: "John"}
}).done(function( msg ) {
returned = msg;
});
return returned;
}
var r = GetChoice();
alert(r);
</script>
temp2.php
<?php
echo $_REQUEST["name"];
?>
its working....!
try this:
function GetChoice() {
var returned = "";
$.ajax({
async:false,
cache:false,
url:"http://mydomain.com/script.php",
type:"POST",
dataType:"text",
success:function (data) {
alert(data);
}
});
}
The problem is, in your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.
Here is explanation.
How do I return the response from an asynchronous call?
Luck,
GetChoice() will return nothing before the callback in success runs.
The callback, which is the function you define as the success paramater will not fire until the data have been requested from the server.
This is asyncronous (the A in AJAX) so the rest of the code with continue causing the GetChoice() function to return before the callback has been run
this is the script
<script type="text/javascript">
$.ajax({
async:false,
cache:false,
url:"http://path.com/to/file",
type:"POST",
dataType: "html",
data: 'data',
success: function(data){
alert(data);
}
});
and in your PHP file write this code
<?php
function test()
{
$str = 'This is php file';
return $str;
}
echo test();
?>
Make sure the path to the php file is correct AND add the script in another PHP file. Basically you need 2 files. Just tested this in my editor and works ..
function GetChoice() {
var returned="";
$.ajax({
url: "../script.php",
type: "POST",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);