Fill jQuery or ajax by PHP var - php

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

Related

how to get an array from a php explode result?

$_SESSION['consequnce1']=[1,2,3]
$consequenceStr1=implode( ',', $_SESSION['consequence1']); //for storage to databases
$_SESSION['consequence1']=explode(',', $consequence1);
//$_SESSION['consequence1'] now is like["1","2","3"].
in html, I want get the array[1,2,3].
var sess = JSON.parse("<?php echo json_encode($_SESSION['consequence1']); ?>");
var num =sess[0];
but this two line code does not work, what's the problem?
thanks
Answer: do not know the reason in fact. But just change
var sess = <?php echo json_encode($_SESSION['consequence1']); ?>;
then it works.
Thanks for others' reply
That is, because json_encode provides value that can be used directly in JavaScript. It wraps strings in double quotes and takes care of other types to be valid as well. JSON.parse takes string as an argument, which is not necessary.
In your example, you had messed double quotes, like this:
JSON.parse("["1","2","3"]")

How to set javascript variable to php session variable

Whats the best way to do this?
I have this $_SESSION["sessionOpentok"] I need to set to this java script var var session_id
Security isn't an issue, its okay for the end user to be able to see this session id.
I have heard of AJAX calls, json encode, delimiters, php echo, php print.
None seems to work. echo and print do not work due to quote being in the session variable.
JSON encode encodes this the number to a null.
Any ideas. Thanks
In theory, just var session_id = <?php echo json_encode($_SESSION['sessionOpentok']); ?>; should do it.
However, you mayhave an encoding problem if you're getting null. Try:
var session_id = <?php echo json_encode(utf8_encode($_SESSION['sessionOpentok'])); ?>;
Escape the string before echoing it:
var session_id = '<?php echo addslashes($_SESSION["sessionOpentok"]) ?>';
This might not work depending on how you plan to use the session_id variable as the strings won't match.

Problem with mixing Javascript the 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.

How to read a file line using php in a javascript variable without the breakline character?

I have a txt file on the server which contains 10 lines of text. The text file is rewritten sometimes, and I get new lines using "\r\n". My problem shows when I want to load the lines in javascript variables. I do it like this, but this work only for numbers or for the last line of the file, because its not using the breakline tag: var x = '<?php echo $file[0]; ?>';
Ive tried to alert(x) but it`s not working.... (working only if I read the last line)
Any idead ?
I'm not sure I completely understand the question, but you should be able to use json_encode() which will escape the data appropriately:
var x = <?php echo json_encode($file[0], JSON_HEX_TAG); ?>;
As others have said, you can trim() the data to remove trailing whitespace/line breaks. You should still use json_encode() in addition to this as otherwise it will still be possible to break out of the javascript string (e.g. by sending a string with a quote in).
You want trim():
var x = '<?php echo trim($file[0]); ?>';
But if you read the file(), you could array_map() it with trim() and then keep doing what you're doing:
$values = array_map("trim", file('input-file.txt'));
You might consider what happens if someone decides to include a single quote in the variable with this approach.
EDIT: Then you can add json_encode() as suggested in other answers:
var x = <?php echo json_encode($file[0]); ?>;
Thanks for all! The I solved the problem with the help of artlung and Richard JP Le Guen:
var x = <?php rtrim($file[0]); ?>

Javascript Object Not Digging My PHP Var's Value (Has HTML in It)

I'm building a CMS for a client (Building on top of wordpress). I'm having an issue with some data I am returning from my database.
Basically I am building Javascript Objects from PHP data so that I can update certain areas of my site upon mouse click.
example (this would work fine):
<script language = "Javascript>
var myObject = new Object();
function updateDiv(id)
{
myObject.name = '<?php echo $valueName ?>'; // $varHeadline = "Bob"
myObject.headline = '<?php echo $value_headline ?>'; // $varHeadline = "My Story"
var div = document.getElementById(id).innerHTML = myObject.name +
'<br>' + myObject.headline';
}
</script>
The problem comes up when the data I bring back from my database already has some html, or line breaks in it.
Example:
echo $varHeadline;
// returns <h1>This is my headline</h1>
// This is part of the value too.
So if I create a Javascript Object with that data:
function updateDiv(id)
{
myObject.headline = '<?php echo $varHeadline; ?>';
var div = document.getElementById(id).innerHTML = myObject.headline;
}
I get errors in my Javascript.
I would like to continue populating my divs with Javascript Object data, but am unable to on account of some of the data containing HTML (or even single or double quotes for that matter).
I DO want to retain my HTML formatting (the <h1> tags and so forth) so using htmlspecialchars or strip_tags is out of the question. Is there any die hard way of storing returned HTML without killing Javascript?
Thanks in advance.
-J
json_encode() the string and take away the quotes:
myObject.headline = <?php echo json_encode($varHeadline;) ?>;
Of course, you could rewrite this as:
<script language = "Javascript>
var myObject = <?php echo json_encode(array('name'=>$valueName,'headline'=>$value_headline)); ?>;
function updateDiv(id)
{
var div = document.getElementById(id).innerHTML = myObject.name +
'<br>' + myObject.headline';
}
</script>
edit: as noted in the comments below, always make sure you can trust the HTML you're placing on the page. If $valueName or $value_headline is coming from user input, this is a bad idea if you don't validate the HTML in some other fashion, you're open to XSS attacks and the like: http://en.wikipedia.org/wiki/Cross-site_scripting
When you "quote" server-side values being dropped into a page, the quoting has to be different when the context is Javascript code and not HTML. For HTML, of course, you do things like turn ampersands into "&" and less-than symbols into "<", and so on. Well inside Javascript strings, less-than and ampersand aren't a problem - they might be later if you're going to stuff the string into HTML, but right there at the time the Javascript parser is reading the string, there's no problem. What is a problem are quotes and characters outside the good ol' 7-bit ASCII range. (That's a generalization, but you see what I mean.)
I don't know PHP but it seems like there has to be some way to tell it NOT to perform the quoting appropriate for HTML/XML, and to instead do something to protect the characters that are special inside Javascript string constants.

Categories