Best way to code javascript with php for ajax?
The following PHP function outputs JS:
function dothething( $data ){
$res = "
<div id=\"blah\">
Here some stuff, ". $data['name'] ."
</div>";
echo "$('#container').html('". $res ."');";
}
This function is called through jQuery $.ajax()
using dataType: 'script'
... so whatever is echo
ed works like a JS function. There is, of course, more, but my question has to do with encoding. Ajax error if $res
contains newlines or apostrophes. So adding this above echo
seems to work:
$res = str_replace("\n", "\\n", addslashes($res));
Is this the best way to format a PHP variable $res
to get valid javascript for ajax?
Is there anything else I should add there?
source to share
In your case, I would use json_encode()
on top of everything else:
echo "$('#container').html(" . json_encode($res) . ");";
When applied to a string value, it will automatically encapsulate it with double quotes and avoid anything inside that might otherwise cause a parsing error.
source to share