I have 2 pages where the user gives data that needs to be stored (the 1st is a string from the first page and the rest comes from a form from the second page). This webpage is not on a server, its on a laptop without any connection to the internet. The plan is for all that data to be written on to a text document.
My question is; can I send the first variable to a JavaScript like var = get.element... and then redirect the user to the second page where more variables get sent to the same JavaScript without the first disappearing. Because from what I have understood, all the scripts and variables "reset" when reloaded.
Extra, this is how I plan to write the info in a text file, does it look good or is there a better way to store data locally?
<?php
function createFile(){
$file = 'D:\test.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
}
?>
Thanks for all your time!
I would think to pass some parameters from the first page using GET or POST request to the second page.
For example:
//yourApp/second_page.php?name=John Smith
is requested from the first page so you can get the data in the second page using $_GET['fname']
The solution #shadow proposed (using html5 local storage api) seems more clean and simple tho.
Related
Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>
I have a website structured like so :
"Client side" : HTML / CSS / Javascript
"Server side" : PHP
Client side, when a user pushes a button, he's redirected to a page (bold because the click action does not trigger a php script, the redirection itself does with window.open("https://...../, '_self');) that toggles a series of scripts back and forth to get, check, and validate data from various other websites and storing some of them in my DB.
Once this is all done, at the end of my last PHP script i need to redirect my user to the original webpage with a bunch of divs and spans and whatsnot updated with the data retrieved.
Typically at the end i'd have this
header( "Location: $originalURL" );
How should i redirect my user while sending back data to the original webpage all the data i need to update my html elements ?
Through a POST request ?
By doing something similar to this :
header( "Location: $originalURL/?data1:$data1&data2:$data2" ); ?
which i would really much avoid not only for its uglyness or unaesthetical aspect, but most of all for the process to be entirely transparant from the user point of view.
EDIT (to explain the 'flow') :
mywebsite.com/mypage/index.**html**
js click function (window.open(mywebsite.come/mypage/processes/index.php))
series of back and forths between external URLs to get data
last call back to my domain mywebsite.com/mypage/stepX/index.**php**
redirection to mywebsite.com/mypage/index.**html**
mywebsite.com/mypage/index.**html** gets the data from step 5 and updates html elements via its script.js
And i'm stuck at step6.
How does my script.js get all the new data directly with the redirection from my server-side PHP script ?
You shouldn't use header(location:) here because it is only a way to force browsers to brutally get to a page.
You need to use require_once() function which is meant to include a PHP file into another. In that way, you would transform your HTML page into a PHP file and you'll be able to access to variables from the file you required.
Passing an HTML file into PHP file is pretty straightforward, it will allow you to transform your PHP variables into JS variables.
I am trying to figure out the best way to pass data across two pages (Page A to Page B) using PHP for a (somewhat )specific scenario:
Page A: A gallery of images with titles. To create this page, a database call is made in a PHP file to an images table that holds and image id, and image location, and an image title. It gets all of the images that exist in the table and echoes them all out to the screen with a for loop. It creates an href on each image's anchor tag that points to page B.
Page B: A larger view of the image. When a user clicks on an image on Page A, it brings them to a new page with a larger view of the image.
To achieve this, I am currently putting an href on each anchor containing the images in Page A with a parameter containing the image id. Then, on Page B, I make another database call using the id that was passed in to again get the image title, location, etc.
This seems wrong to me to make a second database call when I have already retrieved all of the needed data once on the previous page. In my mind, there are only three decent options which all seem bad to me:
Multiple databse queries - as explained above. Seems inefficient.
GET - Instead of just including the image id in the href on Page A, include ALL of the needed parameters in the href. Note that I actually have more than just three parameters, and there may be upwards of 15 values that need to be passed. It seems wrong to have a url this enormous and to be passing things like image location in the url.
POST - Have a form on the page for each image with a method of POST. Put a hidden field in the form for each parameter that needs to be passed form Page A to Page B. Again this seems like a really bad idea to me to have tons of unnecessary markup and will get very messy.
Does anyone have any input on any of these methods, or a better idea? As I develop more, I find myself questioning efficiency and how it doesn't make sense to me to make so many database calls that do the same thing over and over. I want to be able to make one database call for one image once and then never have to do it again for that session.
(Note that JavaScript / jQuery is an option for me)
Thanks!
It's the reality of web that you need to make a HTTP request every time to fetch some data from server. If you reloads a page browser will again make a HTTP request to get that data again. HTML5 have lot of solutions to the above problem...
Web Storage - Store Values as key-value pair on client side
Web SQL Database - Same as SQL
IndexedDB - Somewhere Between Web Storage and Web SQL Database
You need to create a base64 string out of your image & store that string in Web Storage or WebSQL database. You can write code for image to base64 in javascript file & then use HTML5 APIs to store the string in database.
Have a look at this page -- http://www.html5rocks.com/en/features/storage
I would just do what you are doing but using a function for it. The function would have
SELECT * FROM table WHERE id = $imageid
Passing the ID of the image you want and if there is no value in $imageid then show all. That way on page A you can use this to get the images and then just by using POST or GET with the ID you run the same function to get the results for the ID.
I would say that's not very messy to do it that way but again, that's just how I would do it.
Overall doing something like this:
function getImage ($imageid) {
if($imageid == ""){
$result = mysqli_query($con,"SELECT * FROM table");
return $result;
} else {
$result = mysqli_query($con,"SELECT * FROM table WHERE id = $imageid");
return $result;
}
}
With jquery, you won't have to go to the next page. you can simply do the below:
$('div#largeImageDisplay').hide(); // Div to display large image on. You can style however you want
$("a.linkClass").on("click", function(e) {
sImagePath = $(this).children("img").attr("src"); // use replace function to change path to the one you want
sImageTitle = $(this).attr("title");
$('div#largeImageDisplay').empty();
$('div#largeImageDisplay').html("<h3>"+sImageTitle+"</h3><img src='"+sImagePath+"'/>");
e.preventDefault();
});
I am creating a simple website using HTML and JavaScript in dreamweaver. On my home page, I want to show an alert (whenever my home page loads), which says that "Hello, you are visitor no. 12. Welcome to my site!". I want this visitor number to change on every page load of home.html.
I basically want the visitor no. to be stored in a cookie and increase the no. by 1 in the cookie every time the page refreshes.
How can I create such an alert? Please help. Thanks.
Also, I want to know if I add this functionality, would it be an example of dynamic content on a web page or do you HAVE to create database connections and all in order to create dynamic content. Wouldn't this idea of creating cookie also an example of dynamic content?
Edit-1
I want that only. How many times page was visited. I am a beginner and want it all simple. I just want to know how I can store the no. of visits in a cookie and then retrieve that value from that cookie and show it in an alert on page load. Thanks.
If you want to store the number of visitors, you'll need to use a backend scripting framework (PHP, Ruby, Rails, Python, etc) to store the number of visits your page has received in a database. The javascript of displaying the actual number is simple, with alert('message');
If you just want the number of times that specific user has visited, based on their local information, here's a simple solution:
if (localStorage.numVisits)
numVisits = localStorage.numVisits;
else
numVisits = 0;
alert("Welcome, you have visited " + numVisits + " times before.");
localStorage.numVisits++;
To make it really simple for you (without using the database) you can store the number in a .txt file in the server, and use a simple scripting language like PHP to send it in a hidden field to the client. Every time the PHP page runs, it will have to get the current number and increment it. Something like this:
$myFile = "counter.txt";
$fh = fopen($myFile, 'r');
$count = fgets($fh);
$count++;
fclose($fh);
$fh = fopen($myFile, 'w');
fwrite($fh, $count); // write the incremented counter
fclose($fh);
echo "<input type='hidden' id='counter' value='$count'>";
Then, you would have to get this counter value from the javascript (client side) and alert to the user.
var visitCount = document.getElementById('counter');
alert("Hello, you are visitor no. "+visitCount+". Welcome to my site!");
A Cookie is always Client-sided! You can't do it that way. The easiest way to accomplish what you are looking for is to write a simple php counter which reads a number from a file - adds one and writes it back as soon as your page is viewed.
Check google for examples on "counters".
There actually is no way to count clientsided ALL the visitors you have or had - the client can't know that your server was visited x times ;)
for that you need to create the table and every time when session is start u need to increase +1 in there table and alert the visitor no.
table like
id : no
-------
1 : 3
2 : 5
and massage like
echo "
<script type=\"text/javascript\">
alert(\"Hello, you are visitor no. {$row["no"]}. Welcome to my site!\");
</script>
";
You cannot keep a global page view count in a cookie. A cookie is stored in one user's browser and is local only to that browser. All a cookie could show would the page views that occurred in that one single browser.
Page view counts across all viewers must be done at the server level and then the information put into the page when the page is requested. There are some free ways to put page view counts into the page using the free service level of services like StatCounter.
Or, you'd have to implement a counter in your own server that was serving the page (with the count probably stored in a persistent database) and then insert the current count into the page each time it is requested. For just page count information, it's probably easiest to just go with a service like Statcounter.
Cookies are not persistent across different visitors. To give every visitor a visitor number, you need something stored on a server. If you cannot access server-side functions, use a visitor counter - https://www.google.com/#hl=en&q=visitor+counter
Client goes to example.com/form.html where a html POST form is displayed
Client fills the form with specific information and submit it to example.com/form.html
When example.com/form.html receives the POST request redirects the Client on example.com/redirected.html
Is possible to retrieve the variables that the client filled and POSTed to example.com/form using javascript ? The javaScript being deployed on example.com/redirected.html only . I presume that can be some "back" controls iframes and ajax involved but I couldn't find a reliable solution yet.
The operation will take place on the same domain so no cross domain issue is involved
Nope, I don't think this is possible.
You have to either
Store the posted value in a cookie
Store the posted value in a session variable on server side
Add the posted value as a GET parameter to the new URL
Use GET to post the original form, and painfully extract the posted value from document.referer on the new page
With HTML5, use localstorage. (The answer describes how to store object in localstorage- you could store an object of your form fields in there).
But you have to store the data on posting with js at example.com/form.html and then can get it on example.com/redirected.html. Without js at form.html, this is not possible with this method.
This works if you plan to use html5 and do not store too much data in it, iirc it has a limit of 5-10mb depending on the browser.
I don't think there is a way to do this by using plain html. With some server-side language (like PHP) it can be done with no problem.
I have been in a similar situation before, and the way I managed to give the data to JS is by including the data in a tag while preparing the output using PHP.
Assuming the redirected to php script receives the POST data from the script it's being redirected in. I would include this in the php code:
<?php
echo '<script type="text/javascript">';
echo 'var postData = '.json_encode($_POST).';';
echo '</script>'
?>
This will have the javascript know what the POST values contained.
To access the values from js:
//assuming you need the value for $_POST['foo']
var foo = postData.foo;
// or if json is encoded as just an associative array
var foo = postData['foo'];
If the POST data is not being passed to the redirected to script (haven't checked if this happens automatically), you could write the $_POST data in a $_SESSION variable, in the first php script:
<?php
$_SESSION['postdata']=$_POST;
?>
and then get it back from SESSION from the redirected to script.
<?php
$postdata = $_SESSION['postdata']; //use this to create the inline script in the html
unset($_SESSION['postdata']; //empty this from the SESSION variables
?>