Problem with strings using slash (/) in PHP - javascript

I have some id (primary keys from database) with the next format: 2019/34. I show this code in a table where i can see it normally. The problem comes when i try to send this variable in PHP to a javascript method. As im using a slash in the id, when i send the php variable as parameter of the javascript method, it makes the count. It divides 2019 and 34 when i want to send the parameter 2019/34.
I have tried to parse the actual php string variable to string before send it through the parameter.
I have tried to send the parameter using quotes but it makes the count too.
I have even tried to separate the id (2019 and 34), send them to the javascript method using two parameters and making again the complete string in the method. But when i use the explode method (explode("/",$id)), it makes the count again.
echo "<td><a href='javascript:newConcepto(".$id.")'></a></td>"
Expected object sended: "2019/34".
Actual object sended: "59.3823529" (The division of 2019 and 34).

When you don't put the variable in quotes (from a JavaScript perspective), it assumes that you're doing math - as 2019 / 34 is a mathematical equation. Wrap it in quotes, and it becomes a string instead! To avoid collision with the href attribute, use doublequotes there - and to avoid conflict with the PHP double quotes, escape them.
echo "<td></td>";
PHP variables are parsed within double quotes, so you don't need to concatenate the value either, you can do it all inline. There's nothing wrong with doing it either though, by doing newConcepto('".$id."').

Try this
echo "<td><a href='javascript:newConcepto('".$id."')'></a></td>"

Related

PHP - return confirm within PHP issue

