Using HTML variable in PHP - javascript

I'm trying to use the value stored in token in my PHP script to update a database value with SQLite. It wont let me use document.getElementByID....any ideas?
<div id="TokenCount">
<label for="token"><abbr title="Tokens">Tokens</abbr></label>
<input id="token" value="0" />
</div>
<div id="Buttons">
<button id="pay" onClick="pay(10); loadMessage()"><?php $db=sqlite_open("../../logins.db");
$token = document.getElementById('token').value;
sqlite_query($db,"UPDATE Users SET tokens='$token' WHERE user_id='{$_SESSION['user_id']}'");
sqlite_close($db); ?>Pay</button>
</div>
</div>

PHP code is executed server-side, so the website is sent to the client with the result of the PHP code without any PHP found in the source. Because of this HTML tags cannot be used in PHP on a website.

As i said in comments, you can't execute PHP-code(server side code) on client side (in browser).
You should send AJAX query to server, and save this value to mysql on server side.
Javascript(jquery) code:
function loadMessage(){
$.post("setValue.php", {val:document.getElementById('token').value} function( data ) {
alert('success');
});
}
Create new php script for example setValue.php (r use contoller action, or your own staff how you routing pages). Script code:
$token = $_POST['val'];
sqlite_query($db,"UPDATE Users SET tokens='$token' WHERE user_id='{$_SESSION['user_id']}'");
sqlite_close($db);

Related

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

