Getting PHP variables intact with jQuery/json - php

So, a quick breakdown.
I've got a function on my page loads three sections, currently it loads them separately (which is kind of slow). So I've recently combined them all.
I now have all of the information stored in PHP variables. I'd like to get those PHP variables and load them into separate divs.
here is an example of what I'd like to do.
HTML
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
PHP
$var1 = "<div><p>data 1</p></div>";
$var2 = "<div><p>data 2</p></div>";
$var3 = "<div><p>data 3</p></div>";
jQuery
//`get var1,var2,var3`
// load var1 into div.one
// load var2 into div.two
// load var3 into div.three
The current problem I'm having is json_encode is changing some information into this "\n\t\t\t\t\t\t" and it's printing
"<div><p>data 1</p></div>"
instead of "data 1" in a p inside of a div.

Try:
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<script>
var var1 = "<?php echo json_encode($var1); ?>";
var var2 = "<?php echo json_encode($var2); ?>";
var var3 = "<?php echo json_encode($var3); ?>";
$(".one").html(var1);
$(".two").html(var2);
$(".three").html(var3);
</script>
You can pass PHP to JS in this way, but not the other way around.

var var1 = "<?php echo json_encode($var1); ?>";
var var2 = "<?php echo json_encode($var2); ?>";
var var3 = "<?php echo json_encode($var3); ?>";

Related

jquery how to break string and continue string after

im trying to do this to get loop i variable inside my php variable
var monthyear[i] = "<?php echo $startmonth_name"+i+" ?>";
so it will show like:
var monthyear[i] = "<?php echo $startmonth_name1 ?>";
var monthyear[i] = "<?php echo $startmonth_name2 ?>";
can't figure it out and i keep getting error:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';'
Loop in javascript won't work for reasons mentioned in my comment, you can try having a loop in php code, something like below.
Replace this with
var monthyear[i] = "<?php echo $startmonth_name1 ?>";
var monthyear[i] = "<?php echo $startmonth_name2 ?>";
With
<?php
for($i=0;$i<some_value;$i++)
{
echo "var monthyear[".$i."] = ". ${'startmonth_name'.$i} .";"
}
?>
Note: I haven't tested the code. This is just to give an idea.
do this instead:
<?php echo "var monthyear["+i+"] = '"+ $startmonth_name[i]+"';"; ?>;
change these to an array to use them in the loop: $startmonth_name1
Forget about JavaScript right now. JavaScript will be executed later, in another computer, possibly some thousand kilometres away. You are getting a PHP parse error: that means that your PHP code does not even run. And it's clear why—the PHP block contained in this code:
var monthyear[i] = "<?php echo $startmonth_name"+i+" ?>";
... is this:
echo $startmonth_name"+i+"
You might get away with something like this:
var monthyear[i] = <?php echo json_encode($startmonth_name); ?>+i;
Yet I suggest you remember that PHP and JavaScript will simply neither interact nor share variables and rethink your logic accordingly.

How to reach php $_SESSION array in javascript?

I am trying to build some javascript function and I need to check if the users are logged in or not. When a user log in to my site I set a variable in session array named is_logged. I want to reach that variable in javascript is it possible???
I tried some ways but did not work like following:
var session = "<?php print_r $_SESSION['is_logged']; ?>";
alert(session);
and:
var session = '<?php echo json_encode($_SESSION['is_logged']) ?>';
alert(session);
It is either show a text or never alert at all
Just echo it:
var session = <?php echo $_SESSION['is_logged']?'true':'false'; ?>;
alert(session);
You need tertiary operator, as false is echoed as empty string so it would lead to var session = ; which is a JS syntax error.
If you want to reach all elements of $_SESSION in JavaScript you may use json_encode,
<?php
session_start();
$_SESSION["x"]="y";
?>
<script>
var session = eval('(<?php echo json_encode($_SESSION)?>)');
console.log(session);
//you may access session variable "x" as follows
alert(session.x);
</script>
But note that, exporting all $_SESSION variable to client is not safe at all.
Try the following code:
var session = "<?php echo $_SESSION['is_logged'] ?>";
In a js file you cant get the value of a php variable or php code doesnt works on a js file because php code will works in a .php extension file.
So one method is to set the session value as a hidden element value and in your js file get the value of the hidden element.
In the html:
<input type="hidden" id="sess_var" value="<?php echo $_SESSION['is_logged']; ?>"/>
In your js:
var session = document.getElementById('sess_var').value;
alert(session);
You can do things like this
Just insert the $_SESSION['is_logged'] in a hidden field like
<input type = "hidden" value = "<?php echo $_SESSION['is_logged']; ?>" id = "is_logged" />
Then you can access that in your jquery like this
var is_logged = jQuery.trim($('#is_logged').val());
//then do validation here
var get_session=<?php echo $_SESSION['is_login']
alert(get_session);
?>
## *Just try this * ##

