json_encode返回null php数组

I am trying to send a php array to ajax but it does not work. To be honest I do not know what am I doing wrong.

I am using json_encode() which returns null.

my php code:

$info = array();
$info['NEW YORK CITY'] = array(
'Name' => 'New York City'
);

$city = $_POST['city'];

if (strtoupper($city) === 'NEW YORK CITY') {

echo "Name: " . json_encode($info['NEW YORK CITY']['Name']) . ".<br>";
} else {
echo "error.";
}

my ajax code:

$('form.ajax').on('submit', function() {
var that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),
    data = {};

    that.find('[name]').each(function(index, value) {
        var that = $(this),
            name = that.attr('name'),
            value = that.val();

            data[name] = value;

    });

    //console.log(data);

    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function(response) {
            //console.log(response);

            $('form.ajax').html(response);
        }
    }).fail(function(jqXHR) {
        alert(jqXHR.statusText);
    });

return false;
});

Fixed it! I had the json_encode before the array. It works now that I put the array on top.

json_encode accepts an array as an argument

Such that it will take the following

array('key' => 'value')

This will be sent as properly formated json key:value. But a single value will not be handled correctly and may lead to unwanted results.

replace your php code with the following

$city = $_POST['city'];
 if (strtoupper($city) === 'NEW YORK CITY') {
     echo json_encode($info['NEW YORK CITY']);
 } else {
     echo json_encode(array("error."));
 }

Try this if this works:

  $city = $_POST['city'];

   if (strtoupper($city) === 'NEW YORK CITY') {
    echo json_encode(['Name' => $info['NEW YORK CITY']['Name'] ]);
   } else {
     echo json_encode(['error']);
   }

Ajax:

 $('form.ajax').on('submit', function() {
  var that = $(this),
  url = that.attr('action'),
  type = that.attr('method'),
  data = {};

  that.find('[name]').each(function(index, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();

        data[name] = value;

   $.ajax({
    url: url,
    type: type,
    data: data,
    success: function(response) {
        //console.log(response);

        $('form.ajax').html(response);
     }
     }).fail(function(jqXHR) {
     alert(jqXHR.statusText);
   });

    return false;

  });

});

Your ajax should be after the on submit then it will trigger the AJAX functions.