Javascript php variable not passing with http_build_query [duplicate] - php

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
Why does this not work?
var data1 = "<? http_build_query($_GET); ?>";
var data2 = "buy.php?";
var url = data2+data1
document.getElementById('framebox').src = url;
Thanks.

Because data1 is empty (PHP is not outputing anything), try:
var data1 = "<?= http_build_query($_GET); ?>"; // or
var data1 = "<?php echo http_build_query($_GET); ?>";
Any reason you're using PHP to build the query string instead of doing it directly in Javascript?

You can also archive it the plain old pure javascript way:
var data1 = location.href.split('?').pop();
var data2 = "buy.php?";
var url = data2+data1
document.getElementById('framebox').src = url;
But it's much more fun to mix stuff.....

Related

How I can use the Javascript variable in PHP? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have that code:
function saveData(position, map) {
var latlng = marker.getPosition();
var late = latlng.lat();
var longe = latlng.lng();
<?php
require("sql.php");
session_start();
$name = 'prova';
$address = 'temare';
$type = 'bar';
$late = "<script>document.getElementByID('late').value</script>";
$longe ="<script>document.getElementByID('longe').value</script>";
I need to get late and longe variables in PHP but this doesn't work, anyone knows how I can do it?
You can't access javascript variables using PHP as JavaScript is executed on client side ( browser ) and PHP on server side.
The best what you can do is send data from those variables as request to server and read them, for example using jQuery ajax request:
Good example you can find here:
jQuery Ajax POST example with PHP
Or you can use this:
javascript
function sendData(variable1, variable2) {
$.ajax({
type: 'post',
url: 'myphpscript.php'
data: 'var1='+variable1+'&var2='+variable2
});
myphpscript.php
<?php
$variable1 = $_POST['var1'];
$variable2 = $_POST['var2'];
<script type="text/javascript">
<?php $abc = "<script>document.write(late)</script>"?>
<?php $def = "<script>document.write(longe)</script>"?>
</script>

delete or clear cookie using javascript or php [duplicate]

This question already has answers here:
Clearing all cookies with JavaScript
(26 answers)
Closed 9 years ago.
I want to javascript or php script delete the cookie that i was set up with javascript now i want to delete that cookie.
here this is my javascript:
<script type="text/javascript">
var url = window.location.hash;
var result = url.split('?');
var advertise = result[1].split("&");
var id = advertise[0].split("=");
document.cookie = "update_id=" + id[1];
var name = advertise[1].split("=");
document.cookie = "update_name=" + name[1];
</script>
how to delete or clear this cookie using javascript or php code.
You can do like this in JavaScript :
Just call delete_cookie function by passing your cookie name.
function delete_cookie(cookie_name)
{
var cookie_date = new Date ( ); // current date & time
cookie_date.setTime (cookie_date.getTime() - 1);
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}
You can do like this in PHP :
setcookie("cookie_name", "", time()-3600);

Passing a JavaScript Array to A PHP Class Via AJAX? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Passing JavaScript Array To PHP Through JQuery $.ajax
Can I pass an array to a php file through JavaScript using AJAX? In my application code
JavaScript builds the parameters based on user input, and then an AJAX call is made to a processing script.
For example, if the processing script url was process_this.php the call made from JavaScript would be process_this.php?handler=some_handler&param1=p1&param2=p2&param3=p3
Could I do something like this?:
process_this.php?handler=some_handler&param1=[array]
Thanks.
using JQUERY you could do something like this
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var jsarr = new Array('param1', 'param2', 'param3');
$.post("process_this.php", { params: jsarr}, function(data) {
alert(data);
});
});
</script>
php script
<?php print_r($_POST['params']); ?>
output would be
Array ( [0] => param1 [1] => param2 [2] => param3 )
What about sending an JSON Object via Post to your PHP-Script?
Have a look at this PHP JSON Functions
You can use JSON to encode the array to a string, send the string via HTTP request to PHP, and decode it there. You can do it also with objects.
In Javascript you do:
var my_array = [p1, p2, p3];
var my_object = {"param1": p1, "param2": p2, "param3": p3};
var json_array = JSON.stringify(my_array);
var json_object = JSON.stringify(my_object);
var URL = "process_this.php?handler=some_handler" +
"&my_array=" + json_array + "&my_object=" + json_object;
In PHP you do:
$my_array = json_decode($_POST['my_array']));
$my_object = json_decode($_POST['my_object']));
You can send a json object to your php , thats the standard approach

boolean variable values in PHP to javascript implementation [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've run into an odd issue in a PHP script that I'm writing-- I'm sure there's an easy answer but I'm not seeing it.
I'm pulling some vars from a DB using PHP, then passing those values into a Javascript that is getting built dynamically in PHP. Something like this:
$myvar = (bool) $db_return->myvar;
$js = "<script type=text/javascript>
var myvar = " . $myvar . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";
The problem is that if the boolean value in the DB for "myvar" is false, then the instance of myvar in the $js is null, not false, and this is breaking the script.
Is there a way to properly pass the value false into the myvar variable?
Thanks!
use json_encode(). It'll convert from native PHP types to native Javascript types:
var myvar = <?php echo json_encode($my_var); ?>;
and will also take care of any escaping necessary to turn that into valid javascript.
This is the simplest solution:
Just use var_export($myvar) instead of $myvar in $js;
$js = "<script type=text/javascript>
var myvar = " . var_export($myvar) . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";
Note: var_export() is compatible with PHP 4.2.0+
$js = "<script type=text/javascript>
var myvar = " . ($myvar ? 'true' : 'false') . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";

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