Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make JQuery to treat Ajax response as plain text instead of JSON

Tags:

jquery

ajax

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.

like image 604
theark Avatar asked Oct 15 '14 13:10

theark


People also ask

Why is JSON preferred for AJAX?

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.

What is response text in AJAX?

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.

What is a common format used to send AJAX responses?

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.

Does AJAX use JSON?

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.


1 Answers

your code runs well, there has to be another error

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.

like image 179
Tuan Avatar answered Sep 19 '22 18:09

Tuan