How to get JavaScript variable value in PHP - 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.

Related

Access a PHP array element by using a JavaScript variable as index

The code looks like this:
PHP file
<?php
...
$arrayName = ['ArrayValue_0', ..., 'ArrayValue_n'];
...
php?>
JavaScript
$('.elementClass').each(function(index, id) {
$(id).html('<?php echo $arrayName[index - 1]?>');
});
But you can't just insert a JavaScript variable like that into php tags so index is never received.
I know this can be done via AJAX but is there any other way? Thanks in advance.
Additional info:
I've been told to do this in PHP so there's no posibility of switching the array to a JS file.
You can define arrayName variable in JS and initialize it with the value from the server:
var arrayName = <?php echo json_encode($arrayName); ?>;
$(".elementClass").each(function(index, id) {
$(id).html(arrayName[index-1]);
});
What you're trying to do will not work. For example this:
$(id).html('<?php echo $arrayName[index - 1]?>');
The above will never, ever work, because PHP is run on a server, not on your user's browser.
What you need to do is send the variable somehow to the server. You have a plethora of options:
Use a form and read a $_POST variable
Append it to a URL and read a $_GET variable
Use AJAX and asynchronously send that variable to the server
Return the whole array from PHP to your Javascript code
etc. etc.
Remember, PHP runs on the server, which renders the page, which then in turn is read by your browser where you run Javascript. You can't paste PHP code into the page and expect it to be parsed by PHP!
You need to get back to the server if you wish to get info from it (PhP runs on the server), so either you create a javascript variable on-the-fly when loading the page with the complete content of your PhP array , either you use ajax to get back to the server without refreshing the whole page.

PHP Array in Javascript Variable - JS Element

I have a Javascript variable which I am setting a PHP variable to.
function cancel(number) {
var message = "<?= $message[" + number + "]; ?>";
}
$message is an array. "number" is the element of the array I want to set message to. Basically, I want to set a Javascript variable to a PHP variable using a Javascript variable as the element picker. So if "number" was 2, it would select:
$message[2];
However, the above approach doesn't work, and I'm not even sure if this is possible.
It isn't. Use XHR to retrieve the value from the server.
It doesn't seem at all possible; PHP is evaluated server-side, and javascript is evaluated client-side. So PHP would see it as $message["+number+"], and try to find the value at the index of "+number+". You'd probably have to do something like an AJAX request to get the data you're looking for.
What you are doing isn't possible; since php is a server-side language, it's executed first, and the js is executed after; there isn't any way to control which is executed first. You must retrieve the variable using AJAX.
Something like this will work:
<script type="text/javascript">
var messages = <?= json_encode($message) ?>;
function cancel(number) {
var message = messages[number];
}
</script>
Of course this will output the entire array in the JavaScript source. If it is large, then you are better off using AJAX.
Tip: if you "view source" it should be painfully obvious why your method doesn't work.
You simply cannot do this using this methodology. PHP is server-side code, meaning that it runs on the server, while JavaScript is client-side code, meaning it runs on the client, or your browser.
Once the PHP runs, it generates an HTML document and sends that document in the response to the browser. Once that's complete, the only way you can get data back to the server is to send it via a form POST, send it via AJAX, or send it via script tag remoting.
Consider looking at some examples on the Internet of how to POST data back to the server via a form and via AJAX. It's clear you're struggling with some concepts regarding how to properly architect your program, and looking at some examples would be a great way for you to learn and master these techniques.
PHP Submit Form Example
PHP Tutorial
You need to use AJAX call to resolve your issue.

jQuery / PHP mix up

I have the following jQuery function in my PHP:
echo '
function myFunction() {
return $.ajax({
type: "POST",
url: "mypage.php",
data: "name=John&location=Boston"
});
}
$.when(myFunction()).then(function(data) {
// handle data return
someOtherFunction(data);
// need to set "data" var into PHP SESSION
}, function(error) {
// handle ajax error.
});
';
After my AJAX does the majic it returns a value (data), which I pass into another function. In addition I need to be able to set that value into a PHP session:
$_SESSION['project'][data] = data;
How do I do that? The switching between PHP and JS confuses me for some reason...
That's impossible since the JS is now on the client side. You can't set PHP variables directly.
What you could do is set a cookie in JS using document.cookie, and then on the next page request PHP can get at it via $_COOKIE.
You could also just set the $_SESSION variable inside mypage.php - that may be significantly easier, if they both share the same session.
It's confusing because you're mixing the two, try to keep a distinct separation in your code. Instead of echoing your jQuery script, just close the php tag, that would also make syntax highlighting work.
As for setting session variables, you need to do it on the server side in your mypage.php, before writing the data to the output. That will happen before passing the data to the client side jQuery script for processing.
First of all you must be aware the javascript is a clientside language and PHP is serverside. Everything PHP does, it does when the page loaded and it stops after the page is loaded. Javascript takes over then.
What you could do is create mypage in a way that it also creates $_SESSION['project']['data'] as an associative array that you can use with PHP. What you're not trying to do is setting a javascript array into a PHP variable. Not that this is wrong by default, but since you're trying to SET the data using PHP my guess is you will also GET the data using PHP, thus a javascript array in that session would be useless.
So in mypage.php you've probably have something like:
echo json_encode($result);
Where $result is the array of data returned by the script. You could simply add one line above saying:
$_SESSION['project']['data'] = $result;
and have the data stored in the session to use on other pages.

Is it possible to read a PHP session using Javascript?

