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

What are the steps to validate an Ajax form using Dojo JavaScript?

Currently, I am in the process of validating a form that has been written in Javascript/Dojo before sending it via Ajax. Here is the code snippet: <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" type="text/javascript" djConf ...

Ensure NodeJS/JSDom waits for complete rendering before performing scraping operations

I am currently facing an issue with scraping data from a website that requires login credentials. When I try to do this using JSDom/NodeJS, the results are inconsistent compared to using a web browser like Firefox. Specifically, I am unable to locate the l ...

Goodbye.js reliance on lodash

In my search for the most lightweight and speedy jQuery implementation for server-side NodeJs, I've come across Cheerio as the best option. However, I've noticed that Cheerio has a code-size of around 2.6 MB, with approximately 1.4 MB attributed ...

Traverse through an array or object using recursive render functions in JavaScript

Here is an example of the issue I am currently trying to solve: https://codepen.io/wombsplitter/pen/KyWKod This is the structure of my array: [{ //obj 1 link: [{ //obj 2 link: [{ //obj 3 }] }] }] The ...

Switch between two fields using just one animation

I've been experimenting with creating an information tag that slides out from behind a circular picture. To achieve this effect, I created a block and circle to serve as the information field placed behind the image. However, I'm facing a challe ...

Interact with USB drive using electron to both read and write data

I am currently developing an electron project that involves copying files from a computer to USB drives. I need the ability to transfer files and folders to the destination USB drive, as well as determine the amount of free space on the drive. I have expe ...

Can you show me how to use jQuery/JS to split this string into two separate arrays?

Can you help me separate this string into two arrays? { array1: [ 'mary', 'steve', 'george' ], array2: [ 'dog', 'cat', 'hobbit' ] } I attempted the following code but encountered a syntax err ...

The type 'true | CallableFunction' does not have any callable constituents

The error message in full: This expression is not callable. No constituent of type 'true | CallableFunction' is callable Here is the portion of code causing the error: public static base( text, callB: boolean | CallableFunction = false ...

Highcharts: Limiting the yAxis values to a maximum of two decimal places

Here is the code for my graph, which retrieves data from a PHP page and adds some series: $('#grafico_1').highcharts({ chart: { type: 'line', zoomType: 'xy', animation : false, events: { selection: functi ...

What are the steps to transform an object containing arrays into strings and then embed them into my HTML code?

Here is the code I need to add to my errors array and send the values to my HTML client-side template: { "email": [ "user with this email already exists." ] } I am looking for something like this: "user with t ...

What is the proper method for implementing respond_to with JSON data?

I find myself in a bit of a dilemma: I'm currently developing a centralized controller based on the guidance provided in this query and am encountering some confusion regarding the functionality of the respond_to method. In an API::Controller, my cod ...

Using the @ symbol in jQuery within an MVC framework can be achieved by first ensuring that

I'm attempting to incorporate the @ symbol into a JavaScript if condition, but I keep receiving an error. if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) { alert('yes'); ...

Update the text on a button using a different button

function modify_button_text(){ //update the word from cat to dog. } <button id="button_1_id" >Cat</button> <br><br><br><br> <button id="modify_button_text_btn" >Change the Text of Above Button</button> ...

Alignment issue with procedural plane vertices in threeJS

In my project, I am utilizing threeJS along with a Simplex noise algorithm to create a tile system consisting of 50x50 planes. Currently, I am iterating through x+y and adding each plane. The Simplex noise algorithm is then used to calculate the z position ...

How can I create a JSON response in ServiceStack that includes only the primary key?

After creating a new record in my table, I want to generate a JSON response that includes only the primary ID of the newly created record. For example: {"PrimaryID": 123} Currently, I am using the following custom function: // Adds a new row to the P ...

What is the best way to transform a nested JSON within another JSON into an object?

There was a guy I received { "lng_x": "106.883368", "style": "{\"name\":\"TACTICAL\"}" } Whom I wanted to transform into this individual public class Root { public str ...

Difficulty with Ajax post function in CodeIgniter

I am currently working with CodeIgniter version 3.1. When attempting to use Ajax post, I encountered a 403 (Forbidden) error in the console. [POST http://localhost/test/post 403 (Forbidden)] HTML <div class="post"> <input type ...

When using getStaticPaths, an error is thrown stating "TypeError: segment.replace is not a function."

I am a beginner when it comes to using Next.js's getStaticPaths and I recently encountered an error that has left me feeling lost. Below is the code I have written (using query from serverless-mysql): export async function getStaticPaths() { cons ...

Utilize external functions in evaluated code

After working with a TypeScript file containing the following code: import { functionTest } from './function_test' function runnerFunctionTest() { console.log("Test"); } export class Runner { run(source : string) { eva ...

Ways to execute a JavaScript function upon a button click instead of during the page load completion

I searched on Google but couldn't find the answer, so I'm asking here for help. In the attached screenshot located at the end, when the user clicks on the download button, some backend actions are performed such as file transfer. Once the proces ...