Jens Törnell
Jens Törnell

Reputation: 24768

Ajax / jQuery to PHP and back again?

I have an ajax call made with jQuery, something like this:

$.ajax({
    type: "POST",
    url: ajaxurl,
    data: data,
    success: function(response){
        alert(response);
    }
});

I get data from PHP like this:

$data_array = get_data();
foreach($data_array as $data)
{
    echo $data;
}

PHP to slow

The PHP data function call is slow because it gets very much data from the database, might fetch images, make some json calls and other slow things.

One loop round at the time

Therefor I need to get the PHP code just do one round, then Javascript and then do the next round in the loop.

More than one way to solve it?

There might be more than one way to do it. Which one is prefered? Javascript foreach-loop, JSON and global Javascript variables comes to mind.

Upvotes: 1

Views: 181

Answers (3)

afuzzyllama
afuzzyllama

Reputation: 6548

You could manipulate your query to do a limit. So something like:

 var total_count = ajax_get_sql('select statement with count');
 var curr_count = 0;
 var set_number = 10; 
 var select_statement_without_limit = 'statement';  

 setTimeout('fetch_data()',0);

 ...

 function fetch_data()
 {
      if(curr_count < total_count)
      {
           ajax_get_sql(select_statement_without_limit with limit appended);
           curr_count = curr_count + set_number;
           setTimeout('fetch_data()',0);
      }
 }

With all your ajax calls set to wait for a response instead of continuing. I would keep the sql logic in PHP, but use javascript to query the server many times. This will prevent your JS script from giving long execution errors. I haven't really taken into account data manipulation, but you can probably figure it out!

Upvotes: 0

judda
judda

Reputation: 3972

I'm slightly against storing actual images in the database. I prefer to only keep a unique link for them and then return that instead of the actual image. This would speed the query up a fair bit. I agree with mad_programmer that the JSON js would be preferred for your situation.

Upvotes: 1

Maverick
Maverick

Reputation: 2760

You can set the return type in your ajax function as xml or json, and then return you array in either of these types. I feel that JSON js the preferred one for your solution.

Upvotes: 2

Related Questions