1

There is a question bothering me, pls help! I use jquery's ajax to call a php api.

$.ajax({
            type:"POST",
            dataType:"json",
            data:{type:type,fid:fid,model:'star'},
            url:'Recommend/Star/mark',
            success:function (data) {
                //do something
            },
        ...
      });

php code in Recommend/Star/mark method:

    error_reporting(0);
    set_time_limit(0);
    ob_implicit_flush(true);
    ob_end_clean();

    ob_start ();
    echo json_encode($boolMark);
    ob_flush();
    flush();

    sleep(3);
    $this->afterMark($uid, $fid);

I want php echo result to ajax immediately, but my codes do not work.

How to make php send result to ajax immediately, and continue to execute remaining code?

grey256
  • 13
  • 4

2 Answers2

2
 ....
 echo json_encode($boolMark . "<br>\n");
 // get the size of the output
 $size = ob_get_length();
 // send headers to tell the browser to close the connection
 header("Content-Length: $size");
 header('Connection: close');
 ob_end_flush();
 ob_flush();
 flush();
 /******** background process starts here ********/

 ignore_user_abort(true);

 /******** background process ********/
 set_time_limit(0); //no time limit

 /******** Rest of your code starts here ********/
Hamboy75
  • 938
  • 1
  • 11
  • 22
0

You also need to call these two functions after flush():

session_write_close(); 
fastcgi_finish_request();
mayersdesign
  • 5,062
  • 4
  • 35
  • 47
Guillermo
  • 1
  • 1