user656925
user656925

Reputation:

Sending json string along with html data in ajax response text - How to?

For small amounts of textual info ( Control Messages ) I send what I call bullets (Same syntax as HTML comments ) along with my page during ajax calls. For example

<!--Control Message--><html> all my page here</html>

I then parse the "Bullet" out before rendering the page...even though I don't really have to.

For more data, say 5 variables, I plan on json_encoding it...and sending it with the page as well.

How are others demarcating and extracting the structured data / json strings from html. I could just put it in a "bullet" like below and extract it out...but my guess is there is a more "proper" way to do this.

<!--json string here--><html> all my page here</html>

Upvotes: 0

Views: 1433

Answers (2)

Nirmal Patel
Nirmal Patel

Reputation: 5168

If the data is contextual with the HTML, it would be good to send them as data tags within the HTML?

<html data-value="{name:value}">
    <body>
        <div data-div="{name:value}">
    </body>
</html>

Upvotes: 1

Joseph
Joseph

Reputation: 119847

If you are passing this via AJAX, just embed the HTML in the JSON and parse that JSON as a whole:

{
    "html":"<html>...</html>",
    "other_data":...,
    "some_more_data":...
}

//access it later:
data.html
data.other_data
data.some_more_data

If this data loaded with the page, store the data in a variable instead:

<html>
    <head>
        <script>
            var data = <?= json_encode($data) ?>;

Upvotes: 5

Related Questions