An error was encountered in the JSON syntax: Unexpected symbol <

I have encountered a problem with my code that I cannot seem to resolve. Despite the JSON data being successfully sent to the backend and processed correctly, the success function of the call is never triggered.

Here is the snippet of my function:

RegistrationForm.prototype.sendCode = function(url, error) {

    if (accessCode){
      return $.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify({"vouchercode": accessCode}),
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function(data){
          //success case here. never fires
        },
        error: function(xhr, ajaxOptions, err, error){
            console.log(err);
            console.log(accessCode);
        }
      });
 }

Upon logging the error in the AJAX error function, I receive the following message: SyntaxError: Unexpected token <

Answer №1

The response contains data that is not valid JSON and may include HTML or XML due to the presence of '<'. This could be a default error page generated by the server for internal errors.

You can view the returned data in most browsers by using developer tools. In Chrome, you can press F12 and go to the "Network" tab.

Answer №2

contentType is the type of data expected from the server. If you specify JSON as the expected data but receive HTML instead, an error will occur.

To fix this issue, set contentType to either html or text.

Answer №3

Upon encountering the error message, it indicates that the response is in html format. To rectify this issue, simply delete dataType: 'json' from the code snippet. This adjustment will prompt jQuery to interpret the content as html, resolving the problem.

Alternatively, adhere to the steps below:

If you are indeed delivering a json response, it is probable that it is structured within the following format:

<pre>{json here}</pre>

In this case, eliminate the dataType: 'json' line and make the following adjustments within the success handler:

success: function(data){
   var obj = JSON.parse($(data).text());
}

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

Sending an AJAX request to a REST service in order to submit the information captured in an HTML form

<html> <body> <form method="POST"> <label>username</lable> <input id="username" name="username" type="text"> <label>emailid</lable> <input id="emailid" ...

Please consider opening in a new tab rather than a new window

<a href='#' onclick="loadpage();">[RANDOM PAGE]</a> Whenever this code is clicked, the following function gets executed. function loadpage(){ $.ajax ({ type: "POST", url: "fetchpage.php", data: "showpage=1", success: function(msg) { ...

The React application is experiencing difficulties in receiving the response data (JSON) from the Express server, despite the fact that

When making POST or GET requests to our Express server, served through PM2 on EC2, Postman receives the complete response with JSON data. However, our front end React app (both locally and deployed via CF) only gets the response status code and message. Th ...

The visibility attribute of a Primefaces 3.5 dialog is properly updated following an ajax event that triggers its closure

A possible solution can be found here. (This involves showing and hiding the dialog from within the bean.) I have a dialog box with show/hide buttons that are working fine. The dialog reads a boolean value from the backing bean and updates its visibility ...

Combining JSON and PHP for seamless integration

I am utilizing the getJson() function to dynamically fetch content from the server using PHP. Here is an example of the code: function loadContent(url){ $.getJSON("content.php", {cid: url, format: 'json'}, function(json) { ...

The Vue.js Vuetify.js error message is saying "A mystery custom element: <v-list-item>, <v-list-item-title> - Have you properly registered the component?"

I followed the instructions from Vuetify Data Iterator Filter section I am able to use various Vuetify components like v-btn, v-card, v-data-table, v-data-iterator, and more. However, I encountered errors only with <v-list-item> and <v-list-item ...

Transforming objects into JSON format using C#

I have a class: public class CustomerStatistics { public string data { get; set; } public string xkey {get;set;} public Array ykey {get;set;} public Array labels {get;set;} } How can I achieve JSON output like this? { "data":[ ...

The Vue JS Router is prominently displayed in the center of the webpage

I have been delving into Vue JS and working on constructing an app. I've implemented vue router, however, it seems to be causing the content within the routed component to display with excessive margins/padding. I've attempted various solutions s ...

Tips for updating form tag details within the same blade file upon reloading

I have set up a payment page that displays the total amount to be paid. To facilitate payments through a 3rd party gateway, I have utilized a form tag on the page. Now, I am looking to integrate a promo code feature on this payment page so that the total a ...

What could be the reason behind the occurrence of Content-Length=0 for jQuery AJAX POST requests in the IE 11 browser without

I've been developing a Spring MVC based web application. Here are the details of my environment :- Java 1.8.0_162 (64 bit), Spring 4.3.1, Apache Tomcat 8.0.49, Waffle-1.8.3 for SSO, jquery-1.11.3 and Google Charts API. I have included the following ...

Experiencing a result of NaN following a mathematical operation on variables

While working with an array obtained from a JSON response, I am encountering NaN after performing addition operations. var a = new Array(); var b = 0; var c = 0; alert(b); for (var x = 0; x < length; x++) { a[x] = response.data[x] } for (var i = 0; ...

Struggling to properly structure WCF JSON data for HighCharts integration?

I am having issues binding my WCF JSON data to HighCharts Pie. When I hardcode the data, it works fine but dynamic data processing does not seem to work. Original from WCF -[{"AllRecordsUrl":"http:\/\/EMS\/sites\/IST\/report.aspx ...

The options for answering (True, False, Yes, and No) are not currently visible

I am struggling with displaying buttons for "True", "False", "Yes", and "No" in an appended row. Here is the application: Application To use the application, follow these steps: 1. Open the application and click on the green plus button. A modal window ...

What is the best method for styling arrays displayed by React in version 15 using CSS?

React v15 has made a change where elements of arrays in JSX are now rendered as <!--react-text:some_id-->text<!--/react-text--> instead of spans. I've searched for a solution but haven't been able to figure out how to apply CSS styles ...

Angular JS appears to be causing the DOM to freeze up while utilizing the ng-repeat directive to loop through

I have a current app where clicking a button triggers an $http request to fetch and return some data. The retrieved information is then used to update the $scope variables rows and columns, which are then looped through using ng-repeat. However, I've ...

`I'm having issues trying to use ajax and load simultaneously``

Can anyone help me figure out why my AJAX call to sessions.php is not correctly loading and returning true or false each time a user accesses the page? var section = $("#header a"); section.on('click', function() { $.ajax({ type: "PO ...

What steps should I follow to ensure that the message "Read It" is logged to the console before "Ex It"?

app.get('/', async (req, res) => { await fs.readFile('./views/website/index.html', 'utf8', (err, d) => { data = d console.log("Successfully read the file") // console.log(data) ...

Utilizing Codeigniter with the magic of jQuery AJAX

After logging in, I want to use AJAX to call the controller in CodeIgniter. However, when I try to execute it, the login page only gets refreshed and the AJAX URL does not call the controller function in CodeIgniter. I am confused about what is happening. ...

Display loading spinner and lock the page while a request is being processed via AJAX

Currently, I am working on a project using MVC in C#, along with Bootstrap and FontAwesome. The main objective of my project is to display a spinner and disable the page while waiting for an ajax request. Up until now, I have been able to achieve this go ...

Find the HTML elements within an XDocument that need to be replaced and converted into Json format

XML contains HTML tags that need to be removed using XDocument. Is there a way to identify nodes with HTML tags and replace them throughout the entire document? Below is a sample of the XML structure: <?xml version="1.0" encoding="utf-8"?> <myFie ...