imperium2335
imperium2335

Reputation: 24112

How to send and receive using AJAX and JSON

I'm trying to setup a simple AJAX call that sends it's data via JSON to my PHP script, which then returns the data.

But I am having no luck.

Here is my code for sending:

$.ajax({
      url: ROOT+'Address/fetchAddress',
      type: 'POST',
      async: false,
      dataType: 'json',
      data: {
        json: {
          "Id":"0",
          "Name":"Jim"
        }
      },
      error: function(a, b)
      {
        alert(b)
      },
      success: function(data)
      {
        data = $.parseJSON(data);
        alert(data)
      }
    })

Serverside:

public function fetchAddress()
  {
    $JSON = $_POST['json'];
    echo json_decode($JSON);
  }

But I am getting "parseerror" in alert box and if I inspect the response I get:

Warning: json_decode() expects parameter 1 to be string, array given in ...public_html\controllers\Address.php on line 20

Upvotes: 0

Views: 883

Answers (3)

Loupax
Loupax

Reputation: 4914

The data your PHP receives does not need to be decoded, as it is already an array. Just change your function to this and you should be fine

public function fetchAddress()
{
  echo json_encode($_POST['json']);
}

Also, since you have said jQuery that your response is a json, there is no need to call $.parseJSON() to your fetched data

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

The ajax call sends the data as an array and expects the returned data as JSON, so the PHP function should look like

public function fetchAddress()
{
    $data = $_POST['json'];
    echo json_encode($data);
}

and the client side need not decode the returned data, because it specified dataType: 'json' and then this is already done by the ajax function

$.ajax({
      url: ROOT+'Address/fetchAddress',
      type: 'POST',
      async: false,
      dataType: 'json',
      ...
      success: function(data)
      {
        alert(data)
      }
    });

Upvotes: 1

cjds
cjds

Reputation: 8426

There's a conceptual mistake here.

When you say dataType: 'json' it means returned data is in JSON format.

You are still sending data in a POST array

public function fetchAddress(){
    echo $_POST['json'];
}

to fetch the data

To pick up on the other side you have a pre-passed object (as data is returned as JSON)

So

success: function(data)
  {

    alert(data.id+"NAME"+data.name);
  }

(Oh and your data is not a string (which a post expects) and JSON is so clean it up into a nice string

json: '{"Id":"0","Name":"Jim"}'

Upvotes: 3

Related Questions