Passing value to PHP variable inside script - php

I have some PHP code inside the script so I need
the JavaScript value as a PHP variable, as follows:
<script>
;
var js_var = 123;
var php_var = <?php js_var ?>;
alert(php_var);
;
</script>
Using jQuery to send the value to a PHP page will return the value but not as a PHP variable:
$.get("page.php", {js_var_name: js_var}, function(data) {alert(data)});
I tried also all jQuery AJAX functions: load(), post() and the ajax() method, none of them pass back the value of PHP as above requested.
Is it possible to implement the above with jQuery?

Likely you have a syntax issue with :
var php_var = <?php js_var ?>;
Unless you used define() your php variable should start with $ and you need to echo it so that it gets printed to the page
var php_var = <?php echo $js_var ?>;
If you are assuming that php will read the prior javascript js_var=123 it won't. Javscript is a client side language and php is server side.

You cannot simply mix PHP and JavaScript. The former is executed on the server, the latter on the client, namely in the user's browser. In order to hand a value from PHP to JavaScript you need to output JavaScript code via PHP or do a AJAX-Request to a PHP-Script, as you tried. When using AJAX, it is the easiest solutions to have PHP script that returns a JSON string. When calling this script using $.get() the result will be stored in a JavaScript variable and you can access all the values from there.
Take a moment and a deep breath...and then start thinking about your scopes again.

Related

How to get JavaScript variable value in PHP

I want the value of JavaScript variable which i could access using PHP.
I am using the code below but it doesn't return value of that variable in PHP.
// set global variable in javascript
profile_viewer_uid = 1;
// php code
$profile_viewer_uid=$_POST['profile_viewer_uid'];
this gives me the following error :-
A PHP Error was encountered
Severity: Notice
Message: Undefined index: profile_viewer_uid
Another php code i used which give empty value
$profile_viewer_uid = "<script language=javascript>document.write(profile_viewer_uid);</script>
When I echo it shows nothing.
Add a cookie with the javascript variable you want to access.
document.cookie="profile_viewer_uid=1";
Then acces it in php via
$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];
You will need to use JS to send the URL back with a variable in it such as:
http://www.site.com/index.php?uid=1
by using something like this in JS:
window.location.href=ā€¯index.php?uid=1";
Then in the PHP code use $_GET:
$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar
Here is the Working example: Get javascript variable value on the same page.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.
Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.
If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.
<script type="text/javascript>
var foo = <?php echo json_encode($somePhpVar); ?>
</script>
If you want to use a js variable in a php script you MUST pass it within a HTTP request.
There are basically two ways:
Submitting or reloading the page (as per Chris answer).
Using AJAX, which is made exactly for communicating between a web page (js) and the server(php) without reloading/changing the page.
A basic example can be:
var profile_viewer_uid = 1;
$.ajax({
url: "serverScript.php",
method: "POST",
data: { "profile_viewer_uid": profile_viewer_uid }
})
And in the serverScript.php file, you can do:
$profile_viewer_uid = $_POST['profile_viewer_uid'];
echo($profile_viewer_uid);
// prints 1
Note: in this example I used jQuery AJAX, which is quicker to implement. You can do it in pure js as well.
PHP runs on the server. It outputs some text. Then it stops running.
The text is sent to the client (a browser). The browser then interprets the text as HTML and JavaScript.
If you want to get data from JavaScript to PHP then you need to make a new HTTP request and run a new (or the same) PHP script.
You can make an HTTP request from JavaScript by using a form or Ajax.
These are two different languages, that run at different time - you cannot interact with them like that.
PHP is executed on the server while the page loads. Once loaded, the JavaScript will execute on the clients machine in the browser.
In your html form make a hidden field
<input type="hidden" id="scanCode" name="SCANCODE"></input>
Then in your javascript update the field value by adding;
document.getElementById("scanCode").setAttribute('value', scanCode);
This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself.
Given that you have added an php command to catch the variable, you will get it.
You need to add this value to the form data that is submitted to the server. You can use
<input type="hidden" value="1" name="profile_viewer_uid" id="profile_viewer_uid">
inside your form tag.

Include javascript variable inside php tags

