简体   繁体   中英

Abort cURL in a ajax request

I'm sending an Ajax request to ajax.php file that downloads an XML using cURL.

//ajax.php

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD,       USERNAME.':'.PASSWORD);
curl_setopt($ch, CURLOPT_POSTFIELDS,    getData());
curl_setopt($ch, CURLOPT_URL,       $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,    1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,    5);
curl_setopt($ch, CURLOPT_FRESH_CONNECT,     true);
$data = curl_exec($ch);

echo $data;

User is not confirmed about this process and may refresh the webpage.

Sometimes curl_exec($ch) takes a long time and i get a timeout error. this error prevent script to continue. I searched and found no exact solution to solve this problem.

Now the the bigger problem is that in this case while ajax request is processing in background and user refresh the page, it wont refresh until ajax request timeout or ended.

I thought aborting that cURL request when page refreshed is a good temporarily solution but don't know how to do that.

Note: Ajax request has been setup using jQuery and aborting it ajax.abort() did not solved the problem.

You should change the way how your application is handling this functionality. I would try to put another abstraction layer between ajax call and actual calculation process.

For example, ajax call could initialize php background process or even better middleware message queue with workers. In response you give to customer job id (or store it in db linked together with user id). Then onTimeout() is executing ajax requests to get status of job. In the mean time background process or middleware worker is processing the task and saves response into db with the same job id.

So in the end customer initializes job and after that just checks status of that job. When job is finished, you know it on server side. So on next ajax request you respond with actual job result. Javascript is receiving response with result and is executing callback function that is continuing work on client side.

您可以尝试使用try / catch块返回在发生此(或其他)错误时可以处理的内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM