Passing javascript variable into php code without using GET parameters? - php

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.

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

Calling a PHP function through an HTML Link (no form)

I have a PHP Function that I would like to integrate into my (existing) web page. Further, I would like it to execute when the user clicks a link on the page. The function needs to accept the text of the link as an input argument.
Everything I've researched for sending data to a PHP script seems to involve using forms to obtain user input. The page needs to accept no user input, just send the link-text to the function and execute that function.
So I guess the question is two-part. First, how to execute a PHP script on link click. And second, how to pass page information to this function without the use of forms. I am open to the use of other technologies such as AJAX or JavaScript if necessary.
EDIT:: Specifically what I am trying to do. I have an HTML output representing documentation of some source code. On this output is a series of links (referring to code constructs in the source code) that, upon being clicked, will call some python function installed on the web server (which leads me to think it needs called via PHP). The python function, however, needs the name present on the link as an input argument.
Is there some sort of interaction I could achieve by having JavaScript gather the input and call the PHP function?
Sorry for the vagueness, I am INCREDIBLY new to web development. If anything is unclear let me know.
You'll need to have a JS function which is triggered by an onclick event which then sends an AJAX request and returns false (so it won't be redirected to a new page in the browser). You can do the following in jQuery:
jQuery:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("myfile.php");
return false;
}
</script>
And in your page body:
Click Me!
In myfile.php:
You can add whatever function you want to execute when the visitor clicks the link. Example:
<?php
echo "Hey, this is some text!";
?>
That's a basic example. I hope this helps.
You will need to use AJAX to accomplish this without leaving the page. Here is an example using jQuery and AJAX (this assumes you have already included the jQuery library):
First File:
<script language="javascript">
$(function(){
$('#mylink').click(function(){
$.get('/ajax/someurl', {linkText: $(this).text()}, function(resp){
// handle response here
}, 'json');
});
});
</script>
This text will be passed along
PHP File:
$text = $_REQUEST['linkText'];
// do something with $text here
If you are familiar with jQuery, you could do the following, if you don't want the site to redirect but execute your function:
in your html head:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
the link:
Execute function
in ajax.php you put in your function to be executed.
Maybe something like this:
....
<script>
function sendText(e)
{
$.ajax({
url: '/your/url/',
data: {text: $(e).html()},
type: 'POST'
});
}
</script>
You can use query strings for this. For example if you link to this page:
example.php?text=hello
(Instead of putting a direct link, you can also send a ajax GET request to that URL)
Inside example.php, you can get the value 'hello' like this:
<?php
$text = $_GET['hello'];
Then call your function:
myfunction($text);
Please make sure you sanitize and validate the value before passing it to the function. Depending on what you're doing inside that function, the outcome could be fatal!
This links might help:
http://net.tutsplus.com/tutorials/php/sanitize-and-validate-data-with-php-filters/
http://phpmaster.com/input-validation-using-filter-functions/
Here's an overly simplistic example of what you're trying to do..
Your link:
Some Action
Your PHP file:
<?php
if (isset($_GET['action']))
{
// make sure to validate your input here!
some_function($_GET['action']);
}
PHP is a server side language i.e. it doesn't run in the web browser.
If you want a function in the browser to operate on clicking a link you are probably talking about doing some Javascript.
You can use the Javascript to find the text value contained in the link node and send that to the server, then have your PHP script process it.

