why won't my ajax work asynchronously - php

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...

Related

Slow SQL Query / Displaying (PHP / jQuery)

I have a request to get data in my mySQL database (36,848 entries).
Then I format and append them with jQuery on my web page.
These two operations take 2 minutes and 30 seconds.
During this time, no other operation is possible on the page.
Is there a way to optimize this to speed up the process?
Like this, it's unusable.
My PHP function
<?php
function get_my_customers() {
$req = $bdd->prepare("SELECT * FROM clients ORDER BY raison_sociale");
$req->execute();
$customers = $req->fetchAll(PDO::FETCH_ASSOC);
return $customers;
}
if(isset($_POST['ajax'])){
$result = get_my_customers();
echo json_encode($result);
}
?>
Data retrieval in jQuery (Ajax)
function get_my_customers(){
var customers;
$.ajax({
url: "model/application/*******/customers/get_my_customers.php",
async: false,
type: "POST",
dataType: 'json',
data: {ajax: 'true'},
success: function(data)
{
customers = data;
}
});
return customers;
}
var my_customers = get_my_customers();
$('#customers_list').append('<div class="list_card" card="customers_list"></div>');
$.each(my_customers, function(key, val){
if(val.enseigne == null){
var enseigne = '';
}else{
var enseigne = ',' + val.enseigne;
}
$('.list_card[card="customers_list"]').append(''+
'<div class="list_card_element">'+
'<div><b>'+ val.numero_client +'</b></div>'+
'<div>'+
'<b>'+ val.raison_sociale +'</b>' + enseigne +
'<br>'+
val.cp_livraison + ', ' + val.adresse_livraison +
'</div>'+
'</div>'
);
});
Do you know what I can do to speed up processing time?
I've tried limiting the SELECT query to only the fields I need but that doesn't improve processing time.
I wonder if it's not rather the jQuery layout that takes time rather than the SQL query.
Thank you !
Use devtools in your browser to determine which step is causing the slowdown. The Network tab will show you the Ajax request and the time interval of the data fetch. If that time interval is not the issue, it's likely with the Javascript. You can get deeper on the Javascript performance using the Performance tab.
try to use indexes see that
MySQL can use an index on the columns in the ORDER BY (under certain conditions). However, MySQL cannot use an index for mixed ASC,DESC order by (SELECT * FROM foo ORDER BY bar ASC, pants DESC). Sharing your query and CREATE TABLE statement would help us answer your question more specifically.
I just passed from 2 minutes and 30 secondes to 14 secondes with this optimization.
var construct_customers = "";
$.each(my_customers, function(key, val){
if(val.enseigne == null){
var enseigne = '';
}else{
var enseigne = ',' + val.enseigne;
}
construct_customers += '<div class="list_card_element">'+'<div><b>'+ val.numero_client +'</b></div>'+'<div>'+'<b>'+ val.raison_sociale +'</b>' + enseigne +'<br>'+val.cp_livraison + ', ' + val.adresse_livraison +'</div>'+'</div>';
//OLD CODE
// $('.list_card[card="customers_list"]').append(''+
// '<div class="list_card_element">'+
// '<div><b>'+ val.numero_client +'</b></div>'+
// '<div>'+
// '<b>'+ val.raison_sociale +'</b>' + enseigne +
// '<br>'+
// val.cp_livraison + ', ' + val.adresse_livraison +
// '</div>'+
// '</div>'
// );
});
$('.list_card[card="customers_list"]').append(construct_customers);
I'm impressed

$.post call from a loop

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

ajax calls from php page - checking for an empty array as result

I have a php page which includes the following javascript:
<script>
$(document).ready(function(){
$('#search').hide();
});
$('#L1Locations').live('change',function(){
var htmlstring;
$selectedvalue = $('#L1Locations').val();
$.ajax({
url:"<?php echo site_url('switches/getbuildings/');?>" + "/" + $selectedvalue,
type:'GET',
dataType:'json',
success: function(returnDataFromController) {
alert('success');
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
console.log(returnDataFromController);
var JSONdata=[returnDataFromController];
alert('string length is' + JSONdata.length);
if(JSONdata.length > 0)
{
for(var i=0;i<JSONdata.length;i++){
var obj = JSONdata[i];
for(var key in obj){
var locationkey = key;
var locationname = obj[key];
htmlstring = htmlstring + "<option value='" + locationkey + "'>" + locationname + "</option>";
}
}
$('#l2locations').html(htmlstring);
}
else
{
alert('i think undefined');
$('#l2locations').html('');
}
}
});
$('#search').show();
});
</script>
what i'm trying to accomplish is dynamically show a combo box if the variable "returnDataFromController" has any items.
But I think I have a bug with the line that checks JSONdata.length.
Regardless of whether or not the ajax call returns a populated array or an empty one, the length always shows a being 1. I think I'm confused as to what is counted when you ask for the length. Or maybe my dataType property is incorrect? I'm not sure.
In case it helps you, the "console.log(returnDataFromController)" line gives the following results when i do get data back from the ajax call (and hence when the combo should be created)
[16:28:09.904] ({'2.5':"Admin1", '2.10':"Admin2"}) # http://myserver/myapp/index.php/mycontroller/getbranches:98
In this scenario the combo box is displayed with the correct contents.
But in scenario where I'm returning an empty array, the combo box is also created. Here's what the console.log call dumps out:
[16:26:23.422] [] # http://myserver/myapp/index.php/mycontroller/getbranches:98
Can you tell me where I'm going wrong?
EDIT:
I realize that I'm treating my return data as an object - I think that's what I want because i'm getting back an array.
I guess I need to know how to properly check the length of an array in javascript. I thought it was just .length.
Thanks.
EDIT 2 :
Maybe I should just chagne the results my controller sends? Instead of returning an empty array, should I return false or NULL?
if (isset($buildingforbranch))
{
echo json_encode($buildingforbranch);
}
else
{
echo json_encode(false);
}
EDIT 3:
Based on the post found at Parse JSON in JavaScript?, I've changed the code in the "success" section of the ajax call to look like:
success: function(returnDataFromController) {
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
console.log(returnDataFromController);
var JSONdata=returnDataFromController,
obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
alert(obj);
}
But i'm getting an error message on
[18:34:52.826] SyntaxError: JSON.parse: unexpected character # http://myserver/myapp/index.php/controller/getbranches:102
Line 102 is:
obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
The problem was that the data from the controller is malformed JSON.
Note the part of my post where I show the return data:
({'2.5':"Admin1", '2.10':"Admin2"})
The 2.5 should be in double quotes not single quotes.
I don't understand how / why this is happening but I will create another post to deal with that question. Thanks everyone.

