1. Home
  2. Web designing
  3. How to pass LocalStorage data to PHP using Ajax jQuery

How to pass LocalStorage data to PHP using Ajax jQuery

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.

Pass-LocalStorage-data-to-PHP-using-jQuery
Pass-LocalStorage-data-to-PHP-using-jQuery

[sc:demobuttons demolink=”http://demo.techglimpse.com/pass-localstorage-data-to-php-using-ajax/” title=”” boxlink=”http://adf.ly/PkpeE”]

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++;
        }
?>

[sc:demobuttons demolink=”http://demo.techglimpse.com/pass-localstorage-data-to-php-using-ajax/” title=”” boxlink=”http://adf.ly/PkpeE”]

More on HTML5 LocalStorage:

How to store data in Browser’s HTML5 LocalStorage using Javascript

How to dynamically load contents on previous and next navigation buttons click using Ajax

How to parse XML using jQuery, store in HTML5 LocalStorage and read from LocalStorage

Updated on September 2, 2017

Was this article helpful?

Related Articles

Comments

  1. What if I want to get data for more than one field? How do I change the script?

    1. 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.

Add A Comment