could somebody please help me with the below:
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
I know there is an issue with some " ' " but can't figure this out. I am getting a syntax error just before the 'Are'. The line of code was working as expected before I added the:
onclick="return confirm('Are you sure you want to claim this ticket?');"
Thanks!
If you want to use the same quotes you opened the string with inside the string itself, you should escape it.
For instance:
$var = 'Hello, let's go!';
echo $var;
This code will throw a parse error because this is how PHP sees the code:
) New variable $var.
) Is a string, declared using single quotes '.
) After the opening quote we have 'Hello, let'
) Now PHP expects some kind of valid code operators, like ., and next string or ;, but it gets some characters, which are treated as instructions rather than strings because they are outside the quotes, and
) PHP throws a parse error.
To fix this, you can use the backslash \ a.k.a 'escaping' character.
For example, to fix your problem:
echo
('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
See the baskslashes \ surrounding the single quotes inside the confirm JavaScript function? This tells PHP to treat these quotes as normal characters instead of string start/end declarations. Same thing works for reversal when you use double quotes as string declarators.
For example, when you want to show the actual representation of $ or any characters that have special meaning in a double quoted string, which allows direct insertion of variables (and some other's, like class properties) values you would use the escaping character.
For example:
$apples = 12;
$talk = "I have $apples \$apples. Thanks, now have a backlash! \\!";
echo $talk;
This will output I have 12 $apples. Thanks, now have a backslash! \!
Now, you are not actually required to escape the escaping character (it will show just as well if it does't have anything to escape after it).
Read this: PHP Manual - About Strings
You can also switch your single quotes on the edges of your echo statement with regular quotes, which will allow you to insert the $id variable easier. Then, you just have to escape the quotes around your JavaScript in onClick and switch all the other quotes to single quotes.
echo "<a href='assign.php?id=$id' onclick=\"return confirm('Are you sure you want to claim this ticket?');\" style='text-decoration: none'><font color='FFFFFF'><b>Click here to claim ticket</b></font></a>";
However, there is a better way.
Interpolate PHP into HTML
(Instead of HTML into PHP)
The best way to do this is to write HTML as HTML, and interpolate PHP variables into the HTML. This is best practice as it allows syntax highlighting in IDE's, and looks much cleaner/easier to read.
Just write the entire element as HTML, and then echo the $id variable inside the HTML (instead of writing all of the HTML in a PHP echo statement).
<a href="assign.php?id=<?=$id;?>" onclick="return confirm('Are you sure you want to claim this ticket?');" style="text-decoration: none">
<font color="FFFFFF">
<b>
Click here to claim ticket
</b>
</font>
</a>
With this method, you don't have to worry about escaping quotes, and it will allow you to use regular quotes throughout your entire element.
You need to escape the nested ' by doing \'
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
Note that all the stuff inside the single quotes is considered as string by the PHP interpreter.
Docs: PHP: Variables - Manual

How to get single quotes inside a javascript variable (=function parameter) escaped? [duplicate]

In PHP, I use json_encode() to echo arrays in HTML5 data attributes.
As JSON requires - and json_encode() generates - values encapsulated by double quotes. I therefor wrap my data attributes with single quotes, like:
<article data-tags='["html5","jquery","php","test's"]'>
As you can see, the last tag (test's) contains a single quote, and using json_encode() with no options leads to parsing problems.
So I use json_encode() with the JSON_HEX_APOS parameter, and parsing is fine, as my single quotes are encoded, but I wonder: is there a downside doing it like this?
You need to HTML escape data echoed into HTML:
printf('<article data-tags="%s">',
htmlspecialchars(json_encode(array('html5', ...)), ENT_QUOTES, 'UTF-8'));
or use the build-in option:
json_encode(array('html5', ...), JSON_HEX_APOS)
you can check it up in the manual: http://php.net/manual/en/json.constants.php#constant.json-hex-apos

Append user data to url before sending request in PHP

What would be the easiest way to append form data to a json url prior to sending the request? I know next to nothing about php but Im trying either way
The PHP I have so far, I need to replace the ZIP before.json with the content im getting from $_GET['zip']
<?php
$zip = $_GET['zip'];
$zip_data = file_get_contents($zip);
$weather_data = file_get_contents("http://api.wunderground.com/api/myapi/conditions/q/ZIP.json");
echo $weather_data;
?>
In PHP if you just put the variable name inside a string that is quoted with double quotes, it puts the value into the string:
$weather_data = file_get_contents(".../q/$zip.json");
You can also put curly brackets around it to make it cleaner to read:
$weather_data = file_get_contents(".../q/{$zip}.json");
Or you can close the string, use the dot operator to concatenate, and reopen the string:
$weather_data = file_get_contents(".../q/" . $zip . ".json");
Replace
"http://api.wunderground.com/api/myapi/conditions/q/ZIP.json"
With
sprintf("http://api.wunderground.com/api/myapi/conditions/q/%s.json", $_GET['zip'])
(or whatever variable you want to take it's place)
More on string formatting with sprintf

Escaping quotation marks in PHP for JavaScript function argument

I'm having trouble escaping a quotation mark in PHP.
I have a table of products and each row has an onclick function, with the name of the product as the argument.
The name contains the length which is measured in inches, so the name contains a quotation mark. I wrapped an addslashes() around the string. This adds a backslash before the quotation mark but for some reason it doesn't seem to escape the character!
Here's a snippet of my code:
<?$desc1 = addslashes($row['Desc1']);?>
<tr class='tableRow' onclick='afterProductSelection("<?=$desc1?>")'>
<td><?=$row['Desc1']?></td>
When I inspect element in Google Chrome, the colour of the syntax indicates that this has not been escaped, clicking on it gives me a syntax error.
Probably something simple that I'm missing. Hope you can help!
There are a lot of different cases where you need to escape a string. addslashes() is the wrong answer to pretty much all of them.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything.
In your particular case, since you're creating Javascript data from PHP, use json_encode().
json_encode() will take a PHP variable (whether it's a string, array, object or whatever) and convert it into a JSON string. A JSON string is basically fully escaped Javascript variable, including the quotes around your strings, etc. This is what you need to do.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything. -Spudley
I think the function you're looking for is htmlentities()
<?=htmlentities($desc1, ENT_QUOTES)?>
http://ca1.php.net/htmlentities
You are generating a JavaScript string encoded as HTML so you need to encode twice:
Use json_encode() to generate the string
Use htmlspecialchars() to encode as HTML
Use json_encode to output variables from the backend in JavaScript:
<tr onclick='afterProductSelection(<? print json_encode($desc1); ?>)'>
N.B.: For string output there is no need for extra quotes.

apostrophe mark is sent with Backslash in javascript string which is being sent to php page using ajax as part of json object

apostrophe mark is sent with Backslash in JavaScript string which is being sent to php page using ajax as part of json object
var qry="SELECT
invpurchaseitme.Code,
invpurchaseitme.Description,
invunits.Description,
invpurchaseitme.StoreGroup
FROM
invpurchaseitme
LEFT JOIN
invunits
ON
(invpurchaseitme.UOMCode = invunits.Code)
WHERE (
invpurchaseitme.Code LIKE '%d#t#%'
OR
invpurchaseitme.Description LIKE '%d#t#%'
OR
invunits.Description LIKE '%d#t#%'
OR
invpurchaseitme.StoreGroup LIKE '%d#t#%'
)
AND
invpurchaseitme.StoreGroup='"+$("#StoreCode").val()+"'
ORDER BY invpurchaseitme.Code ASC
LIMIT 70"
I am replacing d#t# character with a php variable in the php page using explode() after it is being sent using ajax to the php page. But what I get in the final query is \'%variablename%\' instead of '%variablename%'. I have tried using slashes for escaping ' but the result is same. how to get string without slashes
This solved my problem. stripslashes(str).
http://us1.php.net/stripslashes

Categories

Resources