0

What is the reason why you need to use die(); to end ajax requests? I read that it's recommended to use die() or exit() to terminate the script when its sole purpose is meant for AJAX call?

Is this recommended for my script when the output is the very last thing in the script? Because my index.php file loads the environment, gets the content from controller then the very last thing is using echo to output the data. It's either JSON encoded data for ajax, or HTML content for non ajax. I could add the die at the end by checking if it's an ajax call, but I don't understand why I would need it here.

// index.php

// Load environment
require '../load.php';

// Handle request
$controller = new App\Controllers\Controller();
$content = $controller->doRequest();

// Output the content
echo $content;

// Terminate script with die() for AJAX requests (is this needed?)
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    die();
}

1 Answers1

0

If you use one of those php-frameworks which can output additional data by themselves -- then you need to use exit

Also do not forget to DO NOT use ?> at the end of your script. You may leave empty line after php closing tag so your web-server will add this empty line to answer if you do not use exit

Also, do not forget about register_shutdown_function -- it will run immediatly after exit, so exit is the good way to prevent adding any other shutdown functions after echo $content;

You may not use exit in this concrete script, but also don't forget to remove ?> too

mochalygin
  • 739
  • 6
  • 14