CodeIgniter Forums
Ajax controller responding slow - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Development (https://forum.codeigniter.com/forumdisplay.php?fid=6)
+--- Forum: CodeIgniter 3.x (https://forum.codeigniter.com/forumdisplay.php?fid=17)
+--- Thread: Ajax controller responding slow (/showthread.php?tid=91246)



Ajax controller responding slow - geirarnesen - 07-08-2024

I am experiencing that controller endpoint handling Ajax requests are responding very slow...
I've though mittigated this exit() just after handling the response to the client requesting the endpoint.

Code:
$this->output
                            ->set_content_type('application/json')
                            ->set_status_header(201);
                        echo json_encode(array(
                            'status' => 1,
                            'message' => 'ok',
                            'image' => $post['id'],
                            'jury_id' => $this->jury_id,
                        ),JSON_UNESCAPED_SLASHES);
                        exit();

If I don't do the exit() in the controller function, it seems that too much is taking place in the post processing functions.
Any better way to approach this?

I am still on CI3!!

Geir


RE: Ajax controller responding slow - jonathan58 - 12-03-2024

Hi Geir,

using exit() isn't always the best practice, as it can sometimes lead to issues with things like session handling or hooks.
A cleaner approach in CI3 is to make sure that any post-processing tasks are either optimized or moved to background jobs if possible. However, if you still need to stop the script execution, consider using return instead of exit()

Here's a quick example of how you can adapt your code:
Code:
$this->output
    ->set_content_type('application/json')
    ->set_status_header(201);

echo json_encode(array(
    'status' => 1,
    'message' => 'ok',
    'image' => $post['id'],
    'jury_id' => $this->jury_id,
), JSON_UNESCAPED_SLASHES);

// Return from the function to prevent further processing
return;
This way, you maintain a bit more control over the flow of your application. Also, double-check if there are any unnecessary processes running after your response that can be deferred or optimized.