$.post call from a loop - php

I have an ul with 9 li elements. I want to load some information to these li elements through ajax in asynch mode.
It's so simple, isn't it?
I just created a for(i = 1; i<=9; i++) loop, and called the $.post.
Fail: i will be always 10, because the for loop running more faster, then the $.post. So let's search the $.post in loop on net.
I found three solutions. Two are here, and one is here.
All of it has the same effect: does not works asynchronously. Every time it load the first, then second, then third etc... Sometimes the order is changing, but every request wait while the previous finish.
I am using WIN 10 64bit, Apache 2.4 64 bit, php 5.6 64bit. Already tried on debian box, effect is the same.
In my php file, there is a sleep(1) and an echo 'a'.
My first attempt:
$('.chartContainer').each(function(index,obj) {
var cnt = index + 1;
$.post(getBaseUrl() + 'ajax.php', {dateTime: $('#chart_' + cnt).data('time'), action: 'getChartByDateTime'}, function (reponse) {
$(obj).html(reponse);
});
});
My second attempt:
for (var i = 1; i <= 9; i++) {
(function (i) {
var $obj = $('#chart_' + i);
$.post(getBaseUrl() + 'ajax.php', {dateTime: $('#chart_' + i).data('time'), action: 'getChartByDateTime'}, function (reponse) {
$($obj).html(reponse);
});
})(i);
}
My third attempt:
function loadResponse(i) {
var $obj = $('#chart_' + i);
$.post(getBaseUrl() + 'ajax.php', {dateTime: $('#chart_' + i).data('time'), action: 'getChartByDateTime'}, function (reponse) {
$($obj).html(reponse);
});
}
$(function () {
for (i = 1; i<=9; i++) {
loadResponse(i);
}
});
Expected result:
Every 9 li loaded in 1 second in the same time.
Can somebody lead me to the right solution?
EDIT
Maybe I was not clear. In the production, the script will run for approx. 3 seconds. If I send one request to get all the data back, then it will take 9*3 = 27 seconds while the response arrives. This is why I want to send 9 request, and get back all the data in 3 seconds. I think this is why we use threads.
What I want is to get all the data for all li in the "same" time. Not one by one, or get all in one request.
EDIT 2
Ok guys, shame on me, I think I mislead all of you. There is a session start in my php script.
If I remove everything, and then just echo something and die after sleep. In this case 5 request is responding in 1 sec, other 4 is later. But I think that is a new thred.

From the jQuery manual:
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
Are you sure the requests are not sent by your browser? It is possible your php script does not allow multiple sessions. Have you tried inspecting the ajax calls with firebug/chrome inspector?
Edit:
PHP writes its session data to a file by default. When a request is made to a PHP script that starts the session (session_start()), this session file is locked. What this means is that if your web page makes numerous requests to PHP scripts, for instance, for loading content via Ajax, each request could be locking the session and preventing the other requests from completing.
The other requests will hang on session_start() until the session file is unlocked. This is especially bad if one of your Ajax requests is relatively long-running.
Possible solutions:
Do not use sessions when you don't need them
Close your session after reading/writing the necessary information:
session_write_close();
Store your sessions in Redis/mySQL for example

function loadResponse(i) {
var $obj = $('#chart_' + i);
$.post(getBaseUrl() + 'ajax.php', {dateTime: $('#chart_' + i).data('time'), action: 'getChartByDateTime'}, function (reponse) {
$($obj).html(reponse);
if(i<=9) loadResponse(++i);
});
}
var i = 1;
$(function () {
loadResponse(i);
});
Here loadResponse function is being called first time at the page load. Then it is being called recursively on the response of the POST request.

You can try this.
for (var i = 1; i <= 9; i++) {
var $obj = $('#chart_' + i);
var time = $('#chart_' + i).data('time');
(function ($obj, time) {
$.post(getBaseUrl() + 'ajax.php', {dateTime: time, action: 'getChartByDateTime'}, function (reponse) {
$obj.html(reponse);
});
})($obj, time);
}

Try sending all the data at once
var dateTime = [];
$('.chartContainer').each(function(index,obj) {
var cnt = index + 1;
dateTime.push({date:$('#chart_' + cnt).data('time'),el:'#chart_' + cnt});
});
$.post(getBaseUrl() + 'ajax.php', {dateTime:dateTime , action: 'getChartByDateTime'}, function (reponse) {
$.each(reponse,function(i,v){
$(v.el).html(v.procesedData);
});
});
php :
$ajaxresponse =[];
foreach($_POST['dateTime'] as $datetime) {
$data = $datetime['date'];//change this with your results
$ajaxresponse[]= array('procesedData'=>$data,'id'=>$datetime['id'])
}
return json_encode($ajaxresponse);

Related

Run Php script constantly and if connected to internet as windows service which inserts data into xampp server

