Sirac
Sirac

Reputation: 693

AJAX - Sending html-fragments ok?

I want to create a website where the user enters data in a formular and a php-script uses this data to create html-code which shall be inserted in a div-element. Using AJAX seems to be the right way to do this, but there is one thing that bothers me. in my opinion a script should always generate a whole document (doctypt-declaration, head, body etc.), but if i use AJAX i have to send only a fragment of a whole document, because i would have to write something like this:

document.getElementById("mydiv").innerHTML = ajaxObject.responseText;

So i would like my PHP-script to send a whole document, but i cannot assign a whole document to the inner html of an element. is there a way that javascript can process a whole document, and insert the documents body in a div or should i maybe use iframes instead?

Upvotes: 1

Views: 423

Answers (2)

thpl
thpl

Reputation: 5910

in my opinion a script should always generate a whole document

A big no to that! Have a look on other data formats such as json which is widely spread, or xml. Some formats do not even follow certain document structures that say: here my document starts, title belongs here, that must be like that, the other thing has to be like this and here the document ends. There's just bare data (of course under the accordance of the syntax).

The server doesn't need to return HTML at all (if you don't want it to). The opposite is the case. Provide as many output formats as you can.

Think of other client applications that would use your script, such as non-js applications or applications outside the browser that can't even handle HTML.

Would you always write a new script or change your existing whenever you need another output data format, or would you rather have a strong serverside application structure that can handle the output of several data formats?

Think of your server as an interface. It returns the data that you request. How you handle the data is absolutely up to the client (the server should not even care) in this case.

Also returning HTML chunks is absolutely okay in your case. That's what I would do here too. What I want to point out is that you absolutely don't need your script to return a whole HTML document (isn't exactely that even a big advantage that came up with AJAX?)

Upvotes: 5

ncabral
ncabral

Reputation: 2522

If you don't mind using a bit of jQuery,

$('html').html(ajaxObject.responseText);

If you just want change whatever's in the body,

$('body').html(ajaxObject.responseText);

As suggested in the comment below, it without using jQuery,

document.body.innerHTML = ajaxObject.responseText;

Upvotes: 1

Related Questions