PHP / JavaScript: How to pass variable from one page to another - javascript

I am new to PHP and hope someone can help me with this.
I have a page (index.php) where users can select a language.
If no language is selected than the page URL is just index.php which defaults to English.
If they select a language than the page gets reload and the variable ?lang=xy is added to the URL which defines the page language.
E.g. for German the page URL would then be index.php?lang=de .
So far everything works as intended.
Now I have a navbar on the index page that allows to navigate to other pages which are all saved as separate php files (like page1.php, page2.php, page3.php etc.).
How can I manage that if someone has selected a language on the index page and then navigates to another page that the language variable is passed along to all other pages ?
E.g. for German the other pages shoud be page1.php?lang=de, page2.php?lang=de, page3.php?lang=de etc.
I know I can use $_GET["lang"] on each page to fetch the variable but couldn't find a way to pass this on from the index page to other pages using PHP or JavaScript/jQuery, ideally in a way that I can set this more general instead of separately for every single link.
Note:
I am using undordered lists with standard links to create my navbar, e.g.:
<li>Page1</li>
Can someone help me with this ?
Many thanks in advance.

You can use cookies to do so
setcookie(name, value, expire, path, domain, secure, httponly);
i.e.:
setcookie('language', 'german', 60000,"/");
and then check this wherever with
$_COOKIE["language"]
http://php.net/manual/en/features.cookies.php reference

you can use sessions to pass variables to any page,it's more secure than cookies as it's a server side,
example:
After Posting Data:
<?php
session_start();
if(isset($_POST)){
$var_name=$this->db->real_escape_string($_POST['input_name']);
$_SESSION['var1_sess']=true;
$_SESSION['var1_sess']=$var_name;
}
?>
note:session_start() must be in the first line of the file.

If you are using to select languages, just add onchange event to then submit the form to index.php
<form action="index.php">
<select name="lang" onchange="javascript:this.form.submit()">
<option value="en">English</option>
<option value="xy">XY</option>
</select>
</form>
and in the same page
<?php
$lang = $_GET['lang'];
if(empty($lang)){
$lang = "en";
}
?>
Then pass the $lang to where you want to
<li>Page1</li>

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.

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!

Is it bad practice to pass php variables into values of html input tags?

The thought of making yet another get request and yet another php file is annoying to me... so I've been using this method:
<input class='hidden' id='dataIwant' value=' <?php echo $_SESSION["bigObjectArray"] ?>" />
Is this bad practice? What do you think?
IMHO, session variables might be dangerous to display in the client side. Only part of them such as indexes, strings which the user already knows should be shown to the user. If the session variable contains something like user password, session token etc., it should be hidden.
About your question, it changes when where you want to use this data. If it's only for passing it inside the form to another PHP page, you don't need to do this, as it will still be available in the form processing page.
If you want to use it inside the javascript code in the client side, you can json_encode it and assign it to a javascript variable.
<script type="text/javascript">
var myBigJSON = <?php echo json_encode($_SESSION["bigObjectArray"]);?>;
var myBigArray = $.parseJSON(myBigJSON);
</script>
I think this example speaks for itself:
<?php
session_start();
$_SESSION['bigObjectArray'] = "\" /><script>alert('Hi!')</script><input type=\"hidden";
?>
<input class="hidden" id="dataIwant" value="<?php echo $_SESSION["bigObjectArray"] ?>" />
output:
<input class="hidden" id="dataIwant" value="" /><script>alert('Hi!')</script><input type="hidden" />
Make sure to validate and filter the data you are echoing. Be paranoid, always.
It's a bad pratice if you do not escape it (htmlentities or htmlspecialchars).
It's a bad practice if user have no reason to change this field.
It's a bad practice for multi-tab browsing, since it's SESSION stored (concurrent pages writing/reading that value will fail).
It's a good practice if you html escape the value, if the user can change that field (and if you check it on the treatment page) and if it avoids storing that value in SESSION.

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'

Simplest way for image upload function , without refreshing page

Here's a challenge:
I don't care about which language to use, Javascript, PHP, .. whatever.
I need the most simple way to let my user upload an image.
I will later offer the user a way to place it on a canvas (displayed inside a div, with jquery draggable)
I can not have the page refreshed since there are useful variables in other fields etc..
(I don't have any security preferences as this will be a local website for intranet)
I tried:
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
</br>
<input type="file" name="file" id="file" size="70%"><br>
</br>
<input type="submit" name="submit" value="Submit">
</form>
But then came to realise there are soo many options out there, such as uploadify, and i easily got lost online..
You have two choices to make a file upload w/o refreshing the page:
Use HTML5 form upload
Post the form to an hidden iframe
The latter one gives best browser compatibility, and is what I'd suggest you to use. To post to an hidden iframe, simply set the target of the form to the iframe:
<script>
// Global callback function from the file
function uploadCallback(){
console.log("File is uploaded!");
}
</script>
<iframe name="hiddentarget" style="display:none;"></iframe>
<form action="upload_file.php" method="post" enctype="multipart/form-data" target="hiddentarget">
...
To respond back to the site from the iframe, you will have to go through the window.top frame as such:
upload_file.php:
<?php
// Uploading stuff
// ...
// "Talk" back to the site
// Of course you can (should) pass some parameter to this JS-function, like the filename of the recently uploaded image.
echo "<script>window.top.uploadCallback();</script>";
?>
EDIT:
As suggested by other users; the optimal solution would be to use the File API where supported, and fall back to the hidden iframe on browser that doesn't support it. This gives you nice features such as file uploda progress for example.
The way that I would suggest is using AJAX and and make your upload box a div which can be replaced when the upload is successful. Instead of traditional post you then create a Javascript function for onSubmit. Your action can then be changed to #.
If you lookup AJAX there are some great tutorials about and you will be able to do many more amazing things.
Alternatively look into jQuery which will definitely have something to help you
I'm gonna show you an example on how to use the jQuery Form Plugin to upload files to your server really easy without needing to refresh the page.
First off, download and install the jQuery Form Plugin. After you do that, include it in your files where you want to make use of it. Add an ID attribute to your form tag like this:
id="unique_id"
After you have identified the upload form, put this code in your jQuery:
$(function() {
$('#unique_id').ajaxForm({
target: '.myTarget' // Display here whatever the server side script returns
success: function(response) {
// An usual success callback
}
})
})
Assuming that your server side language is PHP, this is how a simple upload script would look like (upload_file.php):
<?php
$uploaddir = 'your_upload_dir/something';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']); // Filename
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo $uploadfile;
} else {
echo "Error";
}
?>
Where userfile is the name attribute of your file input (<input type="file" />).
The above code combined returns the relative path to your image which you can use to display the image inside an img tag. You must use Javascript (or jQuery) for that.

Categories