0

i want to post a json object to php.

var user = {username:"test", password:"test", name:"test",  
email:"test@hotmail.com"};
var str_json = JSON.stringify(user);
$.ajax({
        url: '/register_API.php',
        type: 'post',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
           console.log('success');
        },
        data: user
    });
}

In php i want to insert it into mysql:

$data = file_get_contents('php://input');
$json = json_decode($data,true);

$username = $json['username'];
$password = $json["password"];
$email = $json['email'];

$insertSql = "INSERT INTO users (username, password, email)
VALUES ('$username', '$password', '$email');";

The $data string contains: username=test&password=test&name=test&email=test%40hotmail.com, but i can't get the variable by decoding...

Thanks in advance!

Papauha
  • 169
  • 1
  • 1
  • 8
  • 1
    Your not sending the stringified json data: str_json your trying to send the user object. change data: user to data: str_json – Drew Mar 06 '15 at 20:22
  • possible duplicate of [How to get parameters from this URL string?](http://stackoverflow.com/questions/11480763/how-to-get-parameters-from-this-url-string) – mopo922 Mar 06 '15 at 20:23
  • Specify `data: str_json,` above your success function. – Jay Blanchard Mar 06 '15 at 20:34

4 Answers4

2

Change data: user to data: str_json and then

change $data = file_get_contents('php://input');

to $data = $_POST['data']

developerwjk
  • 8,619
  • 2
  • 17
  • 33
1

You're not sending a JSON string, you're sending a Javascript object which jQuery is translating to a set of parameters in the outgoing POST request. Your data will be available to PHP in $_POST - no need to decode it first.

Look for it like this:

$username = $_POST['username'];
$password = $_POST["password"];
$email = $_POST['email'];
0

I think you want to send raw JSON as text and have that be in the post body and not treated as an encoded form.

In this case I think your PHP code is right. Send the stringified JSON as you are, but set the data type to dataType: "text".

I think you will be able to read it with

$data = file_get_contents('php://input');

dudeman
  • 503
  • 3
  • 11
0

I think you can use

//works like explode, but splits your data where finds "=" and "&" too.
$output = preg_split( "/ (=|&) /", $data);

This will return an array of your data. where:

$output[0]="Username";
$output[1]="test";

This can be useful if you have fixed data.

David Demetradze
  • 1,361
  • 2
  • 12
  • 18