How to pass javaScript values to PHP - javascript

How to pass javaScript values to PHP, my code is following
<script>
function a{
var b = a;
}
</script>
<button onclick="a(2)">Values</button>
<?php
$select = mysql_query("select * from tabl1 where id='values'"); // values comes here
echo $select;
?>

There's a lot of thing you could do.
Principal things you have to know is that javaScript run on the client side (browser), while PHP is running on the server.
Then If you want to pass a variable from your JS to your PHP you have to make a server call.
There's various way you can use in order to send variable from client to server.
As I understand from your example, it looks like your php code and your javascript on the same file. so maybe call your file another time will be enough for you.
Let's say your file's name is index.php.
<script>
function yourJavascriptFunction(id) {
window.location.href = "index.php?id=" + id;
}
</script>
Then in change your PHP code to this:
<?php
$select = mysql_query("select * from tabl1 where id='".$_GET['id']."'"); // values comes here
echo $select;
?>
$_GET will get the variable you've sent in your Js function.
Doing like this will refresh the page.
May be you don't want to refresh the page? Then look at the ajax way.
I hope it helps you

Related

Codeigniter insert id model using javascript

How can I get the value of the productid in the php code?
function getunitstock(){
var productid = document.getElementById('product').value
<?php $prodbyid = $this->pos_model->get_productbyid(+productid+)?>
document.getElementById('unitprice').value = <?php echo $prodbyid['price'];?>
}
You can't use javascript variable in php code. Php code run's on the serverside and javascript code runs in the client side. You can't ask the browser to run php code.
<?php $prodbyid = $this->pos_model->get_productbyid(+productid+)?>'
So, this line won't get value of productid.
The only way to do what you are looking to do is either:
do a redirect to a PHP script or do an AJAX call to a PHP script

How to transfer a value on DB to JAVASCRIPT through PHP

<?php
// Connect to database server
mysql_connect("192.168.1.101/phpmyadmin/", "root", "praticas") or die (mysql_error ());
// Select database
mysql_select_db("logs_history") or die(mysql_error());
//---> at this point, I want yo pull a VALUE from a column called potencia_ativa and insert in
// the code JS below
mysql_query($strSQL);
// Close the database connection
mysql_close();
?>
//JS code-------------------------------------------------------------------------------------------
<div id="graphHolder" style="height:75%;width:100%"></div>
<script type="text/javascript">
setInterval(
function() {
var d1 = [];
for (var i = 0; i < parseInt(document.getElementById('number').value,10); i += 0.5) {
d1.push([ //----------> pull the value from the php/DB as a FLOAT
]);
}
$.plot("#graphHolder", [{
label: "Label",
data: d1,
lines: { show: true, fill: true }
}
]);
}, 1000);
</script>
Remember, PHP executes on the server and GENERATES the page that runs the Javascript on the client. Putting a value from PHP into the JS code is as simple as:
<script>
var foo = <?php echo json_encode('bar'); ?>;
</script>
If you need to send the PHP data over AFTER the page was generated and already send to the client, then you need to have the client execute an AJAX request to fetch that data from the server. Once PHP has shoved the page out the door, it's basically done and can't "reach out" to the client to do updates on its own.
Also: Note the use of json_encode(). You should NEVER dump output from PHP directly into a Javascript context without it. Anything else puts you at risk of generating JS syntax errors, which will kill the entire JS code block.
Why are you using Interval? Are you trying to update the displaying page data/value automatically after some time passed? That won't work, because if anything changes in database, It won't change in the displaying page, unless you use AJAX to call your php script and return some values, and then, change in the displaying page.
To get a value from PHP script to JAVASCRIPT, you just need to use the php clausule;
var test = <?php echo $variable; ?>
// echo for strings, ints, floats.
// print_r for arrays.
Of course, if your PHP script already injected the data into the page/the data is in the same page you're using JAVASCRIPT, assuming that you have already fetched the data, handled it and etc.

Assign js variable in PHP variable

