How to Send JSON Objects in AJAX Requests from TypeScript
A common stumbling block when integrating TypeScript with PHP backends like CodeIgniter is misunderstanding how JSON.stringify interacts with jQuery's $.ajax method. In your scenario, the server receives a malformed payload where the entire JSON string becomes a single key with an empty value. This happens because you are passing a raw JavaScript object to the data property of the AJAX call while simultaneously setting the contentType to 'json'.
When jQuery sees data: {"_dificultad_seleccionada":"Normal"} (a plain object) combined with contentType: 'application/json', it attempts to serialize that object into a JSON string before sending it. However, because you also provided _params as a pre-serialized string via the third argument in your function call, jQuery gets confused about how to handle the payload. More critically, if you pass a string directly to data without explicitly telling jQuery to treat it as raw text, jQuery might try to encode it again or append it as a query parameter depending on the version and configuration.
The specific error you observedâwhere _REQUEST shows an array with the full JSON string as a keyâis a classic symptom of sending a serialized string when the server expects an object, or vice versa. In your PHP code:
print_r($_POST);
// Result: [{"_dificultad_seleccionada":"Normal"}] => [0] => )
This indicates that the request body was likely interpreted as a query string or form data rather than raw JSON, or the Content-Type header wasn't respected correctly by jQuery's default handling.
The Correct Approach for Raw JSON
To send a TypeScript object as a JSON payload to a PHP endpoint, you must ensure three things happen simultaneously:
- Serialize the Object: Convert your TypeScript class instance to a string using
JSON.stringify(). - Set the Content-Type: Explicitly tell jQuery (or the fetch API) that the body is JSON.
- Pass Raw Text to jQuery: Do not pass the serialized string as a plain object in the
dataproperty if you want it treated as raw body content.
Here is the corrected implementation for your universal AJAX function. Note the change from passing _params directly to using the processData: false option. This prevents jQuery from attempting to encode the data again or treating it as a standard form submission.
function sendAjaxRequest(_type: string, _url: string, _data: any, _callback: CallbackFunction) {
var request = $.ajax({
type: _type,
url: BASE_URL + _url,
data: _data, // This can be an object or a string
contentType: 'application/json', // Crucial for PHP to read raw JSON from $_POST
processData: false // Prevents jQuery from trying to encode the data again if it's already a string
});
request.done(function(res) {
_callback(res);
});
request.fail(function(jqXHR, textStatus) {
console.error(jqXHR);
_callback({ err: true, message: "Request failed: " + textStatus });
});
}
Now, in your click handler, you must ensure the object is stringified before passing it to this function:
let _dificultad: Dificultad = new Dificultad("Normal");
const jsonPayload = JSON.stringify(_dificultad);
// Pass the string, not the object instance
sendAjaxRequest("POST", "get_dificultad_seleccionada", jsonPayload, function(response) {
console.log(response);
});
Why processData: false Matters
In your original code, you passed a string to the third argument of sendAjaxRequest. When jQuery's default processData setting is true (which it is by default), and you pass a string to data, jQuery assumes you want to send that as form data or tries to parse it. By setting contentType: 'application/json', you are telling the server "I am sending JSON." However, if processData remains true, jQuery might conflict with this header.
Setting processData: false tells jQuery: "The data property is exactly what goes into the request body. Do not touch it." This ensures that the raw JSON string generated by JSON.stringify(_dificultad) is sent verbatim. On the PHP side, CodeIgniter will then populate $_POST with a key-value pair matching your JSON structure (depending on how CodeIgniter's routing and $this->input->post() handles the input), or you can read it directly from file_get_contents('php://input') if needed.
Alternative: Using Objects Directly
If you prefer not to manually stringfy the data in the client, you can pass the object directly and let jQuery handle the serialization. However, you must still set contentType: 'application/json'. This is often cleaner if your TypeScript class implements an interface that matches the expected JSON structure.
// Passing the object instance directly
let _dificultad: Dificultad = new Dificultad("Normal");
sendAjaxRequest("POST", "get_dificultad_seleccionada", _dificultad, function(response) {
console.log(response);
});
In this case, jQuery will automatically call JSON.stringify() on _dificultad before sending it. The critical part is that contentType must remain 'application/json'. This approach avoids the need to manually convert the class instance to a string, reducing the chance of syntax errors in the client code.
Server-Side Considerations
On the PHP side using CodeIgniter, simply printing $_POST might not always reveal the full picture if the Content-Type header is missing or incorrect. If you are debugging and want to ensure you capture raw JSON regardless of how it was sent, consider using $this->input->raw_input() in newer versions of CodeIgniter, or reading from php://input.
By aligning the client-side serialization with jQuery's expectations and explicitly managing the content type, your TypeScript objects will arrive at the PHP backend exactly as intended.