So I'm sending a string parameter to javascript function, and the problem is space characters and/or quotes. I can have either one working, but can't figure out how to get both ways to work at the same time.
I left encodeURIComponent and decodeURIComponent to my example as I currently use them to deal with spaces.
Javascript:
function alertTitle(title){
alert(decodeURIComponent(title));
}
PHP:
//...fetching from MySQL
$title = $row['title'];
//If $title content is wrapped in single or double quotes, this will do:
$title = str_replace("\"",""",$row['title']);
//But if it's not, and has spaces, I have to wrap it in quotes for encodeURIComponent:
$title = '\''.$row['title'].'\'';
//And that obviously gives error in encodeURIComponent if $title happens already to have
// single quotes
//..And sending $title to javascript:
echo '<a onclick="alertTitle(encodeURIComponent('.$title.'));" href="#">Alert</a>';
So somehow I need to escape single quotes also, or then come up with some very different approach.
But this is already so close, so I wish I have just missed something simple.
$title might be anykind of the following examples:
"Title"
"Title with spaces"
'Title'
'Title' with "all combined"
Title "Blaablaa" here
And so on.
All hints are more than welcome. Thanks!
Just add a pre-replace using single quotes :)
//...fetching from MySQL
$title = $row['title'];
//If $title content is wrapped in single or double quotes, this will do:
$title = str_replace("\"",""",$row['title']);
$title = str_replace("\'","'",$row['title']);
//But if it's not, and has spaces, I have to wrap it in quotes for encodeURIComponent:
$title = '\''.$row['title'].'\'';
//And that obviously gives error in encodeURIComponent if $title happens already to have
// single quotes
//..And sending $title to javascript:
echo '<a onclick="alertTitle(encodeURIComponent('.$title.'));" href="#">Alert</a>';
Related
Using ajax I post data to php file where I have loop with code below.
Part of my code where I can't properly format onclick event:
$result .= '<a href="#" onclick="$("#element").dialog("open");" ></a>';
I tried to escape double quotes with backslash, but no luck. Using backslashes, in console I see: Somehow from nowhere "=" appears, also all backslashes are printed. Code doesn't work.
Could someone help to figure out where I made a mistake in syntax? Thank you.
In your string there are double quotes, followed by content wrapped again in double quotes. The second quotes should be single quotes, but that would terminate the string. So you will have to escape them.
The desired html code should look like this:
to achieve this, you will have to change your PHP code to the e.g. the following:
$result .= '';
When parsing the HTML, the browser will read the onclick="$("#element" part, and infer that attribute onclick equals "$(", because it thought it found the closing double quotes. So, you'll need to escape the double quote character after the $(. Since you're using $result .= 'some_string' (I want to empasize on the single quote being used here), you are unable to escape the double quote character within the single quoted string. Thus, you'll need something like this:
$result .= '<a href="#" onclick="$(\'#element\').dialog(\'open\');" ></a>';
Now, php will translate \' to just ' while rendering, so the final output of the string will be
<a href="#" onclick="$('#element').dialog('open');" ></a>
I hope this helps.
Double quotes should be escaped
$result .= '<a href="#" onclick="$(\"#element\").dialog(\"open\");" ></a>';
Another way is
$result .= `<a href="#" onclick="$('#element').dialog('open');" ></a>`;
There are a few questions on here on quotes within quotes within quotes, but none have the solution for me.
(I think) I need 'real' quotes within quotes within quotes
My scenario is thus:
<?php echo "<script>text=/"<a onclick=\'myFunction('php-variable')\'>click me</a>/"</script>" ?>
The browser output would be:
<script>text="<a onclick='myFunction('argument')'>click me</a>"</script>
Thanks to a commenter (who didn't post an answer) I have taken the script code out of the <?php ?> and only used it where necessary.
<script>text="<a onclick=\'myFunction('<?php echo $PHP_variable ?>')\'>click me</a>"</script>
The quotes nest as thus
" , /" , '
(Whereas before I was nesting quotes 4 times)
<?php
echo "<script>text=\"<a onclick='myFunction(\\\"argument\\\")'>click me</a>\";document.write(text);</script>";
I've tested it.
I encoded an array using json_encode() function and it gave me a string like this..
"[{"details":"power - 2000w \nac-220-240v \/ 50-60hz\n369 degree cordless base\n","model_id":"MC-EK3428 \/ MC-EK3328"}]"
as you can see it contains special characters like "\n"..I want these special characters to be replaced with "" because in javascript I am using the JSON.parse(); function to convert this string to an object..
but it gives me an error
syntaxerror : missing ) after argument list
I think this is because of the special characters in the string..how can I escape these?
Edit
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = JSON.parse('<?php echo $jsonencoded_array; ?>');//this line gives me the error
update :
found out that the error is given in this :
'<?php echo $jsonencoded_array; ?>'
The problem here is that \n (and various other combinations) have special meaning inside a JavaScript string, and you are dumping your JSON into a JavaScript string without doing any conversion of those characters.
Since JSON is heavily inspired by JavaScript literal syntax, you can use json_encode to convert a PHP string into a JavaScript string.
There are some gotchas, the main one being that </script> can appear in a JSON text without causing any problems, but having that in the middle of your JavaScript <script> element is going to cause the HTML parser to cut off your JavaScript in the middle of the string … but PHP's default encoding rules will generate <\/script> which solves that problem.
So:
<?php
$json_array = json_encode($array);
$javascript_string = $json_encode($json_array);
?>
var products = JSON.parse(<?php echo $javascript_string; ?>);
That said. A JSON array is also a JavaScript array, so you can skip that step entirely.
<?php
$json_array = json_encode($array);
?>
var products = <?php echo $json_array; ?>;
There must something that you are missing or there is some other reason for your issue while parsing in JavaScript; because json_encode handles \n and other special characters such " \ etc. very well and escape them properly without any explicit work.
I would suggest you to check the JSON produced and you are supplying to JavaScript and see if there is something missing in between.
Note: You can do a str_replace but it is not advised. Better stick to json_encodesince its s standard function and it works well.
Edit:
You should be echoing $view->jsonencoded_array not just $jsonencoded_array, no need to parse already JSON object.
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = <?php echo $view->jsonencoded_array; ?>;
json_encode() twice helped me to solve this issue..
$view->jsonencoded = json_encode(json_encode($array));
$str is loading dynamic content from admin panel (tinymce) in following format
$str = 'First Line
Second Line
Third Line';
Now when i try to access this variable then it gives me unterminated string literal
<script type="text/javascript">
$(document).ready(function() {
var a = '<?php echo $str;?>';
$('#abc').html(a);
});
</script>
<div id="abc"></div>
when i convert string to $str = 'First line Second line Third line'; then it does not give error but my string is in above way.
When dumping a PHP variable into JavaScript, ALWAYS use json_encode. Like this:
var a = <?php echo json_encode($str); ?>;
Note no quotes around the PHP code, this is important! PHP will add the quotes for you and escape everything correctly.
It's the line breaks, they're not valid inside a JavaScript string literal. If you want multiple lines in a JavaScript string, use a backslash (\):
var testString = 'This is \
a test';
Even then, multiple whitespace (including linebreaks) will be removed when it's set as the content of an HTML element.
That said, I don't see why you're using the JavaScript to do this at all, you could simply do:
<div id="jaspreet"><?php echo $str;?></div>
I have a php page which is called via AJAX. and basically it fetches some value from my database and echos back at table with inputs etc. The problem is when the string it fetches contains quotation marks(actually only single quotes seem to be effected). So on the php page there's something like this:
$value = htmlentities($DB_result->cloumn);
echo'<input type = "button" onClick = "$(\'#something\').val(\''.$value.'\');" />'
so if $value = "hello", no problems but if: $value = 'hello', the page which I'm making the AJAX call from throws up some such error: Syntax Error: unexpected identifier.
so I guess the quotations in $value have not been escaped, which I thought it would with the htmlentities. any Ideas how to solve this much appreciated. Thank you.
The problem is that $value contains single quotes, which interfere with the correct parsing of javascript. from the manual entry for html entities:
all characters which have HTML character entity equivalents are translated into these entities.
this means that your single quotes are not escaped, they are only translated in a way browsers will better understand. You need to use addslashes():
$value = htmlentities(addslashes($DB_result->cloumn));
"'hello'" will become "\'hello\'" which in the browser will look like:
<input type = "button" onClick = "$('#something').val('\'hello\'');" />
which will attribute the string 'hello' (with the single quotes) to the value attribute of $('#something')
Try:
$value = htmlentities($DB_result->cloumn, ENT_QUOTES, "utf-8");
Passing ENT_QUOTES through as a flag will convert both double and single quotes.