Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending JSON to server, using jQuery

Tags:

jquery

php

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

This is what I have so far:

var emails = ['[email protected]', '[email protected]', '[email protected]'];

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 can see that the data is POSTed to the server - however, at the server, there is no data ($_POST is empty) - what am I doing wrong?

like image 848
oompahloompah Avatar asked Jun 24 '11 00:06

oompahloompah


1 Answers

We post all of our data with 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"
  ));
?>

This way we don't even mess with the post variables, and in general, its faster than having jQuery process them.

like image 188
Rahly Avatar answered Oct 06 '22 21:10

Rahly