Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda