0

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?

Developer
  • 2,676
  • 8
  • 43
  • 65
  • 1
    What did you try already? – kero Apr 28 '14 at 14:17
  • hello @kingkero i have tried 1hr but not solved my problem – Developer Apr 28 '14 at 14:18
  • ok, so first lookup [`$.ajax`](https://api.jquery.com/jQuery.ajax/). You made a `POST` request with `lookup` (which jQuery automatically converts, so you can safe some code). Now I look up sth like ["_php post_"](http://bit.ly/MzqCWe) and am already linked to [the official manual on `$_POST`](http://www.php.net/manual/de/reserved.variables.post.php) – kero Apr 28 '14 at 14:24
  • [Decoding JSON as associative arrays instead of objects](http://stackoverflow.com/questions/5164404/json-decode-to-array) – moonknight Apr 28 '14 at 14:41

2 Answers2

1

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'];
...
sroes
  • 14,663
  • 1
  • 53
  • 72
0

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'];
jeroen
  • 91,079
  • 21
  • 114
  • 132