How to pass value given by javascript variables to PHP variables? - php

I want the variables like screen width screen height color depth and pixel depth to be used in a PHP function. Basically what I want to do is when user come in my webpage eg:localhost/try.php I want to know all above mentioned details of client without setting cookies or session properties or get parameters. Yeah and of course without reloading the page. I know php but not AJAX so can anyone help me with that?

if i understood it right, your question is When user comes to your page(e.g try.php)how to pass javascript variable(e.g screen.width screen.height) to PHP section so that you can make it as a PHP variable.
Here is a working solution.
try.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="" method="POST" name="myForm" id="myForm">
<input type="hidden" id="screenWidth" name="screenWidth">
<input type="hidden" id="screenHeight" name="screenHeight">
</form>
<script type="text/javascript">
document.getElementById("screenWidth").value = screen.width;
document.getElementById("screenHeight").value = screen.height;
function autoSubmit ()
{
let form = document.getElementById("myForm");
form.submit();
}
window.onload = autoSubmit;
</script>
</body>
</html>
<?php
if($_SERVER["REQUEST_METHOD"] === 'POST')
{
if(!empty($_POST["screenWidth"]))
{
$screenWidth = $_POST["screenWidth"];
echo $screenWidth; // see if it gets the screen.width
}
if(!empty($_POST["screenHeight"]))
{
$screenHeight = $_POST["screenHeight"];
echo $screenHeight; // see if it gets the screen.height
}
}
?>
It basically manipulate the DOM and change the value of input value to be the screen.width and screen.height and then submit the form automatically when the window is onload.
If the the server received an HTTP POST method input then it checks the name of the POST inputs and save it into each PHP variables.

Related

How to send the values of the query variables into php variable for inserting into database? [duplicate]

