Search code examples
javascriptphpjquerysessionstorage

Remove quotes when reading from sessionStorage and sending to php using jquery


I'm storing different values in the sessionStorage during a longer process. At the end i want to read all the data and send it to my php backend using ajax. The problem is that php seems to take every value including quotes. Here is what i got:

// Reading data from storage
var imgb = sessionStorage.getItem("img_b_id");
....
// perpare data
var oData = {
            imgb: imgb,
            ...
};

// Sending data
$.post( "../php/direct/create.php", oData).done(function(data) {
    if(data==true) {
        window.open("step5.php", "_self");
    } else {
        alert("Error: " + data.toString()); 
    }
});

This is working perfectly fine. However, php will read the value of imbg with quotes. Example:

echo $_POST['imgb'];
/* Returns "asd" instead of asd

The image below shows that my data is stored without the quotes (chrome sessionstorage screenshot) enter image description here

Do you have any suggestions on how to solve this. I currently replace the quotes, but I'd love to fix this problem at it's root...


Solution

  • I have tried your code ( with Firefox and Chrome ) and

    echo $_POST['imgb'];
    

    Print the string without quotes. Consider that even if you set a number in the session storage, for example

    sessionStorage.setItem("img_b_id", 100);
    

    The value is received at server by PHP as a string so you can convert it with PHP functions intval(), floatval() etc.

    http://php.net/manual/en/function.intval.php