php - Passing string to a Javascript function does not work -
i trying pass string javascript function opens string in editable text area. if string not contain new line character, passed successfully. when there new line character fails. code in php looks like
$show_txt = sprintf("showedittextarea('%s')", $test_string); $output[] = '<a href="#" id="link-'.$data['test'].'" onclick="'.$show_txt.';return false;">'; and javascript function looks -
$output[] = '<script type="text/javascript"> var showedittextarea = function(test_string) { alert(test_string); } </script>'; the string passed "this test" , failed "this first test
this second test"
you getting error because there nothing escaping javascript variables... json_encode useful here. addslashes have used in context escape double quotes.
$show_txt = sprintf("showedittextarea(%s)", json_encode($test_string)); $output[] = '<a href="#" id="link-'.$data['test'].'" onclick="'.htmlspecialchars($show_txt).';return false;">';
Comments
Post a Comment