views:

563

answers:

3

When I perform an asynchronous request with jQuery Ajax, sometimes the response is returned quickly in 800 ms, somtimes it's slow and the response is returned in 2.50s (avg), and sometimes it hangs, and just shows the loading images. I'm not sure if it's because of my PHP code or jQuery Ajax code. I send some values using jQuery Ajax:

function get_detail_product(obj)
{    
    var id = obj.id ; 
    var $this = jQuery('#'+id); 
    var Thumb = jQuery('#Scroller div.Container') ;
    jQuery.each(Thumb , function(){
        jQuery(this).css('border' , '#ccc 2px solid');
    });
    $this.parent().css('border' , '#ff8500 2px solid') ;
    var load_area = jQuery('.detail') ;
    //ajax request 
    load_area.html("");
    load_area.html('<div id="loading" style="margin-top:60px;margin-left:350px;"><img src="../images/loading.gif"><br>Loding ... </div>');
    jQuery.ajax({
        url: 'index.php?module=product&popup=on ',
        type: 'POST',
        data: 'pid=' + id ,   
        success: function(result) {
            jQuery('#response').remove();
            load_area.html(result);
            jQuery('#loading').fadeOut(500, function() {
                jQuery(this).remove();
            });
        }
    });
}

and in the PHP file I have the following code to retrieve the requested data:

//ajax requests 
if(isset($_POST['subcatid']) && is_numeric($_POST['subcatid']))
{
    $subcatid = $_POST['subcatid'] ;
    $products = $dbc->getAll("select * from xxproduct where xsubcatid='$subcatid'") ;
    //send result 
    echo '<table cellpadding="0" cellspacing="0" border="0" id="ScrollerTable"><tr>'; 
    foreach ($products as $p) : echo '<td><div style="border:#ccc 2px solid ; padding:0px;margin-top:20px ; margin-bottom:20px ; margin-left:8px ; margin-right:8px;" class="Container"><a href="javascript:void(0)" id="'.$p['xproductid'].'" onclick="get_detail_product(this)" ><img src="imgsize.phpw=100&h=100&img=../uploads/product/'.$p['xproductid'].'/'.$p['xproductid'].'__1.jpg" border="0"/></a><div style="background-color:#ccc ;text-align:center ; padding:5px; ">'.$p['xproductname'].'</div></div></td>';
    endforeach ;
    echo ' </tr></table>'; 
}

I wonder if you can find any mistakes in my code that cause the delay; additionally I'm using a PEAR DB object to interact with the database.

When i type the title of my question in this page, suggestions are returned in about 500 ms. Why is this ajax interaction so fast but mine is not?

A: 

I'm assuming you're getting the response times (the 800ms - 2.5s you mentioned) via FireBug? If that's the case, then that's the time of the request itself. At that point, all of your developer-land JS has already executed and the only JS that's running is the jQuery code in the ajax() function.

So I think you can be reasonably sure that it's your PHP code.

What I would do is use some php microtime() calls and hit that script directly (from a browser or commandline, not via an ajax call) and print out the microtime result.

Specifically, you'd add this at the top of your script:

$start = microtime(true);

And this at the end:

echo "Time: " . (microtime(true) - $start);

Then, try to isolate what params/etc are used during any consistently slow queries. As in most cases with CRUD apps, the DB is most often the culprit.

Edit:

After looking more closely at your code, there's nothing obviously wrong. What I wonder is if this is the only request that has such crazy response times. If it is, that suggests that the connection between your client and server is not the issue. That it's specifically this script.

And by doing what I mentioned above--hitting the script directly via your browser rather than an ajax call--you can isolate the PHP code and then, by moving the placement of those microtime statements, isolate the specific lines of code.

But if it were me, I'd focus first on that SQL Query. Most like you're not using any bytecode caching like APC. It's a great tool it's just not in such widespread use right now.

So the only caching mechanism that code is using is probably the MySQL Query Cache. If there's no index on the subcatid field, it could be that MySQL is doing a table scan. But the next time you request that same query (with that same subcatid value), the results will be in the query cache and MySQL will return them instantly.

You could test this out by isolation even further: Forget the AJAX call and the PHP code, just copy and paste that query, plug in some valid subcatid values, and run it directly into phpMyAdmin or the MySQL CLI or your favorite MySQL tool. If you're seeing intermittent performance as you plug-in new and different subcatid values, then you know where your problem lies.

Encoderer
yes , thanks I'll working on your solution . great recommendation ;) i seprate ajax calls php files and now i getting better results .
mehdi
A: 

Possibly caching both in the browser and any php mem-caching going on.

Unkwntech
A: 

Network latency can have a huge impact on your ajax calls, particularly if one side or the other doesn't have a consistent internet connection. Since the problem seems to be intermittent I'd suggest looking at network or cacheing as the likely source.

acrosman
Nah, you just missed the if() statement at the top of that PHP Snippet. There's no injection vector there.
Encoderer
True, my bad. I'll take that out.
acrosman