PHP code runs automatically in Javascript when not needed [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 years ago.
Inside a PHP/HTML page i'm trying to start a session in php and then set a value to a session variable, and i'm trying that inside a Javascript function, and in this function there is a if statement, but the php code inside the if statement runs automatically when i go to the page immediately, when i want the code to run only when the user accept the terms...
Here is my code :
HTML :
<label>
<input type="checkbox" name="terms" id="terms-checkbox">
<font color="#090909" size="+1">I agree to the Terms and Conditions.</font>
</label>
Javascript :
if(document.getElementById("terms-checkbox").checked){
<?php session_start(); $_SESSION["ITA"] = "Yes"; ?>
window.open('DL.php?App=STOPit');
}
So when i open the php page that contains that previous Javascript code, the $_SESSION["ITA"] variable will be equals to "Yes" even that the condition is not met yet.
Hope someone can help me with that.
That's not how PHP and Javascript work.
PHP runs on the server before anything else. JS runs on the client side.
Without further information:
I suppose your JS code is not a file, but a inline script on the same HTML/PHP page. When your user requests the HTML page, PHP parses it, including the tags inside your JS code.
If you want PHP to do something based on a user action on the browser (document.getElementById) you have to take other routes. Maybe using Ajax, for example -- so your PHP code can do something.
For your better understanding php runs on the server side and javascript runs on the client side.
What you are trying to do is possible if you submit the data using a form or you have to make an ajax call using javascript.
Below is one way of doing something similar.
<?php
session_start();
if(isset($_POST['terms'])) {
$_SESSION["ITA"] = "Yes";
header('Location: DL.php?App=STOPit');
}
?>
<form action="<?php $_SERVER["PHP_SELF"] ?>" method="post">
<label>
<input type="checkbox" name="terms" id="terms-checkbox">
<font color="#090909" size="+1">I agree to the Terms and Conditions.</font>
<input type="submit" value="Submit">
</label>
</form>
Always start your PHP session_start() on the top of your PHP script file.
<?php
session_start();
?>
Here you can continue with your HTML/CSS/JavaScript codes
but the above is mandatory in order to start a session within
your PHP project.
Otherwise you'll be sending header information after the output buffering happend, and you'll end up with an error like this:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
When you have properly initialized a session handler as I described, you can use or do:
$_SESSION['item-name'] = 'value'; // to set a value of a specific session item
echo $_SESSION['item-name']; // retrieve it's value and output it
unset($_SESSION['item-name']); // to delete it from the $_SESSION container

How can I save the entire form from the client by a servlet?

I create a form with some inputs and other information on a client by JSP,then i want to send the form to the server while a servlet runs on the server. My question is how to save the entire form which I post inside a html file, the html file will be created once I get the request.
<form name="myform" action="servlet on server" method="post">
<input type="button" id="sth" />
....
</form>
I want to use the File class to create the new html file, but how can I get the entire form and write it in the new file?Thanks.
I guess you could do some javascript to send a post request with a field containting the inside html of your document of your browser.
<script type="text/javascript">
myform.sth = document.innerHTML;
myform.submit();
</script>
I cannot give you the exact syntax, but that's the idea.
BUT it surely is a weird design you are building

get data from mysql database to use in javascript

I have a javascript that dynamically builds an html page. In the html page there are textarea boxes for the user to type information in. The information already exists in a database. I would like to populate the textarea boxes with the database in the mysql database.
I have php code that will connect to the database and build an html table with the data, so I know how to do this with php, but I don't know how to do this from the javascrip. I've studied ajax get requests, etc., but I'm still not sure of how to do this.
Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php,
$result = mysql_query("SELECT field_name, field_value
FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />. You can reference that field with this jQuery: $("#field1").val().
Here's a complete example with the HTML. If we're assuming your fields are called field1 and field2, then
<!DOCTYPE html>
<html>
<head>
<title>That's about it</title>
</head>
<body>
<form>
<input type="text" id="field1" />
<input type="text" id="field2" />
</form>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$.getJSON('data.php', function(data) {
$.each(data, function(fieldName, fieldValue) {
$("#" + fieldName).val(fieldValue);
});
});
</script>
</html>
That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value attribute.
To do with javascript you could do something like this:
<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>
Then you can use whatever you want in your javascript to put the text var into the textbox.
Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?
Send AJAX request to php script
PHP script processes request and builds table
PHP script sends response back to JS in form of encoded HTML
JS takes response and inserts it into the DOM
You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.

to send a text file to server using javascript

I need to send a text file to server and get it saved. how can i do it using javascript???
There are all sorts of security issues surrounding this. Would you be happy to visit a website that would upload a file from your machine to the server?
For a generic website, where users are likely to have their permissions set to deny this sort of access it isn't possible.
If by chance, you are looking to do this for an application where you have control over the security settings for its users, and that you can guarantee its Windows and IE, then it is possible by reading the file and passing the details by posting to the server. See the following link : http://www.javascripter.net/faq/reading2.htm
However when you move away from IE or Windows, then you are going to struggle.
using ajax of course.
have a file on the server, PHP or ASP - depending on what your internet server is.
this file will accept the text file (data and name), and should also check for size and if this file already exists or not, and if all is ok- it will save it, and return a string "OK"
on the client, javascript side, just send the information to the server using ajax, or HTTPREQUST object - there's plentty of documentation for that around. and if you get back a response of "OK" then you know that it sent well.
even better: don't use HTTPREQUEST, but do dynmaic script tag insertion - where the source attribute of the script you're appending is that file on the server like:
var a = document.createElement('script');
a.type = 'text/javascript';
a.src = "http://server/serverFile.PHP?filename=XXX&data=LONG STRING OF DATA REPRESTING THE DATA TO BE SAVED PROBABLY LESS THAN 2K IN SIZE AND ALSO YOU SHOULD ESCAPE OR ATLEAST URIENCODE IT";
document.body.appendChild(a);
and on the server file, serverFILE.PHP:
<?php
// some code to save the request variable [data].
// if all is ok:
alert("ok")
// or:
result = "ok"
?>
get it?
note: you'll probably have a limit of less than 2K on the file size.
Javascript is a front-end language. You may use php or any server side language.
You can create an Ajax equiv function make an iframe with width and height=0px then make it the target of the form with the file upload input and process it with the action PHP
<form action="upload.php" target="target" method="post"
name="uploadform" id="uploadform" enctype="multipart/form-data">
<label for="input_file_upload">Upload:</label>
<input onchange="document.uploadform.submit();" size="80"
type="file" name="file_upload[]" id="file_upload"
multiple="multiple" />
<input type="hidden" name="fileUpload" value="upload" />
<input type="button" value="Upload" />
</form>
<iframe id="target" name="target" style="width: 0px; height: 0px;">
</iframe>

Categories