简体   繁体   中英

How to get JSON data in ajax.php page?

I am sending email using ajax JSON.

Code:

var lookup = {
            'name': fname,
            'email': email,
            'items': [{
                'message': message,
                'value': itemValue
            }]
        }
        $.ajax({
            type: 'post',
            url: 'ajax.php',
            data: JSON.stringify(lookup),
            success: function(data){
                alert(data);
            },
            contentType: 'application/json',
            dataType: 'json'
        });

My data is going to JSON format

{"name":"Chinmay","email":"xxxxxxxx@gmail.com","items":[{"message":"Bla Bla Bla!!!","value":"100"}]}

In my ajax.php page how to get the name , email , message and value ?

Since you're posting the data as JSON, you have to deserialize the raw post data :

$data = json_decode(file_get_contents("php://input"), true);
echo $data['name'];
...

That is not going to work. The data argument needs key - value pairs, so you could do something like:

data: {json_string: JSON.stringify(lookup)},

and in php:

$data_array = json_decode($_POST['json_string']);

Although normally you would just send the form to your php (if possible) file without having to build the data-structure yourself:

data: $('form').serialize(),

and then in php you can do something like:

$name = $_POST['fname'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM