javascriptphpajaxoutput-buffering

Why am I getting a file 2 times when fetching a php via ajax?


It's quite curious to me. I've got a php test file like this:

<div class="live-ajax-messages">message from deep ajax</div>

I'll get it using this function:

public function get_ajax_messages_template() {
    ob_start();
    include(__DIR__. '/../templates/search-results-messages.php');
    $content = ob_get_contents();
    exit($content);
}

I'll get that function output like this:

    load_ajax_messages_template: function(){
        jQuery.ajax({
            url: ajax_url,
            data: 'action=my_action', // executes get_ajax_messages_template
            dataType: 'html',
            type: "GET",
            success: function(response){
                console.log(response); // getting 2 times <div class="live-ajax-messages">message from deep ajax</div>
                //this.results_el.find('.ajax-results').html(response);
            }.bind(this),
        })
    },

Basically, I'll get

<div class="live-ajax-messages">message from deep ajax</div>
<div class="live-ajax-messages">message from deep ajax</div>

Why?


Solution

  • Output buffering (the ob_* functions) temporarily buffer output. If the script exits while there is still buffered output, it will be written to the response.

    So, here you are buffering the output of search-results-messages.php. The call to ob_get_contents returns the current buffer, but does not clear it.

    Then, when you call exit($contents) it is writing the contents to the response, then flushing the output buffer which also contains the contents.

    There are two possible solutions here. (1) is to replace ob_get_contents with ob_get_clean which does the same thing, but clears the buffer.

    The other (simpler) solution is to just include the file without output buffering, since you want to write its contents out anyway, then just call exit(); with no parameters.