I am consuming an API that return JSON. The JSON syntax returned by API is broken and I have no control to get it fixed.
I am using JQuery Ajax call and it returns 500 - Internal Server Error. I want to get API response and plain text and fix the JSON syntax. it just has an additional comma at the end which I can remove. But I am not able to get the response as plain text.
I have tried several approaches such as setting content-type and/or accept headers to plain text using dataType to plain text as below. My code is as below.
$.ajax({
url: apiUrl + "/" + customerId + "/accounts/" + accountId,
data: "client_id=" + clientId,
dataType: 'text',
type: 'GET',
async: true,
statusCode: {
404: function (response) {
console.log('Invalid Transaction details');
},
200: function (response) {
//response processing code here
}
},
error: function (jqXHR, status, errorThrown) {
//Error handling routine
}
});
Update 1 The API works fine when directly called from browser or fiddler. That's how I come to know that JSON syntax is broken.
Although X in Ajax stands for XML, JSON is preferred over XML nowadays because of its many advantages such as being a part of JavaScript, thus being lighter in size. Both JSON and XML are used for packaging information in the Ajax model.
The responseText method is used for all formats that are not based on XML. It returns an exact representation of the response as a string. Plain text, (X)HTML, and JSON are all formats that use responseText.
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.
According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.
See my fiddle
$.ajax({
url: 'http://ip.jsontest.com/',
dataType: 'text',
type: 'GET',
async: true,
statusCode: {
404: function (response) {
alert(404);
},
200: function (response) {
alert(response);
}
},
error: function (jqXHR, status, errorThrown) {
alert('error');
}
});
It returns json from a test API as a string all fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With