jQuery posts error text when posting with ajax

When I'm posting via ajax I'm sometimes getting extra characters posted for example. If the text passed though ajax yo a php $_POST I end up getting:
This is my messagejQuery127638276487364873268_374632874687326487
99% of the time posts pass though fine... I'm unsure how to capture and remove this error as it only happens some of the time.
// this is the ajax that we need to post the footprint to the wall.
$('#submitbutton').click(function () {
var footPrint = $('#footPrint').val();
var goUserId = '1';
$.ajax({
type: 'POST',
url: '/scripts/ajax-ProfileObjects.php',
data: 'do=leave_footprint&footPrint=' + footPrint + '&ref=' + goUserId + '&json=1',
dataType: 'json',
success: function(data){
var textError = data.error;
var textAction = data.action;
var textList = data.list;
if (textError == 'post_twice' || textError =='footprint_empty' || textError == 'login_req') {
// display the error.
} else {
// lets fade out the item and update the page.
}
});
return false; });
Try set cache to false. From http://api.jquery.com/jQuery.ajax/
cache Boolean
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the browser. Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL.
I found out through a process of elimination that the error was being caused by invalid data being passed to the query string.
The line:
data: 'do=leave_footprint&footPrint=' + footPrint + '&ref=' + goUserId + '&json=1',
I noticed that the footPrint variable would always break the script if '??' was passed. A number of members when asking a question would use a '??' when and not a single '?'
By wrapping the footPrint var in encodeURIComponent() I can send all the text though to the PHP script without breaking the URL string.
New Line:
data: 'do=leave_footprint&footPrint=' + encodeURIComponent(footPrint) + '&ref=' + goUserId + '&json=1',
This solution has worked for me... questions comments and suggestions still welcome.

jQuery AJAX POST to mysql table for dynamic table data- Am I doing this in anything like the right way?

I have a table which I can dynamically add and delete any number of rows to. Once the data is all entered by the user I am using the jQuery AJAX functionality to POST it to a mysql database so there is no page redirect or refresh.
The only way I could think of getting it to work was using this for loop in my jQuery, effectively posting each row to the database separately. How dumb is this? Should I be getting all the table data and posting it once? There could be any number of rows varying on user and the user could add and delete rows as much as he wants before submitting.
The strange i variable counting is due to there being two th rows at the top of the table. I couldn't work out a smart way of doing this.
I was a bit paranoid about the data always being associated with the correct row.
Thankyou for your time.
jQuery(function() {
jQuery(".button1").click(function() {
// process form here
var rowCount = jQuery('#dataTable tr').length;
for (var i = 2; i < rowCount; i++){
// the four elements of each row I am storing to the mysql
var txtRow1 = jQuery('#txtRow' + (i-1)).val();
var tickerRow1 = jQuery('#tickerRow' + (i-1)).val();
var quantRow1 = jQuery('#quantRow' + (i-1)).val();
var valueRow1 = jQuery('#valueRow' + (i-1)).val();
var dataString = 'txtRow1='+ txtRow1 + '&tickerRow1=' + tickerRow1 + '&quantRow1=' + quantRow1 + '&valueRow1=' + valueRow1;
//alert (dataString);return false;
jQuery.ajax({
type: "POST",
url: "http://rccl.co.uk/form_action1.php",
data: dataString
});
};
return false;
});
});
It looks very clearly to me as if you have a well-established index of the row in question, using your variable i. Most form handlers server-side will unpack repeated keys of the form into a list, for stuff like many checkboxes with the same name. You could exploit that here.
datastring = '';
for(var i=2; i<rowCount; i++) {
var txtRow1 = jQuery('#txtRow' + (i-1)).val();
var tickerRow1 = jQuery('#tickerRow' + (i-1)).val();
var quantRow1 = jQuery('#quantRow' + (i-1)).val();
var valueRow1 = jQuery('#valueRow' + (i-1)).val();
dataString = datastring + 'index[]=' + (i-1) + 'txtRow1[]='+ txtRow1 + '&tickerRow1[]=' + tickerRow1 + '&quantRow1[]=' + quantRow1 + '&valueRow1[]=' + valueRow1;
}
Then make the ajax call with the whole string.
On the server-side, you should get arrays for each of these, the first of each of which corresponds to the first row, the second of each of which corresponds to the second row, and so on.
It's been a long time since I used PHP, but I believe the [] symbols for each key item are necessary to clue PHP's $_POST that it should convert the various keys' contents into arrays.
I would try posting it all at once.
Reasons
fewer calls, less chance of your message getting lost in transit (your server rejecting requests because of flood)
you don't have to worry about requests responding out of order (maybe not an issue, but having an ass load of jumbled responses could potentially be an issue)
it will be faster for large numbers of rows getting saved at once

Categories