jQuery: inviare dati in formato JSON a PHP con AJAX

jQuery: inviare dati in formato JSON a PHP con AJAX

Inviare dati in formato JSON a PHP con jQuery ed AJAX richiede una procedura specifica.

PHP ha bisogno di una stringa JSON da poter trasformare in oggetto o array associativo. La stringa non solo dovrà essere sintatticamente valida, ma anche con codifica UTF-8. Quindi avremo:


var data = {
  test: $( "#test" ).val()
};
var options = {
  url: "test.php",
  dataType: "text",
  type: "POST",
  data: { test: JSON.stringify( data ) }, // Stringa JSON
  success: function( data, status, xhr ) {
     //...
  },
  error: function( xhr, status, error ) {
      //...
  }
};
$.ajax( options );

E in PHP:


<?php
  header('Content-Type: text/plain');
  $test = utf8_encode($_POST['test']); // Non dimentichiamo la codifica
  $data = json_decode($test);
  echo $data->test;
  exit();
 ?>
 
 
Torna su