I want to pass JavaScript variables to PHP using a hidden input in a form.
But I can't get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?
Here is the code:
<script type="text/javascript">
// View what the user has chosen
function func_load3(name) {
var oForm = document.forms["myform"];
var oSelectBox = oForm.select3;
var iChoice = oSelectBox.selectedIndex;
//alert("You have chosen: " + oSelectBox.options[iChoice].text);
//document.write(oSelectBox.options[iChoice].text);
var sa = oSelectBox.options[iChoice].text;
document.getElementById("hidden1").value = sa;
}
</script>
<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<?php
$salarieid = $_POST['hidden1'];
$query = "select * from salarie where salarieid = ".$salarieid;
echo $query;
$result = mysql_query($query);
?>
<table>
Code for displaying the query result.
</table>
You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.
<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>
<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>
<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>
Just save it in a cookie:
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
It's not a pretty solution, but it works.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
Send the information in a form as stated here (will result in a page refresh)
Pass it in Ajax (several posts are on here about that) (without a page refresh)
Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
Here is the Working example: Get javascript variable value on the same page in php.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's how I did it (I needed to insert a local timezone into PHP:
<?php
ob_start();
?>
<script type="text/javascript">
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
<?php
$offset = ob_get_clean();
print_r($offset);
When your page first loads the PHP code first runs and sets the complete layout of your webpage. After the page layout, it sets the JavaScript load up.
Now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't - it needs to refresh the page. The only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP.
So, we use AJAX to get Javascript to interact with PHP without a page reload. AJAX can also be used as an API. One more thing if you have already declared the variable in PHP before the page loads then you can use it with your Javascript example.
<?php $myname= "syed ali";?>
<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>
The above code is correct and it will work, but the code below is totally wrong and it will never work.
<script>
var username = "syed ali";
var <?php $myname;?> = username;
alert(myname);
</script>
Pass value from JavaScript to PHP via AJAX
This is the most secure way to do it, because HTML content can be edited via developer tools and the user can manipulate the data. So, it is better to use AJAX if you want security over that variable. If you are a newbie to AJAX, please learn AJAX it is very simple.
The best and most secure way to pass JavaScript variable into PHP is via AJAX
Simple AJAX example
var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
$.ajax({
type: "POST",
url: "YOUR PHP URL HERE",
data:userdata,
success: function(data){
console.log(data);
}
});
PASS value from JavaScript to PHP via hidden fields
Otherwise, you can create a hidden HTML input inside your form. like
<input type="hidden" id="mydata">
then via jQuery or javaScript pass the value to the hidden field. like
<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>
Now when you submit the form you can get the value in PHP.
I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.
It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.
One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:
<img src="pic.php">
The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.
PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.
If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.
Here's a previous question that you can follow for more information: Ajax Tutorial
Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.
<?php
if(isset($_POST))
{
print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="data" value="1" />
<input type="submit" value="Submit" />
</form>
Clicking submit will submit the page, and print out the submitted data.
We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -
function statusChangeCallback(response) {
console.log('statusChangeCallback');
if (response.status === 'connected') {
// Logged into your app and Facebook.
FB.api('/me?fields=id,first_name,last_name,email', function (result) {
document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
console.log(document.cookie);
});
}
}
And I've accessed it (in any file) using -
<?php
if(isset($_COOKIE['fbdata'])) {
echo "welcome ".$_COOKIE['fbdata'];
}
?>
Your code has a few things wrong with it.
You define a JavaScript function, func_load3(), but do not call it.
Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
Your form has no means to submit it. It needs a submit button.
You do not check whether your form has been submitted.
It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:
<?php
if (isset($_POST['hidden1'])) {
echo "You submitted {$_POST['hidden1']}";
die;
}
echo <<<HTML
<form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
<input type="submit" name="submit" value="Test this mess!" />
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<script type="text/javascript">
document.getElementById("hidden1").value = "This is an example";
</script>
HTML;
?>
You can use JQuery Ajax and POST method:
var obj;
$(document).ready(function(){
$("#button1").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: "addperson.php",
type: "POST",
async: false,
data: {
username: username,
password: password
}
})
.done (function(data, textStatus, jqXHR) {
obj = JSON.parse(data);
})
.fail (function(jqXHR, textStatus, errorThrown) {
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
});
});
});
To take a response back from the php script JSON parse the the respone in .done() method.
Here is the php script you can modify to your needs:
<?php
$username1 = isset($_POST["username"]) ? $_POST["username"] : '';
$password1 = isset($_POST["password"]) ? $_POST["password"] : '';
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";
;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('success' => 1));
} else{
echo json_encode(array('success' => 0));
}
$conn->close();
?>
Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.
May be you could use jquery serialize() method so that everything will be at one go.
var data=$('#myForm').serialize();
//this way you could get the hidden value as well in the server side.
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
Use the + sign to concatenate your javascript variable into your php function call.
<script>
var JSvar = "success";
var JSnewVar = "<?=myphpFunction('" + JSvar + "');?>";
</script>`
Notice the = sign is there twice.

Why is isset($_POST['submit1']) equal to FALSE?

This is a follow-up of another question that I posted a few hours ago (PHP post method apparently not working).
The code still does not do what it should, but the code and also the question itself have changed so much that I prefer to post a new question (also considering that questions seem to be read mainly immediately after they have been posted). I’ll try to close the earlier question (still somewhat new here).
On to the question then: why is, in the code given below, isset($_POST['submit1']) equal to FALSE when tested? In other words, why is $_POST['submit1'] equal to NULL?
I believe that’s all I need to know.
Here is the code, which consists of two files. The file ‘form.php’ (copied almost literally from the jQuery-site: http://www.visualjquery.net/category/Ajax/jQuery.post , see last example) contains the following code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form action="formprocessing.php" name="formpje" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" name="submit1" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="s"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post(url,{s: term},'json');
/* Put the results in a div */
posting.done(function( data ) {
var content1 = $( data ).find( '#content' );
contentstring = JSON.stringify(content1);
$( "#result" ).empty().append( contentstring );
});
});
</script>
</body>
</html>
And the file ‘formprocessing.php’ contains the following (this includes the isset-test):
<!DOCTYPE html>
<?php
if(isset($_POST['submit1'])) {
echo ( json_encode(array("content" => $invoer)) );
}
?>
Thanks!
Because you're only posting data for s; there's no submit1 in your submitted data object.
Because you never set submit1 as part of your data object that you're passing to $.post():
var posting = $.post(url,{s: term},'json');
$.post() does not automatically pass through all of your form values; it only sends what you specify in its second argument. The only thing that will be set in $_POST is the 's' key.
I would suggest to use
if(isset($_POST['s'])) {
echo ( json_encode(array("content" => $invoer)) );
}
The data from your textbox is being sent (name="s"), not your name="submit1" guy. So either include 'submit1' in your post or look for the 's' value
You can use serialize function to serialize the form. So you will get all the element including submit1 from your form.

my "post" form doesn't post

I have a a problem when trying to send data from one page to another via using SESSION.
In page 1 I have a form like:
<form id="myForm" name="myForm" action="" method="post">
<input name="item_1">......</input> // an input for a number
<input name="comment1">......</input> // an input for text
</form>
to avoid refreshing, I use
function submitOnclick()
{
$.post("thisPage.php", $("#myForm").serialize());
redirectToAnotherPage();
}
then I tried to store data via using SESSION
function redirectToAnotherPage(){
<?php $_SESSION['item_1']=$_POST['item_1'] ?>;
<?php $_SESSION['comment1']=$_POST['comment1'] ?>;
location.href='anotherPage.php';
}
but the $POST result is empty, I tried to replace $_POST['item_1'] with a number 1 and it did store the number to item_1, so I assume it is because $_POST['item_1'] has some problems, I don't know why I can't get the form data in one page without submitting / refreshing,
Any help will be appreciated, thanks!
I don't think you can set a PHP session variable like that inside your javascript function. PHP is separate to javascript since PHP is serverside, those values will be read and assigned when the page first pre-processes.
There will be no change, whether the javascript function gets called or not.
Even without AJAX< just a simple PHP form will do. Please see below:
<form id="myForm" name="myForm" action="anotherPage.php" method="post">
<input name="item1">......</input>
<input name="comment1">......</input>
</form>
To submit using javascript, just use something like this on your function:
function submitForm() {
document.myform.submit();
}
the problem is name of your input is not same with your $_POST index
your input: <input name="item1">
your post index: $_POST['item_1']
and also its not right way to use PHP function inside Js, this:
function redirectToAnotherPage(){
<?php $_SESSION['item_1']=$_POST['item_1'] ?>;
<?php $_SESSION['comment1']=$_POST['comment1'] ?>;
location.href='anotherPage.php';
}
you need to set $_SESSION directly in thisPage.php(ajax post url)
EDIT :
dont use serialize(), this way instead:
function submitOnclick()
{
$.post(
"thisPage.php",
{item_1 : $('input[name="item_1"]').val(),
comment1 : $('input[name="comment1"]').val()
}
);
redirectToAnotherPage();
}
good Luck !!!

Pass value of Javascript variable to MySQL through PHP

I want to pass area name selected from drop down menu to query of MySQL through PHP. I retrieved name in JavaScript but I am unable to store value from JavaScript to PHP. My Code is As follows
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<script>
function getIndex()
{
var x=document.getElementById("cmbArea").selectedIndex;
var y=document.getElementById("cmbArea").options
var z= y[x].text;
alert(z);
}
</script>
</head>
<body>
<form name ="form1" action="Demo1.php" method="post">
<select id="cmbArea" name="cmbArea">
<?php
include 'Connect.php';
$query = "SELECT varAreaName FROM tbArea" ;
$result = mysql_query($query);
while($row = mysql_fetch_assoc( $result )) {
echo '<option value="'.$row['varAreaName'].'">' . $row['varAreaName'] . '</option>';
}
?>
</select>
</form>
<input type="Button" onclick="getIndex()" value="Alert index of selected option">
</body>
</html>
You need to post your form. The value will be available in $_POST['cmbArea'].
If I am understanding you correctly I would use AJAX in this case. Something like this: http://openenergymonitor.org/emon/node/107
Yes, you can not 'store' value from javascript to PHP, as javascript is in client-side(literally in your Browser-side), not in the server-side.
You need to post the data using ajax(Jquery ajax may be), and post them in JSON format.
Check this thread..
PHP will run on server and then javascript will be run on the browser. So you cannot do both in the same page, as you try.
I think the best way is to submit the form, and read the value there using PHP. There you can execute your query.
If you don't want to submit you can check AJAX which will send an asynchronous server side request, without refreshing the webpage.

Want to set value to input type text and then post the form to php from javascript

id doesn't want to put the value in to the document.getElementById("UniLoc").value = val; and it doesn't want to submit the form how to fix this ?
This is how I call the function JS nas some value "asd56"
echo "
<script type="text/javascript">
repostD("'.$JS.'");
</script>";
here is my function inside
<script>
function repostD(val)
{
//document.getElementById("UniLoc").value = val;
document.getElementById('UniLoc').innerHTML = val;
//document.UlRL.UniLoc.value = val;
document.forms["UlRL"].submit();
}
</script>
and here is my form in html
<form name="UlRL" id="UlRL" action="in.php" method="post">
<input type="text" id="UniLoc" name="UniLoc" value="<?php echo $UniLoc;?>" />
Use
document.getElementById('UniLoc').value=val;
If there is nothing else wrong with your full form, it should submit. If you haven't closed your form tag, then close it.
</form>
try doint that in php all instead of in function make an if clause down the code that will execute the action of the posting of the form and at the beggining of the php try this
if($JS!="" )
{
$UniLoc=$JS;
$JS="something that will go throught the other if down at the code";
}
else {
$UniLoc=$_POST["UniLoc"];
}
I cant really tell from your question what is wrong, but looking at your code:
document.getElementById('UniLoc').innerHTML=val;
you are trying to set the value of the input with id 'UniLoc', but you are using the wrong syntax. Instead of .innerHTML, use .value
document.getElementById('UniLoc').value=val;

Categories