2

I know the way that I'm currently implementing ajax page loads is not the best way to do it. It goes like this:

I have a module (that I created) that has a path to send all ajax request though. based on the urls parameters, it's able to figure what actual page (node) needs to be loaded. It just returns a json_encoded string for processing (rendering is done client side).

The trouble with Drupal is that it wants to decorate EVERYTHING with all the templates. So I get json intermingled with html. I obviously don't want that. I don't want any rendering done at all in fact. So far, the only thing I've come up with on my own is to implement hook_page_alter and just unset as much data as possible until it renders with only the json. That was working for a while.

Then I added the devel_themer module (or whatever it's called). That automatically appends some javascript to the end of every response. That is breaking the json I'm sending via these ajax requests.

This has brought up the issue of my method of processing the ajax.

What is considered best practice for this type of thing? Ultimately, there may be minimal server side rendering, but I want the data to be sent in chunks that I can inject in various parts of the page. I don't want to have to put in all in one spot. To the ajax_response.title would go in the div with id="title" and the ajax_response.body would go in the div with id="body". There may be info between those two that I don't want to replace/re-render between requests.

Mostly my question is this: How can I tell drupal to send exactly the text that I want as a response instead of insisting on decorating the response with templates and allowing modules to add information?

3

Simply print your json stuff in your page callback instead of returning it, then Drupal isn't going to add anything around it. In fact, there is a helper function for that, called drupal_json_output(), see user_autocomplete() for an example of that.

That's the official way to deal with this currently, Drupal 8 will hopefully add proper handling for different types of content directly into the routing system (which will be heavily reworked and built upon Simfony2 components).

  • I'm actually very interested to see how Symfony2 is going to be incorporated. Thanks for the feedback, that was exactly what I needed. – gregghz Mar 30 '12 at 21:47
1

Use

 // do your processing
 print $json_object

This keeps all the Drupal rendering and template stuff away.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.