The updated syntax for the Dojo XHR request is failing to retrieve the data as intended

As the title suggests, I am currently implementing the new syntax for dojo/request/xhr. However, I have encountered an issue where the data does not load properly and throws an error. Surprisingly, using the old syntax with the same URL yields the desired result.

Here is the code snippet with the current syntax that is causing the problem:

    this.get = function (url, loadFunc, errorFunc, handleFunc) {
        xhr( url, {
            handleAs: 'json'
        }).then(function(data){
            typeof loadFunc === 'function' ? loadFunc : function () { };
            console.log(url+ " load");
            console.log(data);
        }, function(error){
            typeof errorFunc === 'function' ? errorFunc : function () {  };
            console.log(url+" error");
            console.dir(error);
        }, function(handle){
            typeof handleFunc === 'function' ? handleFunc : function () { };
            console.log(url+" handle");
            console.log(handle);
        });
    };

Although the data is correctly logged in the console, the xhr request produces the following error:

"SyntaxError: Unexpected token o at Object.parse (native) at l.json (http://ajax.googleapis.com/ajax/libs/dojo/1.8.1/dojo/dojo.js:228:250) at m (http://ajax.googleapis.com/ajax/libs/dojo/1.8.1/dojo/dojo.js:227:277) at j [as handleResponse] (http://ajax.googleapis.com/ajax/libs/dojo/1.8.1/dojo/dojo.js:151:351) at XMLHttpRequest.e (http://ajax.googleapis.com/ajax/libs/dojo/1.8.1/dojo/dojo.js:154:393)"

In contrast, the following old syntax works flawlessly:

    this.get = function (url, loadFunc, errorFunc, handleFunc) {
      dojo.xhrGet({
            url: url,
            handleAs: 'json',
            load: typeof loadFunc === 'function' ? loadFunc : function () { },
            error: typeof errorFunc === 'function' ? errorFunc : function () { },
            handle: typeof handleFunc === 'function' ? handleFunc : function () { }
        });
    };

EDIT:

This is the JSON data being used:

{ "assistants" : [ { "assistants" : [ "M 11",
        "M 1"
      ],
    "name" : "M X1"
  },
  { "assistants" : [ "M 2",
        "M 2XX1",
        "M 3"
      ],
    "name" : "M 1"
  },
  { "assistants" : [ "M 2" ],
    "name" : "M 2"
  },
  { "assistants" : [  ],
    "name" : "M 3"
  }
],
"chiefs" : [ { "chief" : "M X1",
    "name" : "M 11"
  },
  { "chief" : "M 11",
    "name" : "M 1"
  },
  { "chief" : "M X1",
    "name" : "M 2"
  },
  { "chief" : "M 744X1",
    "name" : "M 3"
  }
],
"departments" : [ { "assistants" : [ "M 11",
        "M 3",
        "M 21"
      ],
    "chief" : "M X1",
    "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddb9ba9daeb2b0b8b9b2b0bcb4b3f3beb2b0">[email protected]</a>",
    "interim" : [ "M X542",
        "M 4"
      ],
    "members" : [ "M 2",
        "M 3",
        "M 4",
        "M 5",
        "M X24544"
      ],
    "name" : "Dep1",
    "notify" : [ "Dep2",
        "M X2",
        "M 21"
      ],
    "resp" : "M 21",
    "validators" : [ "Dep2",
        "M 2",
        "M 558"
      ]
  },
  { "chief" : "M 1",
    "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3756535a5e597744585a5253585a565e591954585a">[email protected]</a>",
    "members" : [ "M 11",
        "M 12"
      ],
    "name" : "Dep3",
    "parent" : "Dep1"
  },
  { "chief" : "M 11",
    "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ceada1a3a3abbcada7afa28ebda1a3abaaa1a3afa7a0e0ada1a3">[email protected]</a>",
    "members" : [ "M 21",
        "M 22"
      ],
    "name" : "Dep4",
    "parent" : "Dep1"
  }
],
 "orgaTestModel" : { "corporation" : "Corporation Sample",
  "name" : "Orga Sample 7855"
},
"root" : "Dep1"
}

Note: I am utilizing version dojo 1.8.1, but I attempted to run it with dojo 1.9.2 as well without success. If anyone can identify the issue in my code or suggest a solution, I would greatly appreciate it.

Your assistance is highly valued.

Answer №1

You have not shown an example of your original JSON response, but it seems like it may not be valid JSON.

When using dojo.xhrGet with handleAs set to "json", it employs the eval function which is more lenient compared to a strict JSON parser. On the other hand, dojo/request utilizes JSON.parse, expecting well-formed JSON data.

Test one of your JSON responses on - if it does not pass validation there, then it won't work with dojo/request.

(The reason for dojo.xhrGet still using eval despite its potential risks is due to its pre-existing use before widespread adoption of JSON.parse. Updating this would break backwards compatibility and cause issues for developers currently facing challenges like yours.)

Edit: The JSON provided in the question is now considered valid and functions correctly with both the old and new APIs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

It can be challenging to determine whether a variable is set when selections are not calculating correctly

