Search code examples
javascriptphphtmlweb-storage

How to submit all sessionStorage content to PHP server


I am currently working with something like the below but I'm having trouble with syntax in assigning all of my sessionStorage data to a variable and passing that through to my PHP:

var exampleValueOne = "Value A";
var exampleValueTwo = 2;
var exampleValueThree = "Value XYZ";

//Example value from my HTML modal where multiple of the same 'users' may be captured
var dropDownValue = $('#aDropDown').find('option:selected').attr('value');

//Some assignments
sessionStorage.setItem("valueA", exampleValueOne );
sessionStorage.setItem("valueB", exampleValueTwo );
sessionStorage.setItem("valueC", exampleValueThree );

//Need to be able to assign an indeterminate amount of valueD key value pairs
if (sessionStorage.getItem("valueD1") === null) {   

    var countNumber = 1;           
    sessionStorage.setItem("valueE", countNumber);

    for (var i = 0; i < countNumber; i++){  

    sessionStorage.setItem("valueD"+[countNumber], dropDownValue);

    }

} else {

    //if at least one valueD exists it means we need to add after the last one  
    var countNumber = parseInt(sessionStorage.getItem("valueE"));  
    //update the count
    sessionStorage.setItem("valueE", (countNumber + 1));

    for (var i = countNumber; i < (countNumber + 1); i++){

        sessionStorage.setItem("valueD"+[countNumber], dropDownValue);

    }

}

sessionStorage should look as follows after the above:

valueA: "Value A"

valueB: "2"

valueC: "Value XYZ"

Assuming two values have been saved using for loop they would be save as such (value 8 and 2 are just random example attribute values from the html side):

valueD1: "8"

valueD2: "2"

//NOW I would like to pass these values to my PHP using Ajax

var data = {
            /*ALL SESSION STORAGE ITEMS?*/
            };                                                             

            $.ajax({
                type: "POST",
                url: "myPHP.php",
                data: data,
                success: function(){                    
                return false;
                }
                });

Solution

  • You can use the length property and key(i) method to get all the keys that are used in the sessionStorage. with those keys you can retrieve the values just like normal

    sessionStorage.setItem("valueA", '1' );
    sessionStorage.setItem("valueB", '2' );
    sessionStorage.setItem("valueC", '3' );
    
    //Create data object so we can submit it to the server 
    var data = {};
    for(var len = sessionStorage.length, i = 0; i < len; i++) {
        var key =  sessionStorage.key(i);
        data[key] = sessionStorage.getItem(key);
    }
    console.log(data);
    
    //From this point you can post the `data` to your server side
    $.ajax({ type: "POST", url: "myPHP.php", data: data });