Problem with mixing Javascript the PHP - php

I am trying to assign values in javascript assigned from PHP and the use document.write() to output them. The problem is when I do this, a complete blank screen shows up but no errors are ever thrown. But if I take the PHP out and put in a value such as 'ABC' it works. And example of my code can be this:
var comment_text="<?php echo $value['comment_text'];?>";
var bodyelement = document.getElementsByTagName('body')[0];
var newdiv = document.createElement('div');
newdiv.style.textAlign = 'center';
newdiv.style.zIndex = 10001;
newdiv.style.left = (<?php echo $comment_x;?>+getPos('browserwindow',"Left")-23) + 'px';
newdiv.style.top = (<?php echo $comment_y;?>+getPos('browserwindow',"Top")-90) + 'px';
newdiv.style.position = 'absolute';
newdiv.innerHTML = comment_text;
bodyelement.appendChild(newdiv);
I do have an PHP error log and no errors are beign thrown either. The values are retrieved from the database, the probem comes with outputting them.
*UPDATE*
Ok, I had this problem before.
Basically a newline is created like this:
var comment_text="cool Beans
";
I have tried to remove the newline with string replace but doesn't seem to work. Why would a new line like this cause this error?

Your issue is cleary in the output from PHP. If you get a blank page, means you most likely have a PHP issue that is HALTING the processing of said page.
As PHP is parsed before anything is sent to the viewer, this will result in a blank / error page.
When you substitute your $value['comment_text'] for ABC you remove the location that causes the error.
I am going to assume that $value['comment_text'] is either a result of a function, or a Database query, try just outputting the $value['comment_text'] first, then worry about sticking it in JS (which will work if your PHP code works).
As I don't see any of your PHP code, I cannot help you further.

Use
var comment_text=String(<?php echo json_encode($value['comment_text']);?>);
instead of
var comment_text="<?php echo $value['comment_text'];?>";
This will protect you from cross-site-scripting attacks by escaping all special characters like backslashes, quotes or line feeds.
The String(...) ensures that comment_text has type String and is not interpreted as a number (if $value['comment_text'] is has a number type).

If PHP is causing an error (sounds like it is) you can turn on your error reporting to see the issues
error_reporting(E_ALL)

The solution was just using trim.
echo trim($value['comment_text']);

I recommend you use a heredoc for the javascript code with %s in the js. and use sprintf to substitute the variables.

Related

trouble with double quotes first record of PHP array

