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


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.



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); }



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

Search “$_POST empty from jquery”:;atb=v147-1&amp;ia=web