I have a variable in my MySQL database. I want this variable to handle both simple and double quotes.
For example:
$variable = "I'm happy" or $variable = I'm happy or $variable = "I am happy"
In my DB, the first example is this: "i'm happy" and that works for me. The problem is now on my JS function because I want to call my data:
nameFolder = "<?php echo $variable ; ?>"
But, if $variable = "I'm happy", I've got double "" so I get a JS error. And if I put single quote, the problem is the same with another case.
Any ideas?
The best way to echo data to JavaScript is to use json_encode:
var nameFolder = <?php echo json_encode($variable); ?>;
N.B.: There shouldn't be any surrounding quotes, function will handle that for you.
Use
nameFolder = "<?php echo str_replace('"', '\"', $variable); ?>"
Related
i need qoutes to echo with the variables below, how do i accomplish that? ive tried escaping with \, but its not working
var name = "<?php echo "$_SESSION['name']"; ?>"
var p_name = "<?php echo "$_SESSION['p_name']"; ?>"
Apparently declaring a js variable requires quotes ?
You can also use json_encode
var name = <?php echo json_encode ($_SESSION['name']); ?>;
var p_name = <?php echo json_encode($_SESSION['p_name']); ?>;
That will add the quotes for you and has the benefit of also:
turning php arrays into js arrays
escaping any ' or " in the variables you are trying to echo for you
Yes, declaring a string in javascript requires quotes. Like most (if not all) other programming languages.
You can't just chuck a quotation mark in the middle of your echo statement and expect it to work. Why are you double quoting? Just put the quotes outside the php block.
var name = "<?php echo $_SESSION['name']; ?>";
var p_name = "<?php echo $_SESSION['p_name']; ?>";
I'm trying to make a dynamic webpage. I have the title for each page in its own file and I was trying to use file_get_contents() to get the title, but I'm not sure how to use a variable in the path. This is what I've tried.
<?php
$movie= $_GET["film"];
$title= file_get_contents('/movies/moviefiles/.$movie./info.txt');
?>
<h1><?= ($title) ?> </h1>
You aren't concatenating the strings properly.
Try:
$title= file_get_contents('/movies/moviefiles/'.$movie.'/info.txt');
The same can be done with double-quotes, too:
$title= file_get_contents("/movies/moviefiles/$movie/info.txt");
The difference is that variables aren't interpolated within single quotes. If they're in double-quotes, the actual value of the variable will be used.
And read more about string concatenation here: http://php.net/manual/en/language.operators.string.php
You need to use double quotes " when you want to use variables inside a string or concatenate using the ..
$foo = "world";
print "hello $foo";
print 'hello '.$foo;
Your code should be like this:
<?php
$movie= $_GET["film"];
$title= file_get_contents('/movies/moviefiles/'.$movie.'/info.txt');
?>
<h1><? echo $title; ?> </h1>
You can't work with variable with simple quote.
if you want to use variable, use double quote
$title= file_get_contents("/movies/moviefiles/$movie/info.txt");
More information on these quotes : http://www.php.net/manual/fr/language.types.string.php
$title= file_get_contents("/movies/moviefiles/$movie/info.txt");
I currently have a webpage that need to use javascript to parse variables from php.
I do things like this:
data.notices = JSON.parse('<?php echo json_encode($notices) ?>');
However, when there is single or double quotes in the $notices variable, javascript console return errors.
How can I get the variables correctly?
This code doesn`t return error
<?
$notices = array('sad'=>'asd as" asd', 'asd"sdf '=>'asdasd" \' asd ads');
?>
<script>
data = new Object();
data.notices = JSON.parse('<?php echo addslashes(json_encode($notices)) ?>');
</script>
$a='b' will be converted to "b"(note the quotation mark) by json_encode
just write JSON.parse(<?php echo json_encode($notices) ?>);(remove ') will be ok.
I found that it is the problem caused by the fact that I did not escape the characters before inserting to database.
You are one extra operation. If you want message as javascript variable you can directly get like
data.notices = <?php echo json_encode($notices) ?>;
// and access like this
// data.notices[0] or data.notices['alert']
I have one page iframed inside of another. The child page communicates with the parent page by using the sendMessage() function. The parent page runs eval() on the message that is received from the child page.
This is the code that constructs the message:
var msg_string = '$("body").append("<?php echo $content; ?>")';
var send_string = "sendMessage(\'" + msg_string + "\', '<?php echo $receiver_domain; ?>')";
setTimeout(send_string, <?php echo $delay; ?>);
The problem among other things is that the $content variable contains HTML and the double quotes in things like id="test" do not play well with all of this concatenation. I am at a loss trying to figure this out.
I have already attempted to escape the quotes in $content by converting them to " but that resulted in the browser placing div ids in double double quotes (""test"").
** Update **
Using the json_encode method does work for getting the data to the parent page. It's a much easier solution than what I had been doing (I had already accomplished this much but figured something was amiss). That said, the eval of the data still fails if there are double quotes in a div id="test". A string of just "test" works, but it actually puts "test" verbatim. This is the javascript source in the html after using the json method:
var msg_string = '$("body").append("<div class=\\\"test\\\">HEY WHATS UP<\/div>");';
var send_string = "sendMessage(\'" + msg_string + "\', 'http://domain.com')";
setTimeout(send_string,500);
This fails at the eval. Putting an alert in place of the eval yields this:
$("body").append("<div class="test">HEY WHATS UP</div>");
Any ideas?
** Update 2 **
So I FINALLY figured this out. It was a combination of the three answers below. The json answer tipped me off. Basically the double quotes needed to be tripple backslashed so that by the time it go to the eval, everything would be read properly.
I ran into a few other snags, including /r/n characters in the html...which I removed with str_replace and also an apostrophe...which was in an inner html element...I replaced that with the appropriate html entity and BAM!
Here is the code:
function escapeQuotes(string){
var quotes_regex = new RegExp("\"", "g");
return string.replace(quotes_regex, "\\\"");
}
var msg_string = '$("body").append(<?php echo json_encode( str_replace("\r\n", '', $content) ); ?>);';
var send_string = "sendMessage(\'" + escapeQuotes(msg_string) + "\', '<?php echo $receiver_domain; ?>')";
setTimeout(send_string,<?php echo $delay; ?>);
I upvoted everyone's answer since I used bits of everything. Thank you so much!
JSON is your friend.
var msg_string = '$("body").append(<?php echo json_encode($content); ?>)';
If your only concern is double quotes, why not just replace them with an escaped string?
var msg_string = '$("body").append("<?php echo str_replace("\"", "\\"", $content); ?>")';
I can't exactly test, but that would seem to work to me.
You need to escape using str_replace
$search = array("'", '"');
$replace = array("\'", '\"');
var msg_string = '$("body").append("<?php echo str_replace(search, replace, $content; ?>")';
I have this code that is captured in the jquery Data object from a php page.
echo "
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
";
Problem is, the 's are not escaped. I have tried using /' to escape, but it comes up with an error. I am sure I am doing this wrong, does anyone know where to put the /' instead of '?
You could use a php nowdoc instead of quotes at all which would simplify things:
echo <<<'DOC'
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
DOC;
then use whatever you want inside (quote or dquote). This is, of course, unparsed so if $d was actually referring to a php var then you would have problems.
Your apostrophes actually look fine. But, within a double quoted string, PHP will evaluate any string beginning with a dollar sign as a variable and not produce the desired result. Try replace the jquery related instances of $ with \$. Like this:
echo "
var \$d = \$('<div/>', {
id: 'hi' + \$('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
\$('#textResp').append(\$d)
";
use json_encode function in php, it behaves like the escape_javascript function in rails.
just pass a string argument to the json_encode function, and it return the escaped string for you, see the sample code below:
<?php
$form_html = <<HTML
<form action='...' ...>
<input type='...' name='...' ...>
...
</html>
HTML;
?>
var form_html = <?php echo json_encode($form_html); ?>;
$('.remote#create_form').html(form_html).slideDown();
You will need to use \ before all 's.
However, this is puzzling, why do you feel you need escape characters? It appears you are simply echoing this output, if this is between <script /> tags, you should be fine.
PHP will attempt to expand variables, $name, that occur in strings wrapped in double quotes. Since $d looks like a variable to the PHP interpreter, it will try to replace it with the variable's value.
Assuming that you don't have $d defined anywhere, that will produce an empty space and, possibly, a notice (if you are using error level E_NOTICE).
To prevent that from happening, escape dollar signs with a backslash (replace $ with \$)
Use single quotes for your string construction. Only use double quotes when you specifically are including variables that you want evaluated. PHP is trying to evaluate all of those $ references you have in there. By using single quotes, you will avoid many escaping problems.
echo '
var $d = $("<div/>", {
id: "hi" + $("#textResp").children().length,
class: "eventdiv",
html: "hello"
}).hide().fadeIn(3000);
$("#textResp").append($d)
';