Double quotes breaking jQuery (Very simple) - php

<?
//SQL SELECT HERE
$result = mysql_query($sql);
$options = '';
while ($row = mysql_fetch_array($result)) {
$options .= '<option>Data: ' . $row['data'] .'</option>';
}
?>
$("#multiSelect").html("<?=$options?>");
The above is a PHP query inlined in a javascript function. It's goal is to populate a multiselect. The issue is that when $row['data'] contains something with double quotes jQuery doesn't like it and complains. When I remove the row containing double quotes it works fine.
How can I get around this? Is this normal behavior of jQuery.

Try to addslashes: http://php.net/manual/en/function.addslashes.php

It's because your call is being coming out as something like:
$("#multiSelect").html(""Hello"");
Most programming languages will have problems with that - they assume that the first quote you're adding ends the string you're passing in, and that the next text should be a valid piece of code.
You can get around it by escaping the quotes, removing them, or substituting them to something else:
$("#multiSelect").html("<?=addslashes($options)?>");
$("#multiSelect").html("<?=str_replace('"', '', $options)?>");
$("#multiSelect").html("<?=str_replace('"', '\'', $options)?>");
Depending on what the input text is likely to be.

WHY WHY WHY would you build the options with the code behind and than set it with jQuery? Why can't PHP just set it itself?
You need to escape the quotes with a \
"Man it is \"hot\" in here"

Related

How to prevent PHP variables and expressions from expanding in string

The following text link works fine when I place it directly in my html:
Click here to <?php echo $showOrHideText; ?> the suggested sequence of lessons.
But I want to replace it with:
<?php echo $gradeNote; ?>
Elsewhere $gradeNote is assigned a string based on the grade of the student user. My question after many hours of searching and failing is how can I pass this snippet as a literal string, without PHP attempting to parse it and giving me a junk url? What am I doing wrong here:
$gradeNote = "Click here to <?php echo $showOrHideText; ?> the suggested sequence of lessons.";
You're running <?php and ?> tags inside of a PHP variable. As you're already dealing with PHP, these are unnecessary.
Although the quotation marks "" allow you to echo out evaluated variables, because you're also running a condition in this 'string', you'll want to extrapolate that out and simply store the result as a variable. I've called mine $show.
As such, you're simply looking for:
if($slcustom29 == 0) {
$show = 1;
}
else {
$show = 0;
}
$gradeNote = "Click here to $showOrHideText the suggested sequence of lessons.";
Remember to either escape the double-quotes in the <a href="">, or swap them for single-quotes.
This can be seen working here.
Hope this helps!
Try something like this.
$s = ($slcustom29 == 0) ? 1 : 0;
$gradeNote = "Click here to {$showOrHideText} the suggested sequence of lessons.";
Any string with double quotes "" can have a variable embedded, the {} are not necessary, but i always use them for cases like this where you are trying to embed a variable with no spaces around it, "$xabc" which will return a different result "{$x}ab"
the probelm is that you are trying to put php logic into the string. Notice you have an IF command within the string literal. start with a small or empty string, and concat onto it piece by piece, as opposed to doing it in one line.
then you can echo out the single variable link

Quotas in PHP and onClick

When I try to use this:
<?php
$html = "<p id="test"><input class='is' id='live' type='checkbox' onclick='update(".htmlspecialchars($myid).");'></p>";
?>
If $myid is a number the above works fine. If it contains text like mytext_30, then onClick I get a console message that mytext_30 is not defined. How in the top syntax I can include some kind of quotas for the result to be always like this:
<input .... onclick='update("30")'/> or
<input .... onclick='update("mytext_30")'/>
?
Thank you in advance.
Quotes you are using are mislead for PHP. try this:
$html = "<p id=\"test\"><input class='is' id=\"live\" type='checkbox' onclick='update(\"".htmlspecialchars($myid)."\");'></p>";
The problem belongs to missing escaping of the quotes. Thats easy to fix.
But first, you should decide on a way you will use. Preferred way to write tags in HTML is to always use quotes ". But at least, you should not mix quotes and apostrophes. Decide for one way and use them, but not switch between them here and there.
The best way here is, to use quotes for the tags, and apostrophe for the php string. With using apostrophes for this, you have clean HTML and don't need to escape anything.
$html = '<p id="test"><input class="is" id="live" type="checkbox" onclick="update(' . htmlspecialchars($myid) . ');"></p>';

PHP - Don't use "\" in MySQL query

I wasn't exactly sure how to word this, but essentially what I need is so when I send a SELECT query in MySQL, it doesn't pay attention to the escape character ( \ ) in the search. For example, if the name I am searching for is foo'bar and I send foo\'bar to the server, is there a way to make the server find foo'bar? This is the MySQL query currently:
function escape_data($data) {
$data = mysql_escape_string (trim($data));
$data = strip_tags($data);
return $data;
}
$champ1 = escape_data($_GET['champ1']);
foreach($db->query("SELECT * FROM champs WHERE name = '$champ1'") as $row) {
$role_verify_1 = $row[$role];
}
the only way I can get foo'bar to return is if I change it to foo\'bar in the MySQL database and I would like not to if it is possible.
The function you want is stripslashes before mysql_real_escape_string, however your real concern should be where the slashes are actually coming from - it looks like you might have magic quotes turned on. This is deprecated - check the link for instructions on disabling it.
The Syntax at PHP requires that.
For example;
name = '$champ1'
Here you have a variable in ' tags. But that variable includes ' inside like foo'bar, its turn to that.
name = 'foo'bar'
as you see php can't understand what is going on there. So it need to clear that problem like adding before ' an \. And inserted item will have slashes before aphostropes.
As a solution you can delete the backslashes before you echo the variable.
$theVariable = str_replace("\", "", $theVariable);
Or you can use PHP's upper version's functions. like stripslashes() before you insert your data.
Good luck.

Add ' \ ' before " ' " of a string variable in javascript

I have a javascript variable which hold the value taken from somewhere else(lets say from a API call), taken string is given bellow,
He's the reason for this
I assign this string to a variable name 'sample'. But when I print it, it doesn't work since the string has " ' " character. I want to add " \ " before the " ' " character. I tried using this,
var sample = (get the string from a api call).replace(/'/g,"\\\'");
But it doesn't work?
in my javascript file I use window.location.href = "test.php?detail="+sample; to send the data.
Use encodeURIComponent to escape a string for inserting into a URI.
In my test.php, I use $detail = $_GET["detail"]; and echo $detail; to print it.
If you are printing it into HTML then use htmlspecialcharsto make it safe.
If you are printing it into JavaScript then use json_encode to make it safe.
You're overdoing the escape characters:
var sample = (get the string from a api call).replace(/'/g,"\\'");
Is enough, a single quote, delimited by double quotes needn't be escaped, so just escape one backslash.A sidenote, though: if the string you're checking is a return value, the single quotes shouldn't be a problem (if they are, the api code would break before returning the string). If you really really really want to be extra-super-mega-sure and the string is long:
var sample = (get the string from a api call).split('\'').join('\\\'');
//or (to avoid confusion with all that escaping
var sample = (get the string from a api call).split("'").join("\\'");
Splitting is faster for longer strings (not short strings, as the array constructor is called, an array-object is created, looped,...)
Presumably the problem is with (get the string from a api call). If you have some server-side code (PHP?) like this:
var sample = <?php echo $mystring ?>.replace(…);
…and it produces output sent to the browser like this:
var sample = 'my dad's car'.replace(…);
…then your server-side code has produced syntatically-invalid JavaScript that cannot be fixed by more JavaScript. Instead you need to fix it on the server, something like:
var sample = <?php echo json_encode($mystring); ?>;
It's impossible to help you further without your actual code details, however.

PHP halts output of data on apostrophe

I wrote a php script that pulls some data from a database and displays it in XML format. For some reason it halts output when it gets to an apostrophe in the data. This is a SELECT statement, and a simple one at that, so I don't understand why there are any issues with apostrophes or quotation marks. I've tried using addslashes() and mysql_real_escape_string(), even though my understanding is that those are for sanitizing data being inserted into the database, and it did not help. I'm stumped. Below is the code and thanks in advance for any advice!
<? if($result = $mysqli->query("SELECT * FROM ".$tbl)){
while($row = $result->fetch_object()){ ?>
<slide>
<id><?= $row->id ?></id>
<title><?= $row->title ?></title>
<chatter><?= $row->description ?></chatter>
<image><?= $row->path ?></image>
<link><?= $row->href ?></link>
<active><?= $row->active ?></active>
</slide>
<? }
}else{
echo $mysqli->error;
}
EDIT:
It turns out I have misunderstood the problem. They are not apostrophes but instead are right single quotes. If I change them to actual apostrophes the script works but I still don't understand why it doesn't simply output them though.
Try with str_replace("'", "\'", $field_to_be_replaced);
You can replace the ' char with a blank space if you prefer, just for testing.
Are you sure it halts on the output of the data, and not when the data is processed? Apostrophe's have special meaning in XML, so if they are included in your XML data you have to replace them with an entity reference. There are 5 predefined entity references in XML, for less than, greater than, ampersand, apostrophe, and one for quotation mark. Alternatively, you can mark the text as CDATA so that the XML parser doesn't try to parse it.
Try making your program output the XML data to a text file instead of to wherever it is going now. Does it still halt on the apostrophe? If not, then it's definitely because of a problem parsing the data. If your program still halts on the apostrophe even when outputting the data only to a text file, there may be a problem somewhere else in the program where that data is processed. Check all the references to the variable containing the data, and see if you can find the exact line the program breaks on.
the apostrophe (') is an invalid character for XML!
You must call $safe_string = str_replace("'","&apos;",$string) in all your fields before
outputting the .XML file.
Check here to learn about these characters and build a more complete str_replace
EDIT:
What im using:
// save ubercart products in XML
function replace_characters_for_xml($str) {
return str_replace(
array("&",">","<","'",'"'),
array("&",">","<","&apos;","""),$str
);
}
...
$row->title = replace_character_for_xml($row->title);
$row->href = replace_character_for_xml($row->href);
...

Categories