i have javascript as below
html="<th>"+<?php echo __(); ?>+"</th>";
I want to add another javascript variable inside to __() function like this
<?php echo __(<js varible>); ?>
I tried
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
not working for me
can any one help me please
regards
You have a misunderstanding on how server side and client side code work.
The only way that you could possibly achieve what you are trying to do (apply a PHP localization function to a Javascript variable) would be like this (this code assumes you are using JQuery but can be done without it too):
var myvariable = 'hello';
$.get('http://yoursite.com/localize.php?text='+myvariable, function(localizedText) {
html = "<th>"+localizedText+"</th>";
console.log(html);
});
And then localize.php should look like this:
<?php
include('you localization library');
echo __($_GET['text']);
?>
Explanation: while your client side code (Javascript) is been executed in the browser it will call a URL which will execute your server side code (your PHP __(); function) in the server and then return the value to the client side code.
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
This would try to put the PHP variable "myvariable" into the script tag, what you want is closer to:
var myvarible=200;
html="<th>"+"<?php echo __("'myvarible'"); ?>"+"</th>";
console.log(html);
However, in this case, why not just skip PHP completely?
var myvarible=200;
html="<th>" + myvarible + "</th>";
console.log(html);
Javascript runs on client side and php on server side.
So var myvarible=200;
will be executed only on client side .
but will be get executed on server side. at that time myvariable will not be valid.
PHP is executed on the server, JS on the client. You cannot expect PHP to parse JS, in fact PHP will never see the JS statements, because they will be processed only once the server has processed the PHP.
var myvariable='<?php echo __("200"); ?>';
html="<th>"+myvariable+"</th>";
console.log(html);
However for this to work the javascript would need to be in a .php file that is being interpreted.
The OP wants to include a JS variable in a PHP call, which is not possible, unless you use AJAX. And you'll agree with me that code like this is only meant to cause big headaches and should be avoided at all costs.
Well yes and no.. i wouldnt do it this way. I use a helper that lets me do things like this in a consistent way. In my view file i have something like:
<?php js_call('jslib.myFunction(?,?)', __($value), 'some other value'); ?>
js_call its similar to using sprintf or a prepared statement except for js. The params are run through json_encode so the quoting and what not are correct. All these are stored in an array and then in the layout, just before my </body> i call:
<?php include_js_calls(); ?>
which then takes all the calls ive made with a js_call and outputs the string values inside a script tag resulting in something like:
<script type="text/javascript">
jslib.myFunction('first value', 'some other value');
</script>
Borrowed this brilliance from Apostrophe Cms
To do localization in javascript (for whatever reason), echo __() can obviously not be called directly.
There are different possible strategies
Include a localization string table in javascript when the page loads. Do lookup against it when needed. This table could be generated on server-side using echo __() then cached.
Make ajax requests for server-localized data. Might not be suitable for frequent updates.

Pass Javascript var into PHP var

var javascript_variable = $("#ctl00").text();
<?php $php_variable = ?> document.write(javascript_variable); <? ; ?>
I want to pass the above javascript_variable into php_variable. This code is giving me an error. Any ideas on how?
You cannot do that.
PHP is executed on your server. Javascript on the otherhand is executed on your client's machine in the browser.
There are two different execution context. While you can pass a PHP variable into Javascript, you cannot do the opposite since PHP is executed first and the JavaScript code is the output of your PHP code.
If you want to send a Javascript variable to PHP, you have to do with in a separate request either via a cookie or an AJAX request. Here's an example:
$.ajax({
url: 'receivingScript.php',
data: {'value': $("#ct100").text()}
});

How do I assign a javascript variable to a PHP variable?

I have a javascript variable which holds some information and I want that to assign in a PHP variable. Here is what I am using:
<script type="text/javascript">
function redirectToFacebook()
{
var facebookMessage = encodeURI(document.getElementById('txt_msg').value);
}
</script>
<?php
$_SESSION['sess_facebook_message'] = facebookMessage;
?>
Any help is really appriciable.
Thanks in advance
Because PHP runs on the server, and JavaScript in the client, there is no way to set a PHP session variable after JavaScript works with it, as PHP has done executing before the page was even sent.
However...
If you use JavaScript to make a request (AJAX, imagehack or otherwise) to a PHP script that sets the variable, you can.
For example...
JavaScript:
function something() {
// do something with somevar
somevar = 'content';
// make an AJAX request to setvar.php?value=content
}
PHP:
$_SESSION['somevar'] = $_GET['somevar'];
Make sure you take security issues of client-generated data into account, though.
If you want to pass variables from the browser (javascript) to your backend server (PHP), you need to either:
1) Load a new page with Javascript parameters encoded either as POST or GET
2) Asynchronously call a PHP script (AJAX call) encoding the parameters as POST or GET
A simple example using a GET request (you simply append your parameters to the URL):
<script>
window.location = '/some-url?' + document.getElementById('text_msg').value;
</script>
You probably want to assign this piece of code to a button or something...
what you are trying to achieve is not possible due to API limitation.It does not provide that.
may be you can try to redirect with javascript and pass variables form php to js. They way yout tru it, it can't work.
may be, im realy not shure
try this.
<?php
function redirectToFacebook() {
var facebookMessage = ?>
<script>
document.write(encodeURI(document.getElementById('txt_msg').value));
</script>
<?php
}
?>
or using cookies.

How do I access a PHP variable from JavaScript?

How do I call PHP variables or queries in JavaScript?
<script>
var foo = <?php echo $foo; ?>;
// or, if foo is a string;
var foo = '<?php echo addslashes($foo); ?>';
// for anything more complex, you'll need to use json_encode, if available in your version of PHP
var foo = <?php echo json_encode($foo); ?>;
</script>
Please note, you can only do this one way. Don't expect any changes you make in javascript to come through to PHP.
PHP and JavaScript cannot mix directly. You use PHP server-side to generate and send JavaScript to the client. the JavaScript executes client-side and can communicate with PHP code on the server only via AJAX calls. This can be simplified drastically through the use of an AJAX library like jQuery.
You have to keep in mind that your PHP code is evaluated on the server, while JavaScript (normally) runs in the browser. The evaluations happen in different times, at different places. Therefore you cannot call a JavaScript function (or variable) from PHP, simply because you cannot call a function that exists on another computer.
You may want to check if Ajax is an appropriate solution for your problem.
Generally, you can't. PHP is server-side and Javascript is client-side (processed by the browser).
The exception is to use AJAX, which allows you to access PHP pages, which should then execute the action needed.
You can use JSON for this purpose which serves well for sending a big array to Javascript from PHP. We need to echo JavaScript code in PHP script or we can use Ajax for this. But usually we may need to send a big array. So we can do like this
<script>
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
?>
var foo = echo json_encode($arr);
</script>
The json_encode function will handle all escaping and other issues. Bug also make sure json_encode is available in your PHP version.

Categories