Øyvind
Øyvind

Reputation: 55

Localstorage to PHP variable

I am sending and retrieving some data with this ajax call and saving result in localstorage like this:

$.ajax({
    url: "list.php", 
    data: {values: values}, 
    dataType: "json",
    success: function(result){
    var dataToStore = JSON.stringify(result);
    localStorage.setItem('key', dataToStore);
    }  
});

Then I am retrieving it in a separate PHP document like this and trying to add it to a PHP variable. I think the problem occurs because when I console.log, it logs 10 times or so. And I can't echo it in PHP. How do I pass it correctly?

<script>
var localData = JSON.parse(localStorage.getItem('key'));

$.each(localData, function(key, value){
console.log("This is the data that is stored", localData)
$.ajax({
type: 'post',
        data: {localData}, 
        dataType: "json",
        success: function(result){
        console.log(result)
        }  

        });
</script>

<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier = implode(", ", $user_id);
?>

Upvotes: 0

Views: 3377

Answers (1)

A.B
A.B

Reputation: 20445

You are causing an asynchronous functionality of ajax() real pain by calling it in a loop

Why dont you use join() to join items with ", " in js like what you do in php

<script>
var localData = JSON.parse(localStorage.getItem('key')).join(", ");


$.ajax({
type: 'post',
        data: {localData}, 
        dataType: "json",
        success: function(result){
        console.log(result)
        }  

        });
</script>

<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier =  $user_id;
?>

You Should also cast user_id as an (int) if user_id need to be a single value and int

$verdier = (int) $user_id;

Upvotes: 2

Related Questions