Send PHP variable to JavaScript function [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 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>

Calling JavaScript within Php block and vice-versa

echo "<a href=#> Delete </a>";
Whenever a user hits Delete, a javascript function should be called for confirmation. Somewhere in the Javascript function, php code should be used for delete operation. How do I do that? Use something like "some php code goes here" and "some javascript function();" for me to know where to put what. Thanks.
This assumes that you are using jQuery...
<a href='javascript:delete();'>Delete</a>
<script type="text/javascript">
function delete()
{
$.post("/your_script.php", {}, function(result) {
});
}
</script>
JavaScript functions execute on the client (in the browser) and PHP executes on a server. So, the JavaScript must send a message - via HTTP - to the server to be handled by PHP. The PHP would perform the delete. Make sense?
The message sent to the server might be sent via AJAX.
Maybe you should use Ajax: http://en.wikipedia.org/wiki/Ajax_%28programming%29
PHP is a server-side technology, while JS is a client-side. They cannot interact with each other - in other words: they're completely independent.
PHP can only output code that is a JS code:
echo 'document.getElementById("test").appendChild(document.createTextNode("' . $myVar . '");';
It's all PHP can do. JavaScript cannot direct interact with PHP as well. You'll have to use AJAX to send a new HTTP request and process returned data.
PHP is a server-side language, thus you can not output PHP script to the browser and expect that it will parse it with the PHP engine.
What you're looking for is probably AJAX, or simply redirecting the user to another page (with different URL parameters) or submitting a form.
AJAX doesn't require from the browser to reload the page, while the two other methods does.
Anyway, you can execute a JS script with the "onclick" method, that's executed when the user clicks on the element: Delete
But the following approach looks better and considered as an ideal one:
Delete
<script type="text/javascript">
document.getElementById("myId").onclick = myFunc;
</script>
Since this involves Ajax, let's assume you can use jQuery to handle the XHR an so on.
<script>
$('#del').click(function(ev){
ev.preventDefault();
var del_conf=confirm('Are you sure you want to delete this item?');
if(del_conf){ $.post('delete.php',{'del':1,'id':123123},function(data){
alert(data.result);},'json');
}
});
</script>
<a id='del'>Delete</a>
Okay, so that's some JS and HTML. Now, you need a separate PHP script to handle the post. To go with the example, this would be saved in the same directory, named 'delete.php'.
<?php
$del=(int)$_POST['del'];
$id=(int)$_POST['id']
if($del<1 || $id<1){ exit; }
else{
//do your DB stuff
}
if($db_success){
echo json_encode(array('result'=>'success'));
}
else{
echo json_encode(array('result'=>'error'));
}
here is another example using jQuery:
<div id="message"></div>
<a class="action" type="delete" rel="1234567">delete</a>
<script type="text/javascript">
$('a.action').click(function(){
var $this = $(this);
var processResponse = function(data){
//optionaly we can display server response
$('#message').html(data);
return;
};
var postPparams = {
module:'my_module_name',
action:$this.attr('type'),
record_id: $this.attr('rel')
};
$.post('/server.php',postPparams, processResponse);
});
</script>

php in javascript?

i need to have some php code inside javascript
<script ...>
<?php
echo " ... ";
?>
</script>
but this doesnt work. how can u implement php inside javascript that is in a own file javascript.php?
That doesn't do what you probably think it does. It'll work, but the PHP gets run once, when the page is loaded, not every time the JavaScript function is called.
Just for clarification, this is what will happen
index.php
<script type="text/javascript">
<?php echo "alert('hello!');"; ?>
</script>
output html in browser
<script type="text/javascript">
alert('hello!');
</script>
If that is what you want to do, then you can output all the javascript you like. What you cannot do is execute PHP code in the user's browser.
your can use php to dynamically generate javascript code, but you cannot execute php client side. If you need to execute php you will need to postback or use AJAX
There seems to be a good bit of misunderstanding of the question... Here is what you want to do to generate JS from PHP on the server:
file javascript.js.php
<?php
header('Content-Type: text/javascript');
?>
// javascript code here
function PrintTime()
{
alert("The time is " + <?php echo json_encode(time()); ?>);
}
Now, include it on the HTML page using normal script tags:
<script type="text/javascript" src="/url/to/javascript.js.php"></script>
The server will process the PHP file, and return javascript from it.
You can't run PHP inside a javascript file. Primarily because PHP runs server side and is processed before the client is sent any actual http info. JavaScript is processed by the browser on the client side and is sent as text.
It looks like you want to pass some kind of dynamic info to the JavaScript. You can do this by passing a variable like this:
<?php $variable="its me"; ?>
<script>
alert('<?php print($variable)?>')
</script>
The output passed to the client is:
<script>
alert('its me')
</script>
What are you trying to accomplish and maybe we can help you come up with a better solution?

Categories