Pass data from localstorage to php

0

I need to pass a data of localstorage to a variable php , and I store the data in a script on the same page but I get null to php , I do not know what I'm doing wrong or what I'm missing, I attach my code, thanks in advance for the help.

I capture the data from a form with a select, in an echo of php with the function save (), as I said I get to the localstorage and I even see the value in the local function () the local function is executed at load the page and take the data from the localstorage and send it to php via ajax (or that it was supposed to do), but it arrives null to php.

<script type="text/javascript">
  function guardar () {
  var count = document.getElementById('count').value;
  localStorage.setItem('count', count);
  var con = localStorage.getItem('count');
  saved = parseInt(con);
  console.log('count');
  alert(saved);
}
</script>

<script type="text/javascript">
 function local(){
 var con = localStorage.getItem('count');
 var  saved = parseInt(con);
 alert(saved);
        $.ajax({
           type: "POST",
           url: "index.php",         
           data:  {data: saved},
           success: function(data) {
              $('#output').html(data);
              alert(saved);
           }
        });
    };
</script>

<?php 
$saved = $_POST['data'];
?>
    
asked by BastianBurst 01.06.2017 в 16:48
source

1 answer

1

To be able to capture the value you have to add the following code:

<?php
    $resultado = array('mensaje' => '');
    if( isset($_POST['data']) ) {
        $resultado['mensaje'] = "Viene el valor : ".$_POST['data'];
        echo json_encode($resultado);
        exit;
    }
?>

Where we verify that the value $_POST['data] comes, if it comes, we add to the array $resultado the message value (this is just an example).

While in your javascript functions we leave them as they were except, that at ajax we add the parameter dateType : 'json'

function local() {
  var con = localStorage.getItem('count');
  var saved = parseInt(con);
  $.ajax({
      type: "POST",
      url: "index.php",
      data: { data: saved },
      dataType: 'json',
      success: function(data) {
          //$('#output').html(data);
          alert(data.mensaje);
      },
      error: function(error) {
          alert(error);
          console.log(error);
      }
  });
};
    
answered by 01.06.2017 / 16:56
source