Here is a scenario : “A shopping website will have the cart. User goes on adding items to his cart. Finally when shopping completed, the list of all the items added to the cart should be shown”.
Solution : Use LocalStorage for storing the product ID’s and then use AJAX to retrieve the products from the server. To retrieve the product details, you need to pass the items product ID’s from the LocalStorage to server-side PHP. LocalStorage is on client-side and you cannot pass client data to server using PHP. In this guide i will be showing you how to store the data into LocalStorage, Retrieve and pass it to the server side PHP scripting.
HTML to get input from the user and output the data retrieved from the server :
<input autofocus="autofocus" placeholder="Add Name for Storing" id="name"><input id="submit" type="submit" value="submit">
<div id="output"></div>
Read More: Ajax based add and delete items for storing user settings in LocalStorage using jQuery
Javascript code to Store input data in browser LocalStorage and pass it to the server-side PHP file. Input data is being stored as JSON Object and object itself is sent to server-side PHP using $_POST request as it is secure and faster.
// Function to generate random str as key for the localStorage
function randomStr(m) {
var m = m || 9; s = '', r = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i=0; i < m; i++) { s += r.charAt(Math.floor(Math.random()*r.length)); }
return s;
};
$(document).ready(function(){ var hasStorage = true; localStorage.clear(); if(!localStorage.getItem("names")) { var hasStorage = (function() { try { var myRSSObject = new Object(); localStorage.setItem("names", JSON.stringify(myRSSObject)); return true; } catch(e) { return false; } }()); } $("#submit").click(function() { if(hasStorage) { var names = JSON.parse(localStorage.getItem("names")); names[randomStr(7)] = document.getElementById("name").value; localStorage.setItem("names", JSON.stringify( names )); alert("Stored Succesfully"); document.getElementById("name").value = ""; alert("Now Passing stored data to Server through AJAX jQuery"); $.ajax({ type: "POST", url: "backend.php", data: {data: localStorage.getItem("names")}, success: function(data) { $('#output').html(data); } }); } else { alert("Storage Failed. Try refreshing"); } }); });
Server-Side PHP code : backend.php
<h1>Below is the data retrieved from SERVER</h1>
<?php
date_default_timezone_set('America/Chicago'); // CDT
echo '<h2>Server Timezone : ' . date_default_timezone_get() . '</h2>';
$current_date = date('d/m/Y == H:i:s ');
print "<h2>Server Time : " . $current_date . "</h2>";
$dataObject = $_POST['data'];
$json = json_decode($dataObject,true);
$i = 1;
foreach($json as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
$i++;
}
?>
What if I want to get data for more than one field? How do I change the script?
Could you be more elaborate in your requirements? If i understand, you are getting data of all the fields at once as JSON Object.
To help you, please elaborate your requirements.
I want to use your code to save form data (multiple fields) to localStorage and save the data via PHP in a txt or html file on the server. See my problem here: http://stackoverflow.com/questions/21336996/send-data-from-localstorage-via-ajax-to-php-and-save-it-in-an-html-file