Check out my website at When choosing an option from the drop-down menu for attribute19k, the price value changes. However, selecting other options does not trigger any change. The JavaScript code at the bottom of the source is supposed to calculate and a ...

Incorporating TinyMCE into numerous dynamically generated text areas

I am facing an issue with dynamically created textareas. The content in these textareas is generated dynamically. This is how I retrieve the data and create the textareas dynamically: $(document).ready(function(){ $('#btn').click(function(){ ...

Error message: Cannot establish the attribute 'next' on the string '/:id'

I encountered an error while trying to develop an API for a travel company. The error message "TypeError: Cannot create property 'next' on string '/:id'" keeps popping up, even though all the necessary functions are already created. con ...

Is there a way to access a random element from an array upon pressing a button?

My dilemma involves a reducer array containing Q/A objects that are displayed in two different divs. I want to create a function that will be triggered by the "Next" button, generating a random number to determine which object from the array is displayed n ...

Loop through the input template using ng-repeat with various data types

I have been working on developing a user interface for adding and modifying information in a database. To manage the database, I am utilizing breeze, displaying data using angular grid, and incorporating a ui-bootstrap modal dialog for user interaction. ...

When working in Javascript, make sure to replace newline and carriage return characters in strings with empty spaces. Also, don't forget to replace the literal sequences and

When working with Javascript, I am looking to perform multiple string replacements as outlined below. Remove all newlines and carriage returns Swap out instances of \n with a newline character Change occurrences of \r with a carriage return char ...

Mudblazor - Tap or click within the designated area to trigger the drag and drop functionality

I have incorporated the Mudblazor CSS framework into my Blazor WebAssembly project. Within the drag and drop zone, I have included a button that is supposed to remove each uploaded image. However, when I click on the remove button, it only opens up the fi ...

troubleshooting knockout.js if bindings

It appears that the if binding is not functioning as expected in my case. Below is a snippet of my template: <div> <span data-bind="text: name"></span> <div data-bind="if: false ">+<span data-bind="text: priceFormatted" ...

After generating the token, where is the appropriate place to define the authorization header?

I am currently working on implementing a security system based on tokens. The challenge I am facing is determining the appropriate location to set the authorization header after generating it, in order to validate it across all of my different routes. Belo ...

It appears that my array is not being properly populated by my callback functions

I am encountering an issue with my callback functions. The objective of my code is to send 16 GET requests to a REST API in order to retrieve 16 distinct JSON files. These JSON files are then supposed to be converted into dictionaries representing the foot ...

What is causing the Password Verification code to malfunction when used with a jquery form wizard?

I have implemented a jquery form wizard for my multi-page form. You can view an example of the form structure by visiting . Currently, the form utilizes a jquery validation plugin. However, I noticed that the jquery.validation.js file lacks validation rul ...

Is the model.save() function designed to receive the complete updated JSON response from the server?

There are around 20 attributes available for updating in my model through an HTML form. Upon clicking "Submit", I determine which fields have changed, serialize only those into a data variable, and then execute model.save(data). If the operation is success ...

Utilizing ng-disabled with a custom directive

Is it possible to achieve the following: <directiveName parameter1=value1 parameter2=value2 ng-disabled="true"> </directiveName> I tried this but couldn't get it to work and didn't find many examples of its use. However, I can togg ...

Display loading animation until Google Maps is fully loaded - Utilizing AngularJs

Is there a way to check the readiness of Google Maps before displaying it? I'd like to show a preloader block while the Google Maps is loading. Here is the factory code I am using: var map = false; var myLatlng = new google.maps.LatLng(48.6908333333 ...

Solving the jQuery Context Menu Issue

I created this JQuery script to dynamically modify links generated on my Page (using Ruby on Rails will_paginate) into GET requests that fetch JSON data and update elements on my page. It works perfectly when the links are left-clicked. However, if a right ...

Sorting two distinct lists in parallel using the jQuery sortable feature

I encountered a unique scenario where I had to separate the data into two distinct lists in an html file. Here is what it looked like: <ul id="first_list"> <li ref="1">The quick brown</li> <li ref="2">My father works</li ...

Exploring the integration of Bootstrap Confirmation into an ASP.NET web page

I'm currently working on implementing Bootstrap Confirmation (http://ethaizone.github.io/Bootstrap-Confirmation/#top) on an ASP.NET web page using C#, but I've encountered some issues. Master Page References <asp:ScriptReference Path="Script ...

Display the data labels for the spiderweb graph only when hovering over the line or corresponding legend

I'm currently working on creating a spiderweb chart using the Highcharts guide. One challenge I'm facing is that the data labels are currently enabled by default. I would like to hide the data on load and only display it when the user hovers over ...

Using JavaScript, generate an array of objects that contain unique values by incrementing each value by 1

I have an array of objects called arrlist and a parameter uid If the property value has duplicate values (ignoring null) and the id is not the same as the uid, then autoincrement the value until there are no more duplicate values. How can I achieve the a ...

Exploring ways to enhance the appearance of a Sidebar Widget Navigation using JQuery

When creating navigational items with submenus, such as 'Primary Fees', I added an arrow for visual indication. To enhance user experience, I included an animation that rotates the arrow and highlights the Main Menu item in red upon hovering. Thi ...