I am developing a desktop app which will store data offline but whenever the desktop gets a connection a php script should detect it (cron job) and upload it to the online server like this:
while(true){
if(connected == true){
// run code;
else{
// wait to get connection
}
}
Hi Zaki Muhammad Mulla,
I did some testing myself, and I came up with the following piece of code
Running the code snippets here won't work because this is a sandbox and there is no access to the localstorage here.
Make sure to include Jquery in your code
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous">
</script>
Then the actual function that will do the trick:
function processData(online){
if(online == true){
//My connection is online so I can execute code here
//If data is stored locally, read it and post it with an $.ajax POST
//I can loop through all the data and insert it per found row of data
for(var i=0, len=localStorage.length; i<len; i++) {
var key = localStorage.key(i);
var value = localStorage[key];
$.ajax({
type: 'POST',
url: 'PATH/TO/SCRIPT.php',
data: { column: key, value: value },
success: function(response) {
//The insert was succesful
content.html(response);
}
});
}
}else{
//Create your own loop here and fill data accordingly
for(i = 0; i < 12; i++){
localStorage.setItem("lastname" + i, "Smith");
localStorage.setItem("firstname" + i, "John");
localStorage.setItem("age" + i, "22");
localStorage.setItem("job" + i, "Developer");
}
}
}
And at last the window.setInterval() to run a function every x seconds (Keep in mind 1 second = 1000 in the settimeout)
<script>
window.setInterval(function(){
var online = navigator.onLine;
processData(online);
}, 1000);
</script>
Hope this may help you on your quest!
The sources I used:
https://medium.com/#Carmichaelize/checking-for-an-online-connection-with-javascript-5de1fdeac336
Ajax passing data to php script
https://www.w3schools.com/html/html5_webstorage.asp
https://www.taniarascia.com/how-to-use-local-storage-with-javascript/
Get HTML5 localStorage keys
HTML5 localStorage getting key from value
What's the easiest way to call a function every 5 seconds in jQuery?

Why are jQuery AJAX request to Symfony Controllers are handled in parallel instead of async?

When posting simple data to a plain PHP script using jQuery $.ajax({...}) multiple requests are handled in parallel. When doing to same with a Symfony 2.8 controller as a target, the request is handled synchronously. Why is this?
Plain HTML and PHP setup
// Plain PHP file: /testscript.php
<?php
sleep($_POST['time']);
echo $_POST['id'];
// Plain HTML file: /testpage.html
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
Click here:
<div id='testbtn' style="background-color: #abc">Click</div>
<script>
$(document).ready(function() {
var start = new Date().getTime();
var count = 1;
$("#testbtn").click(function() {
var time = new Date().getTime();
console.log('Click at '+count+':' + (time - start));
$.ajax({
url : '/testscript.php',
type : "post",
data : {'time':3, 'id':count},
async: true,
context : this,
success : function(data) {
var end = new Date().getTime();
console.log('Click Success: ' + data + " - " + (end - start));
}
});
count++;
});
$.ajax({
url : '/testscript.php',
type : "post",
data : {'time':10, 'id':0},
async: true,
context : this,
success : function(data) {
var end = new Date().getTime();
console.log('Auto Success: ' + data + " - " + (end - start));
}
});
console.log('Ajax fired');
});
</script>
</body>
</html>
Symfony Setup
// Controller Action to handle /sym_testscript.php
public function testScriptAction(Request $request) {
sleep($request->get('time'));
return new Response($request->get('id'), Response::HTTP_OK);
}
// Controller Action to handle /sym_testpage.php
public function testPageAction() {
return $this->render('MyBundle::sym_testpage.html.twig');
}
// Twig-Template for /sym_testpage.html
...exactly the same HTML code as above. Twig is only used to insert URL
...
$.ajax({
url : '{{ path('sym_testscript') }}',
...
The page /testpage.html calls /testscript.php when being loaded with a sleep-value of 10 seconds. When clicking the Button a few times the page load waterfall looks something like this:
1: ======================================== // initial call of testscript.php
2: ============ // testscript.php called by 1 click
3: ============ // testscript.php called by 2 click
4: ============ // testscript.php called by 3 click
Each click on the Button immediately calls the testscript.php which is then executed in parallel to the initial call and other button calls. So each click-call runs 3 seconds.
When using the Symfony version instead, the waterfall looks like this:
1: ======================================== // initial call of testscript.php
2: ====================================================
3: ================================================================
4: ============================================================================
Again, each button click immediately calls the /sym_testscript.php. But now the calls are handled one after the other. Thus the total runtime is not 10 seconds but 19 = 10 + 3 + 3 + 3...
When using the sym_testscript.php within the plain HTML file as the target, the result is the same. Thus the problem seems to be within the Symfony controller...
Why is this?
Why are the ajax-calls not handled in parallel when using the Symfony solution?
As soon as you start a session in php, php will lock it and subsequent requests will have to wait until the session is available again.
So if your symfony script uses sessions, you can only execute 1 request at a time using that session while the session is open.
Disabling sessions (if that even is an option...) or closing it when you don't need it any more will allow parallel requests.

Retrieving mysql data using ajax and then manipulating it

My question has part solutions on this site but not a complete answer.
On my wordpress homepage I display a counter of the number of questions answered within our webapp. This is displayed using jQuery and AJAX to retrieve the question count from a php file and works fine with this code.
jQuery(document).ready(function() {
function load() {
jQuery.get('/question_count.php', function(data) {jQuery('#p1').html( data ); });
}
load();
setInterval(load,10000);
});
Is there a way to display counting up to the new number retrieved rather than just immediately displaying it?
Something like this?
function countTo(n) {
var p = $("#p1"),
c = parseInt(p.html(), 10) || 0,
dir = (c > n ? -1 : 1); // count up or down?
if (c != n) {
p.html((c + dir) + "");
setTimeout(function() {
countTo(n);
}, 500);
}
}
Call it in your success handler
jQuery.get('/question_count.php', function(data) {
var n = parseInt(data, 10);
countTo(n);
});
Example
You will need to do a setInterval event so that the count up is visable to human eyes.
This may be a problem if you eventually reach enough questions where the count takes a long time to reach the end.
Code will look like this:
function load(){
jQuery.get('/question_count.php', function(data){
var curr = 0;
var max = parseInt(data);
var interval = setInterval(function(){
if(curr==max){
clearInterval(interval);
}
jQuery('#p1').html( curr );
curr+=1; //<-- if the number of questions gets very large, increase this number
},
10 //<-- modify this to change how fast it updates
});
}
}

Using jQuery Growl with PHP and MySQL

On my database I am planning to create a table storing messages to alert users of anything they need to do.
I am looking at using a jQuery growl like notification method but I'm confused at how I would begin building it.
The data would be added into the database using the standard MySQL insert method from a form but how would I select messages from the database to display using the jQuery growl.
Would this require the use of AJAX?
This is the JavaScript code I have so far, i was wondering how I would implement the PHP code alongside it so that I can pull out data from my tables to display as notifications:
<script type="text/javascript">
// In case you don't have firebug...
if (!window.console || !console.firebug) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
window.console = {};
for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {};
}
(function($){
$(document).ready(function(){
// This specifies how many messages can be pooled out at any given time.
// If there are more notifications raised then the pool, the others are
// placed into queue and rendered after the other have disapeared.
$.jGrowl.defaults.pool = 5;
var i = 1;
var y = 1;
setInterval( function() {
if ( i < 3 ) {
$.jGrowl("Message " + i, {
sticky: true,
log: function() {
console.log("Creating message " + i + "...");
},
beforeOpen: function() {
console.log("Rendering message " + y + "...");
y++;
}
});
}
i++;
} , 1000 );
});
})(jQuery);
</script>
<p>
</span>
<p>
PHP is running on the server and JavaScript is running on the client.
So Yeah, you'll need AJAX.
Well, there would be other ways, but they are more work than simply setting up AJAX. Especially so since you work with jQuery which handles most of the AJAX stuff for you.
Let it call a small PHP script that fetches the Rows from the DB, outputs them in your preferred Way (XML or JSON) and exits.
The usual jQuery AJAX tutorials should cover exactly that.
If your App is Multi-User don't forget to send a UserID in the Request so PHP knows what Rows to pull.

why won't my ajax work asynchronously

I'm having trouble understanding why my code will not work asynchronously.
When running asynchronously the get_price.php always receives the same $_GET value even though the alert before outputs a unique $_GET value.
var arraySize = "<? echo count($_SESSION['items']); ?>"; //get items count
var pos = 0;
var pid;
var qty;
getPriceAjax();
function getPriceAjax()
{
pid = document.cartItemForm.elements[pos].id; //product id
qty = document.cartItemForm.elements[pos].value; //quantity
alert('Product: ' + pid + ' Quantity: ' + qty);
$.ajax({
url:"includes/ajax_php/get_price.php",
type:"GET",
data:'pid='+pid+'&qty='+qty,
async:true,
cache:false,
success:function(data){
while(pos < arraySize)
{
document.getElementById(pid + 'result').innerHTML=data;
pos++;
getPriceAjax();
}
}
})
}
I dealt with a similar problem. I can't quite remember what was going on, so this answer may not be too helpful. Your server may be caching the response. Try using POST.
Try adding a bit of random number to your get URL so the server doesn't cache it, like so:
url:"includes/ajax_php/get_price.php&rnd=" + Math.floor(Math.random()*10000)
It could also be a timing issue. Since it is asynchronous, it could be stepping through the loop and alerting before the value comes back. Your pos counter won't get incremented until it returns, so you will always be getting the price of pos = 0 until your call comes back. I would move the incrementer outside the success function. Also, try moving the alert inside of the success function.
function getPriceAjax()
{
pid = document.cartItemForm.elements[pos].id; //product id
qty = document.cartItemForm.elements[pos].value; //quantity
$.ajax({
url:"includes/ajax_php/get_price.php",
type:"GET",
data:'pid='+pid+'&qty='+qty,
async:true,
cache:false,
success:function(data){
while(pos < arraySize)
{
alert('Product: ' + pid + ' Quantity: ' + qty);
document.getElementById(pid + 'result').innerHTML=data;
getPriceAjax();
}
}
});
pos++;
}
Recursion almost beat me...
Instead of using a while loop it should have been an if conditional statement.
while(pos < ArraySize) WRONG! - executes the first set of parameters arraySize times.
if(pos < ArraySize) CORRECT! - executes the first, then second, and so on...

Categories