user3762051 user3762051 - 5 years ago 338
PHP Question

How to post local storage data to php file

Thanks for your time in reading this post.

I am developing an ecommerce website and used open library simplecart.js to store the cart variables.

I noticed that js file is storing cart items in local storage.

Below is the format that it is getting stored in the local storage

simplecartitems(key) {"SCI-1":{"quantity":1,"id":"SCI-1","price":300}}(value)


I understood as this data is stored in the client side, there is no way php can access.

Can you please help me how to post this data to php, so that i can access the same from another php file

Thanks in Advance.

Answer Source

I'll try keep it simple, but to fetch elements from local storage, you'll need to harness the localStorage.getItem() method.

var data = localStorage.getItem('SCI-1'); // whatever your actual key is, in your local storage.

I'll leave you to figure out if you want to validate the above, but if it does't find anything, it'll just return null.

Now for sending it to the server, You'd be best to check out & use jQuery, harnessing jQuery.post().

$.post( "/path/to/your/url", { data: data}, function(response) {
    console.log(response); // handle the response from the server
} );

If done correctly, you'll receive your local storage data via $_POST in your PHP script. Accessing it is as simple as:

<?php

$data = $_POST['data'];

Note: I'll leave you to figure out how you want to test/sanitize/check/validate your data within the PHP script.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download