Skip to content
Advertisement

jQuery ajax call is returning response data as String instead of Object

On the following StackBlitz:

https://stackblitz.com/edit/react-jbthdw?file=src%2FApp.js

I have a code which fetches a JSON data with a list of names.

There are two ways of returning data: Axios and jQuery.

With the Axios approach the code works properly.

Now, because some business decisions I need to replace Axios with jQuery.

My problem is: with jQuery the response.data is fetched as string when it should be as object as it happens with Axios.

Below you have the code, but feel free to play with the StackBlitz playground I provided above:

import React from 'react';
import axios from 'axios';
import $ from 'jquery';
import './style.css';

export default () => {

  const jsonSource = 'https://raw.githubusercontent.com/tlg-265/mockend/master/data.json';
  
  const handleClickAxios = () => {
    axios.get(jsonSource).then(response => {
      console.log({ responseType: (typeof response.data)});
      console.log(response.data);
    });
  };

  const handleClickJQuery = () => {
    sendApiRequest({ url: jsonSource, method: 'get' }).then(response => {
      console.log({ responseType: (typeof response.data)});
      console.log(response.data);
    });
  };

  return (
    <div>
      <h1>Axios vs jQuery</h1>
      <p><b>Inconsitency:</b> returning response as Object vs String</p>
      <button onClick={handleClickAxios}>Axios</button>{' '}
      <button onClick={handleClickJQuery}>jQuery</button>
    </div>
  );
};

export const sendApiRequest = ({
  url,
  method,
  data,
  timeout,
}) => {
  method = method.toUpperCase();

  let additionalSettings = { data: data };
  if (method === 'POST') {
    additionalSettings = {
      contentType: 'application/json',
      dataType: 'json',
      data: JSON.stringify(data),
    };
  }

  return new Promise((resolve, reject) => {
    $.ajax({
      url,
      method: method,
      timeout,
      ...additionalSettings,
      success: (response) => {
        resolve({
          data: response
        });
      },
      error: ({ responseJSON }) => {
        reject(responseJSON);
      },
    });
  });
};

Here you have a screenshot of the issue:

enter image description here

Any idea on what do I need to update on the code in order to get: response.data as object with jQuery? I need to get that without any post processing of the response. Is there maybe any params I could use with jQuery so it behaves similarly to Axios?

Thanks!

Advertisement

Answer

The URL you are requesting includes this response header:

content-type: text/plain; charset=utf-8

Which is why jQuery isn’t processing it as JSON automatically.

A quick search of the documentation for the word “json” quickly brings up the dataType option which lets you override the content-type.

const jsonSource = 'https://raw.githubusercontent.com/tlg-265/mockend/master/data.json';

jQuery.ajax({
  url: jsonSource,
  dataType: 'json'
}).then(data => {
  console.log({
    responseType: (typeof data)
  });
  console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement