0

i want to post a json object to php.

var user = {username:"test", password:"test", name:"test",  
email:"[email protected]"};
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!

3
  • 1
    Your not sending the stringified json data: str_json your trying to send the user object. change data: user to data: str_json Commented Mar 6, 2015 at 20:22
  • possible duplicate of How to get parameters from this URL string? Commented Mar 6, 2015 at 20:23
  • Specify data: str_json, above your success function. Commented Mar 6, 2015 at 20:34

4 Answers 4

2

Change data: user to data: str_json and then

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

to $data = $_POST['data']

Sign up to request clarification or add additional context in comments.

Comments

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'];

Comments

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');

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.