Sending JSON to the server using jQuery

I am trying to send simple data to sservre and I need a "rough and ready" way to do this.

This is what I have so far:

var emails = ['a@123.com', 'b@123.com', 'c@123.com'];

var ruff_json = "{ 'emails': [";
for (i in emails)
    ruff_json += ((i == 0) ? '' : ', ') + '\''+emails[i]+'\'';

ruff_json += '] }';

jQuery.ajax({
    type: 'POST',
    url: '1.php',
    data: ruff_json,
    dataType: "json",
    timeout: 2000,
    success: function(result){
        //do something
    },
    error: function (xhr, ajaxOptions, thrownError){
        //do something
    }
});

Using Firebug, I see that the data is being sent to the server, but there is no data on the server ($ _POST is empty) - what am I doing wrong?

+5
source share
3 answers

We publish all the data using json.

var myobj = { this: 'that' };
$.ajax({
  url: "my.php",
  data: JSON.stringify(myobj),
  processData: false,
  dataType: "json",
  success:function(a) { },
  error:function() {}
});

then in php we do

<?php
  $json = json_decode(file_get_contents("php://input"), true);
  // Access your $json['this']
  // then when you are done
  header("Content-type: application/json");
  print json_encode(array(
    "passed" => "back"
  ));
?>

Thus, we do not even encounter post-variables, and in general, it is faster than the jQuery process.

+7
source

Your data field must contain an object with key-value pairs because it receives the encoding as POST value pairs.

data = {my_json: encoded_string};

PHP :

$data = json_decode($_POST['my_json']);
+2

PHP fills $_POSTby analyzing the data. However, it only knows the data encoded in the form, JSON data cannot be parsed automatically. Therefore, it $_POSTwill be useless in this case. You need to get the raw data of the message and analyze it with json_decode.

0
source

All Articles