Perl is reporting a status of 200, yet jQuery is receiving a parsererror

An issue I am facing is that the Ajax always returns "textStatus: parsererror, errorThrown: SyntaxError: Unexpected token :".

However, the response actually shows as "responseText: {"success":"Search Successful","Timetable":"aaa"},".

I checked on jsonlint.com and it confirmed the JSON validity.

Note that "aaa" was the desired string to be returned. It may have been too long, so I changed it to "aaa", but the error persists.

Below is the Ajax code:


$.ajax({
    type:"Get",
    url:"cgi-bin/timetable.pl",
    contentType:"application/json;charset=utf-8",
    dataType:"jsonp",
    data:"username="+username,
    error:function(XMLHttpRequest,textStatus,errorThrown)
    {
        $('div#result').text(result);
        $('div#result').text("responseText: " + XMLHttpRequest.responseText 
        + ", textStatus: " + textStatus 
        + ", errorThrown: " + errorThrown);
        $('div#result').addClass("error");
    },
    success: function(data)
    {
        if (data.error) 
        {
            $('div#result').text("data.error: " + data.error);
            $('div#result').addClass("error");
        }
        else
        {
            $('div#result').text("data.success: " + data.success 
                + ", data.userid: " + data.clasinfo);
            $('div#result').addClass("success");
        }
    }
})

And here is Perl's:


foreach $classid(@claid)
{
$class->execute($classid);
while (@cinfo = $class->fetchrow_array())
{
    $num = @cinfo;
    $combineinfo = "";
    for ($i=0;$i<$num;$i++)
    {
         $combineinfo .= $cinfo[$i]."V";
    }
}
 push(@info,$combineinfo); 
 }

 $json = (@info)?
 qq{{"success":"Search Successful","Timetable":"'@info"}}:
 qq{{"error":"Search Error"}};


 print $cgi->header(-type => "application/json", -charset => "utf-8");
 print $json;

Answer №1

Stop manually creating JSON and let Perl do the encoding for you.

use JSON::PP;

my $response = (@data)?
    {"success" => "Data Retrieved Successfully", "Results" => @data}:
    {"error" => "Failed to Retrieve Data"};

my $json = JSON::PP->new->allow_nonref;
print $json->encode($response);

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

Using the index of a v-for loop as the value for v-model

I am facing a challenge in setting the index of a v-for loop to a dynamic v-model. I have tried a method that works, but it is not elegant and results in errors in the console: Here is my template section: <div v-for="(ob, index) in $v.especifications ...

Executing a controller function in AngularJS from an event

I am facing an issue with my AngularJS code. I have defined a function within my controller, and I am trying to call it inside an event listener, but I keep getting an 'undefined' error. Here is how the controller code looks like: inputApp.cont ...

Winning opportunities created by using credits in the slot machine

**Greetings, I have created a slot machine using JavaScript, but I am looking to enhance the player's chances based on their credits. Can anyone guide me on how to achieve this? Essentially, I want the player's odds to increase proportionally wit ...

Typescript/Three.js encounters the issue of game objects becoming undefined

Something in my code seems to have broken unexpectedly. I can't figure out why the "Game" object is defined before calling this.render() in the constructor, but becomes undefined in the render method. Before render(), the console shows: Game camera: ...

A guide on invoking a JavaScript function within a dropdown menu based on selection instead of change event

I need to automatically trigger a JavaScript function based on the value pulled from the dropdown options that are populated by a database. Currently, the JavaScript function only runs when I manually select an option on the front-end. Below is my code. I ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Alter a prototype method belonging to another module

If I wanted to create a custom plugin or module that alters the behavior of an object exported in another module, how can I go about modifying one of its methods? The code below illustrates my attempt at achieving this, but it seems like there may be a cru ...

Fuzzy picture utilizing <canvas>

Working on translating a webgame from Flash to HTML5 with pixel art sprites, I've noticed that the canvas appears blurry compared to Flash where pixels are more defined. <!DOCTYPE html> <html> <body> <canvas id="c" style="bor ...

"Enhance your web app with Emotion.js and Preact SSR, complete with

In my preact SSR application, I have utilized Emotion JS 10 for styling purposes. My goal was to incorporate RTL support into the app. To achieve this, I implemented createEmotion and createEmotionServer, leveraging the resulting renderStylesToString to r ...

"Dilemma with Displaying a 3-Digit Number in DaisyUI Using Next.Js Countdown Component

Hey there, I'm encountering an issue with the countdown component on my Next.js website using daisyUI. When the number of days exceeds 99, it's not rendering correctly as shown below: https://i.sstatic.net/cWR2tSEg.png https://i.sstatic.net/V0Iv ...

Despite the presence of data within the array, the React array returns empty when examined using the inspect element tool

Currently, I'm working on creating an array of objects in React. These objects consist of a name and a corresponding color, which is used to represent the pointer on Google Maps. For instance, one object would look like this: {name: "Ben", colour: "gr ...

Save information in an object that has been received through Retrofit

After fetching a JSON file using Retrofit2, I need to extract and store certain data points as objects in an ArrayList. The JSON data includes coordinates for blue cones and yellow cones, and I aim to transform these coordinates into objects and store the ...

The input field malfunctioned after the clear button was pressed

Hi there, I have a question. Every time I try to click on the clear button, it keeps giving me an error message and I'm not sure what the issue is. Also, I can't type in the field anymore after clicking it. methods: { add () { this.ta ...

Is there an easy method for importing, modifying and saving JSON files?

I am encountering issues with editing a JSON file and saving the changes in a usable format. The starting point for my problem is: modify-json-file-using-some-condition-and-create-new-json-file-in-r Even though I am attempting something simpler, it still ...

I encountered an ECONNREFUSED error while attempting to fetch data from a URL using NodeJS on my company-issued computer while connected to the company network. Strangely

After searching through forums and conducting extensive Google searches, I have come across a problem that seems unique to me. No one else has posted about the exact same issue as far as I can tell. The issue at hand is that I am able to successfully make ...

Comparing JSON-RPC with JSON: A Deep Dive

While I am well-versed in creating Restful services using JSON, the term "JSON-RPC" is new to me. After some research, it seems that JSON-RPC is akin to SOAP web services in requiring a defined contract between the requestor and responder. The requestor m ...

Submitting HTML forms in SilverStripe using Ajax

I need to transfer data from a basic HTML form to a controller using Ajax, then handle the data and send a response back. Currently, my setup looks like this: HomePage.ss <form method="POST" class="form-horizontal submit-form" onsubmit="return checkf ...

How to enable CORS in Flask while avoiding the "Response to preflight request does not have an HTTP ok status" issue

Seeking assistance with setting up client-side Javascript code to send post requests to my Flask backend. I referenced this helpful answer regarding an issue with flask-cors being blocked by CORS policy, resulting in a preflight request error without passi ...

node js retrieves information from the request body

Hey there! I'm diving into the world of Node.js and JavaScript, but I've hit a roadblock. I'm trying to fetch data from a URL using node-fetch, then parse it as JSON. However, I keep running into the issue of getting 'undefined' in ...

The issue of Kendo UI Grid failing to display JSON data

I have been struggling with a challenge for some time now regarding the binding of JSON data from my controller action to the Kendo UI Grid. Previously, there were a few JavaScript issues that have since been resolved, but my grid still does not display an ...