将JSON字符串传递给$ .ajax并在PHP文件中访问它

I am trying to send JSON encoded string to PHP file through ajax.

I tried this but the $_POST is empty in the ajax target file.

var html = $.ajax({
            type: "POST",
            url: "getControl.php",
            data:js_post_array,
            dataType: 'json',
            async: false,
            success: function (data, status)
            {
              //alert('here');
              //$("#notiDesc").text(data.msg);              
            }
         }).responseText;

js_post_array contains json encoded string

{ 'business_name': 'test', 'business_type': 'R', 'type': '', 'total_sku_in_store': '',
 'speciality': '', 'first_name': '', 'last_name': '', 'title': '', 
 'responsible_for_wine_buying': '', 'responsible_for_events': '', 'address1': '' }

but in the getControl.php file I tried print_r($_POST) that shows an empty array.

But when I just copy this string and paste here data:js_post_array, instead of js_post_array then it works fine.

What I am doing wrong?

it's because data accepts a string not other data type like array...it just append string as a query String in url and send to server.
So if you pass an array then it's not going to break this into string, that's why it's giving you empty $_POST

Are you sure the js_post_array is visible inside that function?

It looks like a new variable named js_post_array is created empty in the ajax call.

Try to declare js_post_array this way:

var js_post_array = ....;

var html = $.ajax {
...
}

For the send part, do the following:

$.ajax({
    url: …,
    // Make sure to send data as post body
    type: 'POST',
    headers: {
        // Make sure to send as JSON
        'Content-Type': 'application/json',
    },
    // Serialize your object
    data: JSON.stringify(sampleData)
});

For the receiving part:

<?php
// Get the response body (the data is not in $_POST)
$body = file_get_contents('php://input');
print_r(
    // Convert JSON string to some PHP data structure (PHP array)
    json_decode($body)
);

Note that

  • The JSON string from the question is not valid since it uses apostrophes instead of quotes around the keys
  • $_POST does only contain form-encoded data, not data that was sent as JSON