php5, Microsoft SQL Server Management Studio, OS 6.3.15063. i get $row data via mssql_fetch_assoc and stuff a PHP array with the $row data just fine when the first record does not have double quotes. subsequent row data can have double quotes, just not the first row. Error: "SyntaxError: missing ) after argument list" in jquery.min - so i cannot peruse and get helpful info from that. code:
$History_SQL = "
DECLARE #AID int;
SET #AID = $Activity_ID;
SELECT activityid, lpid, abstract, changeid, changestamp FROM cpy_activity_history
WHERE activityid = #AID ORDER BY changestamp DESC;
";
$History_results = mssql_query($History_SQL);
while ($row = mssql_fetch_array($History_results)) {
$HistoryRecords[] = $row;
}
This works when record index[0] does not have double quotes, but when double quotes, errors out.
Interestingly, if i use:
$HistoryRecords[] = json_encode($row);
RESULT>>SyntaxError: missing ) after argument list
then it gets past the error; but I am having trouble usind json_decode to get any useful information out of the array [not even getting js braces or anything, getting another record from another table, possibly because this value is not what it thought it was going to be/either way, not sure i am even starting down the right road with json_endode/decode.]
it could be i simply do need help learning how to decode each record coming out of the json encoded var. either way, does this problem look familiar, and any ideas for how to stop getting the error? NOTE: ultimately, i need to display the array information via javascript. other related posts do not seem to cover this scenario. these double quotes are proving maddening. thanks in advance!
thx, All for helping!
the SYMPTOMS included the [a]browser crashing with console/js error: "missing ) after arg list", [b]a var in the code to display an erroneous field, unrelated to the sql used to create info for that var.
the REASON this occurred was that i had within PHP, a console.log that contained a PHP variable. so i was mixing js and PHP. the PHP was firing late and so at the time, the js console.log had nothing to display.
the CLUE which led to fixing this was noticing that the js msg was crashing in the browser, YET the php LOG_IT stmts below the js were working. the js was trying to console.log a msg that had a null value, and somehow a js var was getting loaded with wrong information. sheeze.
the CODE - before the fix the php echo from within the console.log was the culprit. i tossed the original offending stmt, but it was something like this:
<?php here in php land....., now i want to do a console.log....
?><script>console.log("show me info!: " <?php echo $info; ?></script><?php
...back in php land...
i commented out the "echo $info;" and things worked. of course i ripped it out altogether. funny, it would've cleared itself up when i stopped banging my head on the wall and simply decided to clean up and remove all the troubleshooting console.logs.
the CONCLUSION - an old lesson, "don't mix js and php", even in error logging!
thx again for all your help!

php htmlspecialchars and jquery .text()

I ran into an issue recently. I have a system where users can post stuff. One of the fields is the title field. So to save user input safely I use htmlspecialchars on the user submitted title and send it to a function that then saves to the database (after using mysql_real_escape)
Now on the client's side I use json get to fetch this title
$.getJSON("PHPFILE", function(json) {
// let's say json.title is the title we need so...
var title = json.title;
}
Now the thing is this user given title value can contain anything, even html tags (for reference let's say it now contains
<script>alert('');</script>Some Text!
so since I use jquery I thought of clearing those using the .text() function
var cleanTitle = $(title).text();
alert(cleanTitle);
However this immediately throws an error. In chrome it says
Uncaught Error: Syntax error, unrecognized expression ...
So I verified if this title variable is a string. And it is indeed a string. (Btw for some reason if this variable contains only numbers there is no error)
Using the following however gives me the text but the tags aren't removed
var cleanTitle = $.parseHTML(title);
cleanTitle = $(cleanTitle).text();
alert(cleanTitle);
This outputs
<script>alert('')</script>Some Text!
How can I remove all html tags? Any suggestions? I am planning to use this title text to set Browser title. Thanks.
document.title = $('<div />').append( $('<div />').html( title ).text() ).text();
Appending the string twice should fix the htmlentities issues.
Since you are using MySQL as engine to store that kind of data, you are clearly using PHP scripting. Suggestion: use PHP's strip_tag() and you are cutting "workload" for jQuery/Javascript by letting PHP do the work.

Fill jQuery or ajax by PHP var

Is it possible to fill jQuery variable by PHP???
I mean something like this:
<?php
$string_php = "50%";
?>
And with "$string" variable I want to fill jQuery:
var jquery_string = "$string_php";
$('.bar1').animate({'height':'jquery_string'},500);
The code above is only idea how I would like to be working
Yes but with php tags <?php ?> (so that php knows its code):
var jquery_string = "<?php echo $string_php;?>";
$('.bar1').animate({'height':jquery_string}, 500); // no quotes for variables
It is possible because PHP (server-side) runs before jQuery (client-side). The page first goes to server and server returns the response (php code is parsed there) to the browser.
Sure
var jquery_string = "<?php echo $string_php;?>";
Since PHP is processed first on the server and the result is then sent to the user's browser, this is easy, and often done.
The above code would result in:
var jquery_string = "50%";
You would, however want to modify your second line, removing the quotes from the variable so it was:
$('.bar1').animate({'height':jquery_string},500);
since keeping the quotes around jquery_string would make force it to be interpreted as a string whereas you want a variable.
The end result would be the equivalent of:
$('.bar1').animate({'height':'50%'},500);
For simple variables, just do as the users said.
F.ex. var jquery_string = "<?php echo $string_php;?>"; (taken from #Blaster's solution).
In other words:
The most simple solution is to output a php variable that we intend to use as string literal via echo anywhere we define the variable.
But: a correct approach would be that everytime we use a serverside variable as a Javascript string, it should be encoded, because the above solutions would fail when double quotes are present. Here json_encode may come handy.
var jquery_string = <?php echo json_encode($var); ?>;
Code example
We want Javascript alert the string "Hey", dude!
$string = "\"Hey\", dude!";
echo "alert(\"" . $string . "\");";
results in:
alert(""Hey", dude!"); <--- will give Javascript error
Instead:
echo "alert(" . json_encode($string) . ");";
results in:
alert("\"Hey\", dude!"); <---- correct JS code

prevent php from removing backslashes from output

On my site, I have a PHP script which takes multiple source files (HTML,CSS, and javascript), optimizes them, embeds them into a page, and caches them (basically compiling my website). Recently, I have added jquery-json (a jQuery plugin for encoding JSON into strings), but part of the code contains multiple slashes (used in some sort of a regex):
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,
When this line is processed by the script I mentioned earlier one of the backslashes is removed and results in:
var escapeable = /["\\x00-\x1f\x7f-\x9f]/g,
Also, I have setup a short script to make sure the problem is not being caused by something in the way that the javascript is being processed by the PHP script, and that it is in fact a issue with the way that PHP outputs it:
<?php
$string = 'var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,';
echo($string); //this outputs: var escapeable = /["\\x00-\x1f\x7f-\x9f]/g,
?>
As you can see by the comment, the problem is the same in the simple script too...
I'm not sure if this is relevant, but I have checked to make sure that magic quotes are off. Also, I am aware of 'escapeable' being misspelled but, that's just the way it is in the jquery-json source code.
So, how do I prevent PHP from removing backslashes from the output?
You may use the nowdoc-syntax(requires PHP 5.3.0 ):
$string = <<<'EOD'
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,
EOD;

using php include in jquery

What im trying to do, is use php include within a jquery append attribute. something like this:
$('a.popup[href^=#]').click(function() {
$('body').append('<div id="content" class="popup_block"><?php include( SITE_URL . 'activity/popup.php' ) ?></div>');
My script is in a php file, server side, so that i could accomplish this, but im not sure how to go about it. When it comes to html, css etc. I can combine it and php within the php file, but when it comes to javascript, its the quotes that confuses me, and when and how to use the brackets. This might sound confusing lol. Anyways, does CDATA have anything to do with it? I've never used it before, but I should atleast learn it's use.
The PHP interpreter will only look for <?php and ?> tags and try to evaluate anything in between. It doesn't care about surrounding quotes. You need to make sure though that the result of whatever PHP does is valid Javascript.
var foo = '<?php include 'foo.php'; ?>';
becomes
var foo = 'This is the content of foo.php.';
after PHP is done with it.
If there are any quotes in foo.php, it may become this:
var foo = 'This is the 'content' of foo.php.';
which is invalid Javascript syntax. You'll need to escape any character of foo.php that may cause such invalid syntax, for example with addslashes. This can be quite cumbersome though, so I'd advise to look for an alternative this to begin with.
You can encode the value using JSON, which is definitely syntax safe:
var foo = <?php echo json_encode("Some string with 'quotes'."); ?>;
Generating code in code is always tricky, try to not do it and stick to language neutral data interchange formats like JSON or XML.
If you are 100% sure you don't have any single quotes in your include, there should be no problems with how you have it.
If you want to visualize it, copy all of your generated code from the included php file and paste it right into the main page inside of the append(). See how it looks. This will give you a good idea of what the browser will end up with.

Categories