Pass Javascript variable to another page via PHP Post - javascript

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!

Related

using ajax to pass string from php to javascript

So I have a piece of javascript code in an html document that responds to a button click. I want a new url to open, and if I specify the link in javascript as I've done below, everything works fine.
<input type="submit" id="submitbtn" value="Purchase Module"/>
<script type="text/javascript">
document.getElementById("submitbtn").addEventListener("click",handle_click);
function handle_click() {
var link;
link="http://www.google.com";
window.location.href=link;
}
</script>
Problem is I want to hide the real link on the server side as it includes a username:password. The php script below calls a function (not shown) that generates the link (a string). This also works fine.
<?php
$link=get_page_link();
?>
I want to pass the link string to the javascript and have tried various iterations of
link=<?php echo $link ;?> to no avail. As I understand it you can't pass strings this way and you need to use ajax. That's where I'm stuck. Seems like I need a $_POST on the php side and a $_GET on the java side, but not sure on the specifics. Any help would be appreciated. Thanks.

Getting values from html form as JavaScript variables

i want to capture input variables sent via form from one page to another.html page and obtain these values as JavaScript variables. Can this be done.
This is my form;
<form action='another.html' id='form' data-ajax='false'>
<input id='sent_by' value='tom'/>
<input type='submit' value='Submit'/>
</form>
And in my another.html i tried to get the values as;
var sent_by = $.session.get("sent_by");
But i am not able to get the values. All help is appreciated.
You can use the browser's localStorage to achieve this. Before submitting and going to the other page store all the values of the form in the localStorage and you can access it on the other page:
Page1.html
Field Name = "name" <input type="text" name="name" id="name" />
Read the value and store it to localStorage
localStorage.setItem('name', document.getElementById('name').value);
and so on.
You can make a function in JavaScript that saves all the fields of the form in localStorage on / before submit.
To read these values on the other page:
Page2.html
Value stored for key name can be get using the following JavaScript:
localStorage.getItem("name");
NOTE
the page1.html and page2.html should be in the same domain for you to access the localStorage.
Read more about localstorage at https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
Have you tried using Window.localStorage? It's similar to sessionStorage but with no expiration date. So, be sure to clear it once the browsing session ends.
I think the answer provided by #Shakti Phartiyal is probably the most practical and a sweet trick I might add. The main reason I'm writing this post is because I had also taken a long path of using javascript to pass along this kind of information. It resulted in me bewildered at how powerful PHP can be for some tasks that you dedicated javascript to do. (Yea I know some javascript wizards out there can do everything with it, I'm just talking about basic programming tho). So if you wondered what the PHP way of passing this around:
Your modified html form:
<form action='another.html' id='form' data-ajax='false' method='post'>
<input id='sent_by' value='tom' name='uname'/>
<input type='submit' value='Submit'/>
</form>
and then in "another.php" you would have this to retrieve the input from the form:
<?php
$uname= htmlspecialchars($_POST['uname'];
?>
Great. But how to make this php variable into javascript?
Ah, the fun part. You're going to write javascript to your webpage with php - you do something like this:
var uname = "<?php echo $uname; ?>";

How to get information from Javascript to MySQL database using PHP?

(NEWBIE ALERT)
Hello! I am working on developing a database that stores information that people enter onto these online surveys. I don't have experience with Javascript, but I have worked with PHP and MySQL before. I am currently stuck on how to store the data to the database. Here are a few things about the code:
The person that created the online surveys had the online surveys written in Javascript (saved as HTML files)
Each survey is written in a separate file
Each survey has multiple data to be stored
Every time the user hits the next button, it goes to another page of the survey
I've worked on a project similar to this before, but my forms were only a page, so whenever the user clicks the "Submit" button, I had it go to another webpage written in a separate PHP file (kind of like a "results" page).
WHAT I DON'T UNDERSTAND/NEED HELP ON:
How do I make this so that when the user hits the "Next" button, it not only goes to the next page (what it's doing right now), but also sends the info to be stored in the database?
These surveys should be filled by people on their own computers so the surveys are written in JS (client-side). The storing part should be written in PHP (server-side) and MySQL, correct? Does this mean that I have to create a separate PHP file to create the code for transferring the data to the database or can it all be done in the same file? (I would think that I would need to create a separate file, one for each survey.)
Here's a general structure of how the HTML file:
<!DOCTYPE html>
<html>
<head><link rel="stylesheet" type="text/css" href="survey.css">
<script>
function Q2(){
document.getElementById("Q").innerHTML = "does something...<button type='button' onclick='Q3()'>Next</button>";
function Q3(){
document.getElementById("Q").innerHTML = "does something...<button type='button' onclick='Q4()'>Next</button>";
function Q4(){
document.getElementById("Q").innerHTML = "does something...<button type='button' onclick='Q5()'>Next</button>";
//keeps going until the last question
</script>
</head>
<body>
<h1>Meeting 1</h1>
<p id="Q">Some text...<br><input type="text" name="tweet" style='height: 50px;width: 500px;'><br><br>
<button type="button" onclick="Q2()">Next</button>
</p>
</body>
</html>
I've done a bit of research and looked at a few textbooks. I think AJAX may be something that I need to use? But I'm not too sure. If possible, could someone explain to me what I should be doing? I would like to not only be able to find a solution for this, but understand it as well.
Thank you in advance!!
For sending data to a PHP page using JavaScript, I'd recommend using the jQuery framework, where you can do it in as simple a code as this:
function Q2(){
var tweet = $("input[name='tweet']").val();
$.post("your_receiving_page.php", { data : tweet }, function(response){ //POST to PHP page where $_POST["data"] is the tweet variable
//deal with PHP output here
console.log(response);
if(response=="success"){
//javascript code to go to next page etc.
}
}
}
That way, you make a PHP file called "your_receiving_page.php" (or whatever) and handle the posted data like so:
<?php
$tweet = $_POST["data"];
//do stuff with $tweet, e.g. put it in a database
//...
//then end the code with "success", which is what you're looking for in the JavaScript as a successful callback
exit("success");

target in php when i click on the submit button i want to go to two different URL

I am facing problem in a project: When I press submit, I want to go to two different urls: one from blank and one direct here.
How can I resolve this problem?
My code:
<form method="post" action="" name="form" target="_blank">
function addAmount($invoice_number,$particular,$quantity,$rate,$percentile,$amount){
$addAmm=$this->conn->prepare("insert into `amount`(invoice_number,particular,quantity,rate,tax,amount)values(?,?,?,?,?,?);");
$addAmm->bind_param("isssss",$invoice_number,$particular,$quantity,$rate,$percentile,$amount);
$addAmm->execute();
header('loaction:add_info_success.php');
//header('loaction:printpdf.php'); error face
}
I want to print pdf and swith current page to iformation page.
In PHP, you can't set two different Location headers (you have a typo in your code by the way). If you need to achieve something similar to what you want, you have to handle form by JavaScript and open two different windows with window.open (manual).
it is possible to open multiple URL's if you combine PHP with js. But i am not sure if it's a good way to implement it. It can lead to confusion at the user. My suggestion is to add a direct download link at the success page. But if you want to go this way, you can use the next in PHP.
<?php
$urls = 'window.open("add_info_success.php");window.open("printpdf.php");';
?>
<script language="javascript" type="text/javascript">
function openURLs() {
<?php echo $urls; ?>
}
window.onload = openURLs;
</script>
If you have more URLs, you can simply use a loop and add each url's in the windows.open() method.
Use
header('location:printpdf.php');
inside 'add_info_success.php'

How to clear a server-side html file's content, from input type button

I'm new to PHP. I want to use a (HTML) input type = button to make the content of a HTML empty.
I searched the web, if I use fopen(file.html,w+), it will clear the files content:
"w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist)".
Source: http://www.w3schools.com/php/func_filesystem_fopen.asp
My problem is that there is probably a bit of code missing or syntax mistakes, because when I press the button nothing happens.
I really don't know and couldn't find anything on the world wide web, it's probably really simple. Sorry in advance if I wrote the question wrong.
HTML code
<input type="button" name="clearlog" id="clearlog" value="Clearlog" class="btn btn-default">
PHP code:
<?php
// clear log
if(isset($_POST['clearlog']))
{
function cleartlog()
{
$fp = fopen("log.html", 'w+');
fwrite($fp, "");
fclose($fp);
}
}
?>
The PHP code is in an external file, but is required it in my index.php.
PS: is it better to use the ftruncate function?
Source: http://www.w3schools.com/php/func_filesystem_ftruncate.asp
What you're trying to do here is far beyond the scope of your current understanding. You don't have anything associating that button to any code. Either the button needs to be part of a form that submits to a php file, or you need a javascript click event listener added to it which will then send an ajax request to the server (php) to call your php code.
Form submission directly to a php file (requires a page load) is a mostly outdated practice. Using Ajax is preferred.
The logic is simple:
Attach a javascript click event listener to the button.
The click function will send an ajax request to a page where your php code to run.
jQuery is not necessary, but with jQuery, the ajax call could be as simple as $.get('foo.php). and then whatever php code on foo.php will be executed.
You should use a form which will connect to the server and the PHP should clear the log.html file.
<form action="wipeFileContents.php">
<input type="submit" value="Clear Log File">
</form>
It will be the simplest solution, although you can go the harder AJAX way which is theoretically faster, but requires you to learn javascript.
you could try the following:
HTML
<form action='myfile.php'>
<input type="submit" value="clear">
</form>
PHP
if(isset($_POST['clear']))
{
file_put_contents("log.html", "");
}

Categories