qqmisko
qqmisko

Reputation: 143

ajax json response containing html

Do I need to json_encode ajax response data before sending?

$html1 = '<span>some html</span>';
$html2 = '<span>some html</span>';
$res = array('html1'=>$html1, 'html2'=>$html2);
echo json_encode($res);

or

echo $res;

Upvotes: 0

Views: 90

Answers (1)

mplungjan
mplungjan

Reputation: 178413

The X in AJAX stands for XML

If you return XHTML, you do not need to json_encode it

echo '<div>'.$html1.$html2.'</div>';

You can

  1. dump it onto the page someElement.innerHTML = returnValue; or document.body.insertAdjacentHTML('afterend',returnValue);

  2. Extract from a DOMFragment:


const domFragMent = document.createElement("div")
domFragment.innerHTML = returnValue;
const spans = domFragment.querySelectorAll("span");
  1. use a domParser

  2. Send a json_encoded array of values and parse them on the client into spans

Upvotes: 3

Related Questions