PHP $_POST not populating from jQuery (JavaScript) $.ajax() POST

Problem

I was trying to submit data from a web page to a back-end API in PHP using jQuery’s AJAX (ie. $.ajax()).

But the $_POST variable in PHP didn’t contain the values I was posting.

 

Solution

The problem is I was encoding the POST body data the wrong way in JavaScript.

I was using JSON.stringify(data), where “data” is a JavaScript object or array.

What I needed to do what manually create a string of key1=value1&key2=value2&keyN=valueN pairs.

Example Code from my submit function:

        //sendData = JSON.stringify(data);  //<-- This doesn't work ...

        // ... but this does.
        sendData = "";
        for (var key in data) 
        {
            if (sendData != "") sendData = sendData + "&";
            sendData = sendData + key + "=" + data[key];
        }

	var ajaxRequest = {
		url: url,
		type: "POST",
		data: sendData,
 		dataType: dataType,

		success: function(data, textStatus, jqXHR)  { successCallback(data, textStatus, jqXHR ); },
		error: function(jqXHR, textStatus, errorThrown) { errorCallback(data, textStatus, errorThrown); }
	};

	$.ajax(ajaxRequest);

 

What I searched for (which didn’t help much):

Search “$_POST empty from jquery”: https://duckduckgo.com/?q=%24_POST+empty+from+jquery&amp;atb=v147-1&amp;ia=web

https://stackoverflow.com/questions/1650516/jquery-ajax-method-post-but-post-empty

https://stackoverflow.com/questions/16360008/jquery-post-post-empty

https://stackoverflow.com/questions/54039285/ajax-form-posting-to-php-script-but-post-is-empty-in-php-script

https://stackoverflow.com/questions/1650516/jquery-ajax-method-post-but-post-empty/49948834#49948834