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?

+3


source to share


2 answers


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.

+3


source


Try it,



if(count($result)>0) {
    $status = 0;
} else {
    $status = 1;
}   

$json['status'] = $status;
$json['result'] = $output;
print(json_encode($json));

      

0


source







All Articles