Pregunta

i have a function that return som html.

Id like this function to be used both as a template function, and with ajax.

I have learned that you should always use die(); at the end of an ajax function that returns html. This will break the script that includes the function as a template, though work fine with the ajax call, as it only loads part of the page, and everything after it is already loaded.

If i dont use die(), both works fine, but ajax will return an additional "0", to the page. Im unsure if there are other reasons why this would be the wrong approach.

So my question, what is the best way to reuse an ajax function in the template. I wanna do this so that i dont have to write the whole html output twice. Will be annoying to maintain.

Thank you :)

¿Fue útil?

Solución

first off - it's nice to see that you care about your software design and it will definetely save you some headaches. I can't exactly tell why it should be a good thing to use die() for AJAX functions, as these will suppress any further output. What you should propably be doing is a stricter separation of the presentation and your logic, but that's something you should propably research about yourself.

For you current situation (it looks as if you were building a site navigation or something like it) it would be the best for all requests to return the same thing (-> leave die() out) and you to just cut away unneeded things in JavaScript, which will allow you to build a gracefully degrading AJAX site (users without JavaScript will still be be able to use the site)

If above is not true, you might as well - for a more general solution - include something like this:

function is_xhr_request()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
    }

and a check like this:

    if(is_xhr_request()){die();}

is propably a good workaround, assuming the header is set correctly (which it should be in most of the cases).

The function is taken from the Toro Framework

Otros consejos

Soo all i had to do was write a condition check in my function :

//Detect if function was called with ajax. 
    if (strcasecmp('XMLHttpRequest', $_SERVER['HTTP_X_REQUESTED_WITH']) === 0)
    {
        //Always die when returning output with ajax. 
        die();
    }

That did it. But i think the ajax call might have to be called with jquery or some othe ajax framework in order for this to work - not sure though : )

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top