function show_selling_price(sp,co)
{
$r=sp;
var e="select * from tbl where id='$r'; ?>";
document.getElementById('selling_price_'+co).value=e;
}
//php assign value does not work why?
//Please correct above code with proper description
You can not set a PHP variable from JavaScript. For example this is not possible:
var js_var = 10;
$php_var = js_var;
However you can set a JS variable from PHP:
var js_var = <?php echo $php_var ?>;
PHP is executed on the server side and then the result shows up on the browser.
JavaScript is executed on the client side once the server returns the response.
If you really need to pass a JS var then use AJAX to submit vars to the server.
It is not possible to assign a javascript variable to a php variable like your example above.
Javascript is a client side language whilst PHP is a server side language.
What you can do is to echo out php variables to a javascript code before it is rendered at the visitors web browser like:
<script>
var text = "<?php echo $variable; ?>";
</script>
If you are setting a variable in Javascript first, and then want to pass it on to PHP, you either have to use ajax, or use a html-form to post the information to the server

Javascript game info to PHP

So after the player loses I want their score to be updated into the database using PHP.
I have a separate javascript class that actually runs the entire game but it uses setInterval to check the index.php function to check if the player lost; if they do they I want it to update the database. The update works but its not taking the score and is just replacing whatever highscore they had with 0.. obviously not what I want. I know people are going to recommend AJAX but my professor only wants PHP and Javascript so I'm getting really confused here... heres the function inside the index.php
<script type="text/javascript">
function checkFinished(){
if(end()){
<?php
if(isset($_SESSION["id"])){
$id = $_SESSION["id"];
$userName = $id["name"];
$update = "UPDATE bloodred SET score='?>score<?php' WHERE name='$userName'";
$update = $dbh->prepare($update);
$update->execute();
}
?>
gameover = false;
}
}
</script>
as you can see im trying to grab the javascript variable score by doing this in the $update variable
score='?>score<?php'
does anyone know any quick short cuts to do this? thanks !
Javascript is client side, and PHP is server side. When you remove the PHP from your javascript, you end up with this:
<script type="text/javascript">
function checkFinished(){
if(end()){
score
gameover = false;
}
}
</script>
If you would like to update the database with the content of a JavaScript variable, you will need to make a new request to the server. This can be a redirect, AJAX, socket, etc. But putting PHP inside of your javascript expecting it to execute like this just doesn't work.
Just a side note, this will work the other way around since PHP is executed first. This does not help your question, but might help clarify why your code isn't working:
This will work:
<script>
alert("<?php echo $variable; ?>");
</script>
After reviewing everything you all said to me I was able to think of a simple solution:
Heres the new javascript:
<script type="text/javascript">
function checkFinished(){
if(end()){
document.getElementById("setScore").value = score;
gameover = false;
}
}
</script>
added a simple form:
<form name="highscore" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<input id="setScore" name="setScore" value="" type="submit" />
</form>
then some php
<?
if(isset($_POST)){
if(isset($_SESSION["id"])){
$id = $_SESSION["id"];
$score = $_POST["setScore"];
$userName = $id["name"];
$update = "UPDATE bloodred SET score='$score' WHERE name='$userName'";
$update = $dbh->prepare($update);
$update->execute();
}
}
?>
Thought id post this in case anyone else needed it. Thanks again guys for your help!
Without using ajax you can create an iframe and post to it using a form on the page with the target attribute.
javascript
function checkFinished(){
if(end()){
var iframe = document.getElementById('updateScore'),
form = document.createElement('form'),
input = document.createElement('input');
if(!iframe){
iframe = document.createElement('iframe');
iframe.name = 'updateScore';
iframe.id = 'updateScore';
}
input.name = 'score';
input.value = getGameScore();
form.action = '/updatescore.php';
form.method = 'post';
form.target = 'updateScore';
form.appendChild(input);
form.submit();
form.remove();
gameover = false;
}
}
updatescore.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SESSION['id']) && isset($_POST['score'])){
$id = $_SESSION["id"];
$score = $dbh->real_escape_string($_POST['score']);
$userName = $id["name"];
$update = "UPDATE bloodred SET score='$score' WHERE name='$userName'";
$update = $dbh->prepare($update);
$update->execute();
}
?>
First of all: AJAX is Javascript.
Second: PHP is a Server-Side language. Javascript a Client-Side. So what you want mixing PHP code with JS code will never work. When JS execute, all PHP code was already evaluated and executed by PHP compiler.
To solve your problem there are some methods,like:
You could use HTML5 WebSocket, but this is kind of AJAX and the user must have a updated, newer, browser and you must implement de server side of PHP socket to listen the user gameover event (too much resources of the server).
You could use AJAX (since AJAX is Javascript), is the fast, easy and recomended.
You could redirect the user, when the game over, to another page (or the same, this is your logic) passing a querystring or a cookie with the new score, doing this the PHP code can take the updated and correct value of score and update the database.
Just remember that all forms listed above are insecure because run in client-side and so, any client (AKA user/player) can change the value of score for whatever he wants.
If you cannot use AJAX (again, AJAX is Javascript), if you cannot use WebSockets (Server limitation or HTML 5 limitation), you could load a PHP through a script tag or a iframe tag (but don't tell anybody that was me who told you do that haha)
<script type="text/javascript">
var score = getCurrentScore(); //a simple method that returns the current user score to be stored in database
function updateScore()
{
var s = document.createElement("script"); // create a tag script via JS
s.scr = "updateScore.php?score=" + score + "&nocache=" + Math.floor((Math.random()*1024)+1); // determine that source of this script is the url of script that updates the score for current user, with the queryString score value. nocache querystring with random value between 1 and 1024 is just to guarantee that the script will be loaded every time and not a cached version of a file will be acessed. For better results add a HTTP header "expire" in the updateScore.php with a small or negative value.
s.type= "text/javascript"; // type of script (make sure that updateScore.php response a content-type text/javascript e a valid or empty javascript code
document.getElementsByTagName("head")[0].appendChild(s); //append the tag script at the end of tag head of the current page
}
// call updateScore() method when user gameover!
</script>
When you call the method updateScore it will produce something like:
<script type="text/javascript" src="updateScore.php?score=1000&nocache=123"></script>
This is similar a AJAX request, or a direct request or direct access to the file. Where score=1000 represents a score with value 1000 and nocache=123 is a random value just to guarantee the fresh load of file. (calling method again, nocache value /probably/ will change to something different than 123...)

Set the value of JavaScript variable into a PHP variable

I want to set the value of a JavaScript variable into a PHP variable. How can that be done?
Kindly give me some suggestions.
My code is :
document.getElementById("dummy").value= <?php echo ("document.getElementById('txtplan').value"); ?> //document.formn.txtplan.options[document.formn.txt'+fld+'.selectedIndex].value //eval(''); $_POST['txtplan']
alert(document.getElementById("dummy").value);
<?php
$planname = $_POST["dummy"];
$plandetails = mysql_query("SELECT * FROM membershipplan where planname='$planname'");
while($row1 = mysql_fetch_array($plandetails))
{?>
document.getElementById("txtduration").value=<?php echo $row1['planduration']; ?>
document.getElementById("txtplancontact").value=<?php echo $row1['plannoofcontacts']; ?>
document.getElementById("txtplanamount").value=<?php echo $row1['planamount']; ?>
<?php
}
?>
});
am not do with this means kindly give me the alternative way for the above process
JS -> PHP = impossible (only if you send that info to PHP using POST or GET)
PHP -> JS = possible var text = <?php echo( $text ); ?> ;
The only reason for that is that the PHP code is executed on your server.
You cant do that i.e you cant assign a javascript variable to a php variable
(unless you are using cookie or ajax) but u can assign a php variable to a javascript variable using
var a=<?php echo $a ?> ;
but be careful with that as the php variables will be executed in the server.
The answer is simple. Impossible. Because,
Java script is a client side scripting. Client machine can handle
this script, If it is possible to assign javascript value to PHP
variable that leads to some sort of vulnerability.
So this can't be done.
If you want to accomplish something by doing this kind of assignment, Definitly there would be a way of doing it. Post another question what do you want to do, you will be showered with answers.

Categories

Resources