Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!