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":"[email protected]","items":[{"message":"Bla Bla Bla!!!","value":"100"}]}

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

4
  • 1
    What did you try already? Commented Apr 28, 2014 at 14:17
  • hello @kingkero i have tried 1hr but not solved my problem Commented Apr 28, 2014 at 14:18
  • ok, so first lookup $.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" and am already linked to the official manual on $_POST Commented Apr 28, 2014 at 14:24
  • Decoding JSON as associative arrays instead of objects Commented Apr 28, 2014 at 14:41

2 Answers 2

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'];
...
Sign up to request clarification or add additional context in comments.

3 Comments

not working. coming error message <br /> <b>Notice</b>: Undefined index: name in <b>E:\xampp\htdocs\2014\ebay\ajax.php</b> on line <b>5</b><br />
still coming error <br /> <b>Fatal error</b>: Cannot use object of type stdClass as array in <b>E:\xampp\htdocs\2014\ebay\ajax.php</b> on line <b>6</b><br />
We're getting there.. try again :)
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'];

3 Comments

This one also not working. error message <br /> <b>Notice</b>: Undefined index: json_string in <b>E:\xampp\htdocs\2014\ebay\ajax.php</b> on line <b>5</b><br />
Yes i have changed my javascript and php page
Hi @jeroen I got my answer your code showing blank array array(0) { } when i am using var_dump($_POST); Thanks for trying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.