How can I pass a PHP variable to Javascript variable from two separate pages?

I am trying to pass a PHP variable to Javascript variable for example:
<?php $myvar=10; ?>
<script type="text/javascript">
jsvar = <?php echo $myvar; ?>;
document.write(jsvar);
</script>
How could this be done separating the variable on another page? For instance Page1.html would have the document.write and the variable would be pulled from page2.php
Only with Ajax. For example with jQuery:
$.get('page2.php', function(data) {
alert( data );
});
...
UPDATE
Or alternatively (because smart people pointed out that there is always more than 1 way to go) you can include page2.php in your page1.php and the variable value will become available:
<?php
require_once('page2.php');
?>
<script type="text/javascript">
jsvar = <?php echo $myvar; ?>;
document.write(jsvar);
</script>

how to pass a php var through jquery?

i have this script on JsFiddle .
when i click on the links i get another view.
What i am trying to do is replace
<a id="mine_click" href="#">test</a>
with:
$test = 'here we go'
<a id="mine_click" href="?var=$test">test</a>
and pass the $test var to the tab3view when i click on the test link,
so that the result will be 2222 here we go
any ideas on how to pass a php var through a link going through jquery?
thanks
I'm not sure that it is exactly what you need.
You have a php variable from the server side. In your javascript code you can do
var foo = '<?php echo $test; ?>';
and then you can use foo as a javascript variable
$('#mine_click').attr('href','?var='+foo);
You could do:
var test = '<?php echo($test) ?>';
$('#mine_click').attr('href', '?var='+test);
?var=<?php echo $test; ?>
will do the stuff
$('#mine_click').attr('href', '?var=<?php echo $test; ?>');

Storing php $_GET variable in a javascript variable? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I am passing two pieces of info to a php page using the $_GET method (team1, team2).
I'd like to use these as variables in some javascript. How can I do this?
Thanks
Since $_GET just access variables in the querystring, you can do the same from javascript if you wish:
<script>
var $_GET = populateGet();
function populateGet() {
var obj = {}, params = location.search.slice(1).split('&');
for(var i=0,len=params.length;i<len;i++) {
var keyVal = params[i].split('=');
obj[decodeURIComponent(keyVal[0])] = decodeURIComponent(keyVal[1]);
}
return obj;
}
</script>
Original answer:
In your .php file.
<script type="text/javascript">
var team1, team2;
team1 = <?php echo $_GET['team1']; ?>;
team1 = <?php echo $_GET['team1']; ?>;
</script>
Safer answer:
Didn't even think about XSS when I blasted this answer out. (Look at the comments!) Anything from the $_GET array should be escaped, otherwise a user can pretty much insert whatever JS they want into your page. So try something like this:
<script type="text/javascript">
var team1, team2;
team1 = <?php echo htmlencode(json_encode($_GET['team1'])); ?>;
team1 = <?php echo htmlencode(json_encode($_GET['team1'])); ?>;
</script>
From here http://www.bytetouch.com/blog/programming/protecting-php-scripts-from-cross-site-scripting-xss-attacks/.
More about XSS from Google http://code.google.com/p/doctype/wiki/ArticleXSSInJavaScript.
Cheers to the commenters.
Make sure you use something like htmlentities to escape the values so that your application is not susceptible to cross-site scripting attacks. Ideally you would validate the variables to make sure they're an expected value before outputting them to the page.
<script type="text/javascript">
var team1 = '<?php echo htmlentities($_GET['team1']); ?>';
var team2 = '<?php echo htmlentities($_GET['team2']); ?>';
</script>
<script type="text/javascript">
var team1 = <?php echo $_GET['team1'] ?>;
var team2 = <?php echo $_GET['team2'] ?>;
</script>
Another way to do this with javascript :
var team1 = $_GET('team1');
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
The other methods are kind of dirty, and there can be some problems. Your better off just using javascript:
<script>
function get_data(name){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null) return "";
else return results[1];
}
var var1 = get_data('var1');
var var2 = get_data('var2');
</script>
But this still isn't super secure.
Another way of doing this, which I just thought of, is to print the $_GET array. I don't know if that would work, though. Anyway, if it does, then here it is:
<script>
var _get = <?php print_r($_GET); ?>
var team1 = _get['team1'];
var team2 = _get['team2'];
</script>
And you would want to run array_walk(or something like that), on a function to clean each string.
Make sure your $_GET vars are available and not empty and use the following:
<script type="text/javascript">
var team1 = <?php echo $_GET['team1']; ?>;
var team2 = <?php echo $_GET['team2']; ?>;
</script>

Categories