简体   繁体   中英

How can I use localStorage in php with AJAX to update my database?

I need to use a localStorage value in a PHP file to update values in my database. I know that I need ajax to achieve this, I can't get it to work.

My localStorage item is named option and it exists (checked in browser and stored the value in a div )

$(document).ready(function(){
        $.ajax({
            type: "POST",
            url: "activity.php",
            data: { storageValue: localStorage.getItem('option') },
            success: function(data){
                alert('success');
            }
        });
    });

PHP Example:

$option = $_POST['storageValue'];
mysql_query("...SET x = '".$option."'...");
echo 'Update complete';

I dont see any post data nor do I get a response.

Thank you!

Your page:

<form>
<input type="hidden" value="thedatayouwanttopost" id="option"/>
</form>
<script src="Your_Js_File.js"></script>

Your JS file:

document.getElementById('option').submit(); // This submits the form

var storageValue = $('#option').val(); // This gets the value of the form once it has been posted to the .php file

$(document).ready(function(){
        $.ajax({
            type: "POST",
            url: "activity.php",
            data: { storageValue:storageValue },
            success: function(data){
                alert('success');
            }
        });
    return false; // This stops the page from refreshing
    });

Your PHP file to callback the data to AJAX and display the alert (activity.php):

...
$option = $_POST['storageValue']; // This is the post value of your hidden input on your page

mysql_query("...SET x = '".$option."'...");
?><input type="hidden" id="option" value="<?php echo $option; ?>"><?
// The input above posts the value of 'option' on your page back to your Ajax and spits out the request.
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM