Send PHP variable to JavaScript function [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.
I have a php file that generates a variable and I would like the variable to be put into a JavaScript function which is called by onclick on the main page. Is this possible to send from PHP to JavaScript?
You can do the following:
<script type='text/javascript'>
document.body.onclick(function(){
var myVariable = <?php echo(json_encode($myVariable)); ?>;
};
</script>
Just write:
<script>
var my_variable_name = <?php echo(json_encode($php_string)); ?>;
</script>
Now it's available as a JavaScript variable by the name of my_variable_name at any point below the above code.
Your JavaScript would have to be defined within a PHP-parsed file.
For example, in index.php you could place
<?php
$time = time();
?>
<script>
document.write(<?php echo $time; ?>);
</script>
If I understand you correctly, you should be able to do something along the lines of the following:
function clicked() {
var someVariable="<?php echo $phpVariable; ?>";
}
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username and password:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 'You are logged in';
This would deliver the message You are logged in to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data); line in the success function would alert that message. Of course, you can echo anything that you like, even large amounts of HTML, such as entire table structures.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).
The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.
In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.
You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.
<script type="text/javascript">
// Do something in JavaScript
var x = <?php echo $calculatedValue; ?>;
// etc..
</script>
Related
Run PHP code on user click and pass variables
So I am using the following answer I've gotten from another question, <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript"> function doSomething() { $.get("somepage.php"); return false; } </script> Click Me! I'm just wondering how I can pass a couple more variables from the page this code is on to the somepage.php (the page that I am calling). Also, once that .php page is ran, how can I then use some of the data that it generates back on the page that I ran this code from (basically to update the user that it has been ran by updating a field possibly). It'd be great if someone could at least tell me how I can pass php variables over to the other .php page. By the way, I know there is a similar question here: Run PHP code when user clicks link and pass variables That also has an answer, but I am trying to use the code that I provided, since it's very simplistic.
You want an ajax post call: //Inside your function var someVar = <?php echo $variable ?>; var anotherVar = <?php echo $newVar ?>; $.post("somepage.php", {firstParam : someVar, secondParam : anotherVar}, function(data) { //this is your response data from serv console.log(data); }); You ccan access that data you sent then: $paramOne = $_POST['firstParam']; $paramTwo = $_POST['secondParam']; echo "some response"; And your data from above will be "some response". In a nutshell;
You can pass variables to php page using a POST. here a example: Pass data from jQuery to PHP for an ajax post
Pass a PHP variable dynamically to an AJAX JavaScript function
I have a JavaScript function (which users on this forum graciously helped me construct) that passes variables via POST to a PHP file with a query for inserting the data to a MySQL database. The function is invoked "onchange" for a series of 2000+ rows that are spit out from a MySQL database. I use the ID of the row to give each form field a unique name/id, like this: echo "=<select name='$AdvertisersSQLResult[id]geolocation' id='$AdvertisersSQLResult[id]geolocation' onchange = 'insertAdvertiser()'>"; The JavaScript function looks like this: function insertAdvertiser() { var data = $('#<?php echo $AdvertisersSQLResult[id]?>dataid,#<?php echo $AdvertisersSQLResult[id]?>industry,#<?php echo $AdvertisersSQLResult[id]?>geolocation').serialize(); $.post('/database/InsertAdvertiserRelationship2.php', data); return false; } As you can see, I'm attempting to pass PHP variables as part of the form id values. However, this doesn't work, as the function is written to the page once (in the section) without any variables yet populated. In other words, I'd like to have this JavaScript function utilize whatever PHP variable is being passed to it dynamically. I've looked at other threads about passing a PHP variable to a JavaScript function, but I can't find any reference to how this can be done dynamically, such that the JavaScript function changes to use a different PHP variable each time (if that makes sense). Thanks for any help...
Well yes because you'd need a seperate insertAdvertiser() method for every advertiser on the system. A better way to do it would be to do this: Javascript: // This line turns your PHP array into a Javascript object var advertisers = <?php echo json_encode($AdvertiserSQLResult); ?>; function insertAdvertiser(id) { $.post('/database/InsertAdvertiserRelationship2.php', advertisers[id]); } // Try not to use attributes to bind events, use handlers like this instead. $(document).ready(function() { $('select').on('change', function() { // Reads the advertiser id from the data attribute insertAdvertiser($(this).data('advertiserid')); }); }); HTML: <select data-advertiserid="<?php echo $AdvertiserSQLResult['id']; ?> class="advertiser-select">...</select> I wrote this as I went along so apologies if I've overlooked something. See: jQuery Data jQuery .on()
You can make a global JavaScript variable and use it in your scripts. <script type="text/javascript"> myVariable = <?php echo $x; ?>; </script> You can store your variables someplace and then access them via JavaScript. <input type="hidden" class="myVariable" value="<?php echo $x; ?>" <script type="text/javascript"> var myVar = $('.myVariable').val(); </script> After you have your data in JavaScript you can do what ever you want to do with it.
php constants in a javascript file [duplicate]
This question already has answers here: Closed 10 years ago. Possible Duplicate: Pass a PHP string to a Javascript variable (and escape newlines) I'm working on a project and it's already done, but it needs one more midification and its applying language constants in javascript files. consider we include a javascript file and in that we have something like this alert("YOU Have VOTED BEFORE"); easy like that , the script will alert that text but what if we need to alert a language constant of it : alert("<?php echo _VOTED_BEFORE?>"); this will be worked only if echo the script like inline of my php codes ... but, how can we read and include php constants or $vars for a outside JavaScript file ???
For a cleaner structure, I think the best way is to set all the data you get from PHP in one place, i.e. in the HTML you serve via PHP: <script> var MyNameSpace = { config: something: "<?php echo _VOTED_BEFORE ?>" } } </script> In the JavaScript file you include afterwards, you can access the value via MyNameSpace.config.something. This makes it also easier to reuse the message.
There is a way of doing this using a query string in the script path See my answer here How to pass variable from php template to javascript Unfortunately this will break the cache for your js file so weight your options first <script type="text/javascript" src="script.js?flag=<?php echo _VOTED_BEFORE?>"></script> for the sake of not writing too much code refer to the link to see how to retrieve the value
Actually, what you had was close to being proper. <?php // Valid constant names define("VOTED_BEFORE", "false"); ?> <script type="text/javascript"> alert("<?php echo VOTED_BEFORE;?>"); </script>
If it's not a PHP file, you cannot include PHP echo functions in it. I suggest that if you want to use a PHP variable in your external js files then declare it as a global in your PHP file before you reference the external js. <script type="text/javascript"> var globalvar = '<?php echo _VOTED_BEFORE ?>' ; </script> <script type="text/javascript" src="externalfile.js"></script> Though it's not always a good idea to clutter the global namespace.
You can use cookies to save these constants and read them in via JavaScript or you will have to use AJAX
Passing javascript variable into php code without using GET parameters?
is there any way to get js variable in php, i try something funny like this: <script> var x = "random text"; alert("aaa<?php echo md5(;?>"+x+"<?php); ?>"); </script> Of course it gives me error. Parse error: parse error, expecting `')'' in X:XXX\index.php on line XXX If there is a way without refreshing the page or using GET parameters, please let me know. Thanks EDIT: What I am trying to do is: hash(md5 inside php) the javascript variable.
PHP runs at the server, JavaScript runs at the client (browser). The only way you can pass a variable from JavaScript to PHP is sending it via an AJAX request. There are several MD5 solutions out there for JavaScript, but it's not the same if you want the variable hashed before it reaches the user.
You can't do it like that because PHP builds the page before javascript is initialized. You'll have to do an AJAX request. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> var x = "random text" $.post('md5.php', {md5:x}, function(data) { alert(data); }); </script> <?php echo md5($_POST['md5']); ?> Or.. function md5(e){function k(h,i){var g=[h&2147483648,i&2147483648,h&1073741824,i&1073741824,(h&1073741823)+(i&1073741823)];if(g[2]&g[3])return g[4]^2147483648^g[0]^g[1];return g[2]|g[3]?g[4]&1073741824?g[4]^3221225472^g[0]^g[1]:g[4]^1073741824^g[0]^g[1]:g[4]^g[0]^g[1]}function n(h,i,g,j,s,m,o){h=k(h,k(k(i&g|~i&j,s),o));return k(h<<m|h>>>32-m,i)}function p(h,i,g,j,s,m,o){h=k(h,k(k(i&j|g&~j,s),o));return k(h<<m|h>>>32-m,i)}function q(h,i,g,j,s,m,o){h=k(h,k(k(i^g^j,s),o));return k(h<<m|h>>>32-m,i)}function r(h,i,g,j,s,m,o){h=k(h,k(k(g^(i|~j),s),o));return k(h<<m|h>>>32-m,i)}function t(h){var i="",g,j;for(j=0;j<=3;j++){g="0"+(h>>>j*8&255).toString(16);i+=g.substr(g.length-2,2)}return i}var f=[],v,w,x,y,a,b,c,d;e=function(h){var i=h.length,g=0,j=0,s="",m;for(m=0;m<i;m++){var o=h.charCodeAt(m),u=null;if(o<128)j++;else u=o>127&&o<2048?String.fromCharCode(o>>6|192,o&63|128):String.fromCharCode(o>>12|224,o>>6&63|128,o&63|128);if(u!==null){if(j>g)s+=h.substring(g,j);s+=u;g=j=m+1}}if(j>g)s+=h.substring(g,h.length);return s}(e);f=function(h){var i=h.length,g=i+8;g=((g-g%64)/64+1)*16;var j=Array(g-1);for(l=0;l<i;l++)j[(l-l%4)/4]|=h.charCodeAt(l)<<l%4*8;j[(l-l%4)/4]|=128<<l%4*8;j[g-2]=i<<3;j[g-1]=i>>>29;return j}(e);d=271733878;a=1732584193;b=4023233417;c=2562383102;for(e=0;e<f.length;e+=16){v=a;w=b;x=c;y=d;a=n(a,b,c,d,f[e+0],7,3614090360);d=n(d,a,b,c,f[e+1],12,3905402710);c=n(c,d,a,b,f[e+2],17,606105819);b=n(b,c,d,a,f[e+3],22,3250441966);a=n(a,b,c,d,f[e+4],7,4118548399);d=n(d,a,b,c,f[e+5],12,1200080426);c=n(c,d,a,b,f[e+6],17,2821735955);b=n(b,c,d,a,f[e+7],22,4249261313);a=n(a,b,c,d,f[e+8],7,1770035416);d=n(d,a,b,c,f[e+9],12,2336552879);c=n(c,d,a,b,f[e+10],17,4294925233);b=n(b,c,d,a,f[e+11],22,2304563134);a=n(a,b,c,d,f[e+12],7,1804603682);d=n(d,a,b,c,f[e+13],12,4254626195);c=n(c,d,a,b,f[e+14],17,2792965006);b=n(b,c,d,a,f[e+15],22,1236535329);a=p(a,b,c,d,f[e+1],5,4129170786);d=p(d,a,b,c,f[e+6],9,3225465664);c=p(c,d,a,b,f[e+11],14,643717713);b=p(b,c,d,a,f[e+0],20,3921069994);a=p(a,b,c,d,f[e+5],5,3593408605);d=p(d,a,b,c,f[e+10],9,38016083);c=p(c,d,a,b,f[e+15],14,3634488961);b=p(b,c,d,a,f[e+4],20,3889429448);a=p(a,b,c,d,f[e+9],5,568446438);d=p(d,a,b,c,f[e+14],9,3275163606);c=p(c,d,a,b,f[e+3],14,4107603335);b=p(b,c,d,a,f[e+8],20,1163531501);a=p(a,b,c,d,f[e+13],5,2850285829);d=p(d,a,b,c,f[e+2],9,4243563512);c=p(c,d,a,b,f[e+7],14,1735328473);b=p(b,c,d,a,f[e+12],20,2368359562);a=q(a,b,c,d,f[e+5],4,4294588738);d=q(d,a,b,c,f[e+8],11,2272392833);c=q(c,d,a,b,f[e+11],16,1839030562);b=q(b,c,d,a,f[e+14],23,4259657740);a=q(a,b,c,d,f[e+1],4,2763975236);d=q(d,a,b,c,f[e+4],11,1272893353);c=q(c,d,a,b,f[e+7],16,4139469664);b=q(b,c,d,a,f[e+10],23,3200236656);a=q(a,b,c,d,f[e+13],4,681279174);d=q(d,a,b,c,f[e+0],11,3936430074);c=q(c,d,a,b,f[e+3],16,3572445317);b=q(b,c,d,a,f[e+6],23,76029189);a=q(a,b,c,d,f[e+9],4,3654602809);d=q(d,a,b,c,f[e+12],11,3873151461);c=q(c,d,a,b,f[e+15],16,530742520);b=q(b,c,d,a,f[e+2],23,3299628645);a=r(a,b,c,d,f[e+0],6,4096336452);d=r(d,a,b,c,f[e+7],10,1126891415);c=r(c,d,a,b,f[e+14],15,2878612391);b=r(b,c,d,a,f[e+5],21,4237533241);a=r(a,b,c,d,f[e+12],6,1700485571);d=r(d,a,b,c,f[e+3],10,2399980690);c=r(c,d,a,b,f[e+10],15,4293915773);b=r(b,c,d,a,f[e+1],21,2240044497);a=r(a,b,c,d,f[e+8],6,1873313359);d=r(d,a,b,c,f[e+15],10,4264355552);c=r(c,d,a,b,f[e+6],15,2734768916);b=r(b,c,d,a,f[e+13],21,1309151649);a=r(a,b,c,d,f[e+4],6,4149444226);d=r(d,a,b,c,f[e+11],10,3174756917);c=r(c,d,a,b,f[e+2],15,718787259);b=r(b,c,d,a,f[e+9],21,3951481745);a=k(a,v);b=k(b,w);c=k(c,x);d=k(d,y)}return(t(a)+t(b)+t(c)+t(d)).toLowerCase()}; var x = "random text"; alert(md5(x));
You could use an ajax call to your server and have a webservice on the php side returning the information you need. Besides that? I don't think there is a way expect for refreshing.
How to pass data from Javascript to PHP and vice versa? [duplicate]
This question already has answers here: How do I pass JavaScript variables to PHP? (16 answers) Closed 2 years ago. How do I pass have a Javascript script request a PHP page and pass data to it? How do I then have the PHP script pass data back to the Javascript script? client.js: data = {tohex: 4919, sum: [1, 3, 5]}; // how would this script pass data to server.php and access the response? server.php: $tohex = ... ; // How would this be set to data.tohex? $sum = ...; // How would this be set to data.sum? // How would this be sent to client.js? array(base_convert($tohex, 16), array_sum($sum))
Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request. An example (using traditional event registration model for simplicity): <!-- headers etc. omitted --> <script> function callPHP(params) { var httpc = new XMLHttpRequest(); // simplified for clarity var url = "get_data.php"; httpc.open("POST", url, true); // sending as POST httpc.onreadystatechange = function() { //Call a function when the state changes. if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors alert(httpc.responseText); // some processing here, or whatever you want to do with the response } }; httpc.send(params); } </script> call PHP script <!-- rest of document omitted --> Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;) See also Mozilla's documentation for further examples
I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution: My simple client side code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> <title>Test Page</title> <script> function passVal(){ var data = { fn: "filename", str: "this_is_a_dummy_test_string" }; $.post("test.php", data); } passVal(); </script> </head> <body> </body> </html> And php code on server side: <?php $fn = $_POST['fn']; $str = $_POST['str']; $file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w"); echo fwrite($file,$str); fclose($file); ?> Hope this works for you and future readers!
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
Using cookies is a easy way. You can use jquery and a pluging as jquery.cookie or create your own. Using Jquery + jquery.cookie, by example <script> var php_value = '<?php echo $php_variable; ?>'; var infobar_active = $.cookie('php_value'); var infobar_alert = any_process(infobar_active); //set a cookie to readit via php $.cookie('infobar_alerta', infobar_alerta ); </script> <?php var js_value = code to read a cookie ?> I've found this usefull Server-Side and Hybrid Frameworks: http://www.phplivex.com/ http://www.ashleyit.com/rs/ I've been using Ashley's RSJS Script to update values in HTML without any problem for a long time until I met JQuery (ajax, load, etc.)
There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values. <script language="javascript" type="text/javascript"> function _vals(target, value){ form1.all("target").value=target; form1.all("value").value=value; form1.submit(); } </script> Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier. I'm sure there's probably more methods which are better, but these are just a few that spring to mind. EDIT: Building on this from what others have said using the above method you would have an anchor tag like <a onclick="_vals('name', 'val')" href="#">My Link</a> And then in your PHP you can get form data using $val = $_POST['value']; So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX. The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax