What I want to do is get a JSON object and an HTML view from a single AJAX call.
My current implementation is the JSON object is hidden in some part of the html and just parsed client side.
Is this good practice? Is there a better way of doing this?
Return a JSON object with the HTML inside:
{ "a": "data", "b" : "data", "view" : "<html>...</html>" }
Another option (as the option to alter the content type of the original request seems obvious to everyone here) would be to send a custom JSON header.
XXX-JSON-Payload: {a:1, b:2}
And read that header from JS (see getResponseHeader is not a function for a jQuery method of doing that).
I would return JSON from the AJAX call, and in one of the JSON attributes, store the encoded HTML. Seems quite a bit simpler and stable than trying to parse JSON back out of an HTML response.
You can do it by embedding your JSON into an HTML elements data attribute:
Assuming your ajax call returns this:
<json data-obj='{"my":"json","data":7}'/>
<div>My View</div>
Then the following will load the view, and extract the data from the attribute
<div id="content"></div>
<script>
$('#content').load('ajax.php', function(data) {
$(data).siblings('json').remove().data('obj');
});
</script>
(tested with jQuery v1.7.1)