I am using cakePHP 1.26.
In a controller, I got a function which contains these lines of code:
$this->Session->write('testing', $user);
$this->Session->read('testing');
Now the system wrote a session and stored on the server.
Is it possible to use Javascript or Jquery to read the session named 'testing' ?
The PHP session is stored in webserver's memory while JavaScript runs in the webclient (webbrowser). Those are in real world two physically separate and independent machines. They usually can only communicate with each other over network using HTTP protocol.
You have 2 options:
Let PHP print the session data as if it's a JS variable:
<script>var data = '<?= $_SESSION['data'] ?>';</script>
Let JS request it from the server end using Ajax. Here's a jQuery based example:
<script>$.get('script.php', function(data) { /* .. */ });</script>
with basically this in script.php:
<?php echo $_SESSION['data']; ?>
Needless to say that option 1 is the most easy and straightforward.
No. Generally, you could write the value of testing into the document delivered to the client (a small javascript in the head perhaps?), and then it would be available to the client end.
As other people have already said, getting the session at the client side requires some forethought (blurting it out on the page) or another request.
The other solution is not to use a session but use cookies instead or as a compliment. Just don't trust the cookies. Users can edit them so they should only be used for display stuff.
Is it possible to use Javascript or Jquery to read the session named 'testing' ?
No, but you can use PHP to put the value into javascript:
<?php
print "<script type=\"text/javascript\">\n";
print " var testing=\"" . $_SESSION['testing'] / "\";\n";
print "</script>\n";
?>
(or into the HTML and read it back from there using Javascript)
No. You can use JavaScript to make an AJAX get request to a PHP page that would read the session data and return to the JavaScript.
You can easily pass the session variable from the PHP server using jQuery AJAX to the JavaScript. You can pass it as Json object and then assign it to a JavaScript variable.

Calling JavaScript with PHP

I want to call a PHP function when pressing on a button, sort of like:
<?php
function output(){
// do something
}
?>
<input type="button" value="Enter" onclick="output()"/>
I tried to make something like:
<input type="button" value="Enter" onclick="test.php?execute=1"/>
where test.php is current page and then by php
<? if(isset(&execute)){ echo "Hello"; } ?>
but it doesn't work.
Since PHP runs on the webserver, and buttons (and JavaScript in this case) appear on the client, you have to make an HTTP request to the server.
The easiest way to do this is to use a form. No JavaScript is required. You can add JavaScript (although it should be layered on top of a working non-JS version). Using JavaScript to make an HTTP request without leaving the page is known as Ajax, and generally achieved with the XMLHttpRequest object. There are various libraries such as YUI and jQuery that can do some of the heavy lifting for you.
I think using an AJAX call would do sort of what you are asking. I don't know PHP very well but you can use the following example, and add another variable with the data you are passing in to the server to indicate which function you want to call on the server. On the server you can add some "IF" statements that will call a certain function based on the name passed in and return the result.
Here is what you could use on in your javascript client using the jQuery library as a helper to do the AJAX call:
<input type="button" value="Enter" onclick="output()"/>
<script type="text/javascript">
function output(){
$.ajax({
type: "POST",
url: "submit_data.php",
data: "username=" + "SomeUser"
+ "&email=" + "someEmail#google.com"
+ "&functionName=" + "theFunction1",
success: function(html){
alert('sucess! Result is:' + html);
}
});
}
</script>
and you can use code such as this to catch the data your javascript is passing in. In this example you would want to call this file name as "submit_data.php" to match the javascript above:
<?php
// Variables
$Username = $_POST['username'];
$Email = $_POST['email'];
$FunctionName = $_POST['functionName'];
//Add code here to choose what function to call and echo the result
// If $FunctionName equals 'theFunction1' then execute theFunction1
// If $FunctionName equals 'theFunction2' then execute theFunction2
echo "You called A Page!";
?>
Here I am doing nothing with the "username" and "email" simply grabbing it and storing them into holding variables. But you can easily add extra functionality here, such as checking for a name of a function that you want to run.
PHP is server side and javascript is client side. So I'm not sure if that is really what you want to be doing??
Perhaps you could explain why you want to specifically call a php function?
I googled PHP function from button and found this question on webdeveloper.com
It doesn't use Javascript.
This is PHP you're talking about, not ASP.NET. In PHP, there is no such thing as a button click event. PHP runs entirely on the server and has absolutely no knowledge of client-side events.
Your first try won't work because the PHP code only runs when the page first loads. It does not run when you call a JavaScript function. Your second example won't work because JavaScript and PHP can't talk directly to eachother like that. Trying to directly call a PHP function from JavaScript just doens't make sense. Remember, PHP only runs on the server. By the time you get to the point where JavaScript can run, the PHP code has long since completed its work.
If you want to do something when a button is clicked, you have to explicitly make a request back to the server. You can do this by just POSTing the form as CTphpnwb suggested. Just be aware that this will reload the page and you will have to manually save and restore the page state, e.g. repopulate input boxes. There is no built-in magic that will do this for you.
Alternatively, you can get all AJAXy and do the POST in JavaScript. However, you will have to write the JavaScript to send the request and process the response, and write the server-side PHP code to handle the request. This gets a little awkward to do in a single page.
From : http://www.dreamincode.net/forums/showtopic72353.htm
You cannot directly invoke a PHP function from Javascript this way :
PHP code is executed on the server
HTML / Javascript are interpreted on the client-side.
One the HTML page has been generated and sent to the client (the browser), there is nothing more PHP can do.
One solution would be to use an Ajax request :
Your onclick event would call a Javascript function
This Javascript function would launch an Ajax request : a request sent to the server
The server would then execute some PHP code
And, then, return the result of that execution to the client
And you'd be able to get that result in your Javascript code, and act depending on what was returned by the server.
There are plenty of solutions to do an Ajax request :
You can re-invent the wheel ; not that complex, I should say -- but see the next point
If already using a Javascript framework, like jQuery, Prototype, ... Those provide classes/methods/functions to do Ajax requests
Googling a bit will get you lots of tutorials/examples, about that ;-)

Categories