0

I have problem with send json by AJAX.

var data = [{"name": "Will", "surname": "Smith", "age": "40"},{"name": "Willow", "surname": "Smith", "age": "15"}];

$.ajax({
    type: "POST",
    url: "ajax.php",
    dataType: "json",
    data: data,
    success: function(response)
    {
        alert(response);
    }
});

ajax.php

<?php
     echo json_encode($_POST);
?>

And ajax alert response is[object Object]

How to get array in php side?

2
  • whats the reponse of ajax in console. Commented Jun 15, 2014 at 14:02
  • 1
    You have to convert data to string by JSON.stringify Commented Jun 15, 2014 at 14:02

1 Answer 1

1

You have to convert data to string by JSON.stringify method and place it into an object. Somehow like this:

$.ajax({
    type: "POST",
    url: "ajax.php",
    dataType: "json",
    data: {"data": JSON.stringify(data)},
    success: function(response)
    {
        alert(response);
    }
});

Then on server-side you can access passed data by $_POST['data']:

echo json_decode($_POST['data']);
Sign up to request clarification or add additional context in comments.

3 Comments

Now this works, json is sending. How to get this json by php side as array?
You could upvote this answer as well if it solve your problem
im getting parse error with <?php $data = json_decode($_POST,true); echo $data; ?>

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.