Reputation: 1167
I've done some research and even have a book that explains Ajax calls to php and sending data to and from browser and server. I found this to be pretty close to what I need since I am using local storage How can I pass saved localStorage web data to a php script?, this link seems pretty coherent but I am not sure what to do on the PHP side How to pass data from Javascript to PHP and vice versa?,
though I have a bigger problem, the amount of data I have in local storage is pretty large, there are several different arrays that are stored there and are JSON encoded, when I get the array I use JSON.parse and to set the array in storage I stringify it. How could this be done to send that kind of data over? Not all the data in localStorage is an array either, there are hundreds of variables in local storage that need to be saved.
EDIT:
Here is my code since it was brought to my attention that it is needed. I am trying to get all the data from localstorage to be sent to the server to be saved in a database.
function postData(){
var storage = JSON.stringify(localStorage);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
};
xhr.open('POST', 'Membership.php');
xhr.setRequestHeader("Content-Type: text/json", "application/x-www-form-urlencoded");
xhr.send("data=" + storage);
}
On the PHP side of things I have
if ($_POST){
$data = json_decode($_POST['data']);
echo "The data" .$data;
}
I don't know if this is correct, I can't find anything on how to pass all localstorage data, this is basically what I was trying to ask before but obviously failed to convey that.
Upvotes: 0
Views: 5542
Reputation: 1626
Basically what you need to do is:
Prepare the AJAX request using jQuery or other_framework_of_choice and set the payload to the stringified data and send it:
Content-type: text/json
ti send a hint to the service that you are sending JSON data (Optional, but recommended)Process the data within the PHP side (I.e json_decode
the payload and process it using your own logic satisfying your needs.
You didn't provided any code, so I would just skip the coding part (I can't guess your codes, mate)
You can refer to Send data from localStorage via AJAX to PHP and save it in an HTML file just skip the saving part and replace with your desired processing
Upvotes: 1