Sending data from JavaScript to Perl Dancer framework can be achieved by passing an

Here is the ajax code I'm using to pass values to the dancer framework.

 BookSave: function(data) {
  ### data is an object that contain more than one key value pair
         var book = Book.code;
         $.ajax ({
              type: "GET",
              url : 'textbook/save/' + book + '/' + data,
              success: function(data) {
                  if(data.status == 1) {
                         alert("success");
                  } else {
                        alert("fail");
                  }
             },
          });
    },

In dancer:

any [ 'ajax', 'get' ] => '/save/:book/:data' => sub {
    set serializer => 'JSON';
    my $book = params->{book};
    my $data = params->{data};  ## This I am getting as object object instead of hash
};

Is there a way to send an object from JavaScript and receive it as a hash in Dancer?

Answer №1

Before anything else, it's important to consider using the http PUT or POST verbs instead of GET. Not only is this more semantically correct, but it also allows for the inclusion of complex objects in the http body, such as the 'data' hash (serialized according to my suggestions below).

In my experience, I've encountered some limitations with Dancer's native AJAX methods and a bug that causes issues in certain versions of Firefox. As a workaround, I've opted to serialize and then deserialize the JSON object.

Here are the recommended changes (please note the adjustments made to your routes):

$.ajax ({
    type: "PUT",
    url : '/textbook/' + book,
    data: {
        myhash : JSON.stringify(data)
    },
    dataType: 'json',
    contentType: 'application/json',
    success: function (response) {
        if (response.status == 1) {
            alert("success")
        } else {
           alert("fail")
        }
    }
 })

Additionally, here are the Perl Dancer code modifications:

any [ 'ajax', 'put' ] => '/textbook/:book' => sub {
    set serializer => 'JSON';
    my $book = param('book');
    my $data = from_json(param('myhash'));
};

I have not tested this code extensively, but it should serve as a solid starting point for resolving your issue.

Best of luck with your project!

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 JavaScript/jQuery to tally characters

Here is the code snippet that I am currently working with: PHP <input style="color:red;font-size:12pt;font-style:italic;" readonly="" type="text" name="q22length" size="3" maxlength="3" value="50"/> <textarea onkeydown="textCounter(doc ...

"Clicking on an HTML button triggers a postback action prior to initiating

I am experiencing an issue with my HTML form that is designed to send a "booking" email via AJAX. The form is located within a popup div, and upon submission, I want the form data to be sent to an ashx handler for processing. However, the button on the for ...

Encountered an error while attempting to interpret JSON data

I am currently attempting to utilize JQuery to parse a JSON response: <script> $(document).ready(function() { $("button").click(function() { $.ajax({ url : 'test.php', type : 'GE ...

How to hide an ASP.net panel with JavaScript

I am working on a radioButtonList that contains two items: one with a value of "Yes" and the other with a value of "No." Below the radioButtonList, I have a panel that I would like to show when the "Yes" radiobutton is selected, and hide when the "No" rad ...

Is it possible to automatically click a link using jQuery?

Although this question has been asked countless times before with numerous answers, I am baffled as to why I am unable to autoclick a link upon page load! I have successfully used the same technique over 20 times in the past without encountering any issue ...

Conducting various calculations and showcasing them all on a single webpage

Uncertain about what to name this, but let's see if you understand my question. I have a table on a standard HTML page and I am performing some calculations using Javascript/jQuery. Example: function addThem() { var result; result = userIn ...

Vue has limitations when it comes to applying Template Syntax to buttons

Trying to make sense of the code in my Vue Component. All elements display the template from {{ title }}, except for one lone button that stubbornly shows the template syntax as plain HTML. See Generated Page for reference Snippet of My Code: <templat ...

Listen for the 'open' event on a node HTTP server

This question pertains to a previous inquiry I had about node httpServer encountering the EADDRINUSE error and moving to the next available port. Currently, my code looks like this: var port = 8000; HTTPserver .listen(port, function() { console.lo ...

I must retrieve cookies from the GET call API within the route.js file

I've developed a website using Next.js 13 with a route called /api/users/me. In this route, I need to access the cookies to extract the token. While calling the API from the browser gives me the desired result, trying to call it from the frontend page ...

Unable to maintain checkbox state after page reload in React

I am currently working on creating a to-do list application using React and Material UI. Everything is functioning well except for the checkbox state. I am storing each to-do as an object in an array called todoList in local storage, like this: todoList i ...

Is it possible to load textures in Three.js and Cordova without relying on a server or HTTP?

I am currently working on developing a Cordova game using Three.js with the goal of making it playable offline. However, I have encountered an issue where Three.js requires texture files to be served via HTTP, making it challenging to achieve offline funct ...

Ways to eliminate or conceal solely the play/pause symbol or button from the media player within the video tag

[Please see the screenshot attached, I am looking to remove the play/pause icon that is highlighted] [screenshot] How can I hide or remove only the play/pause button from the media player of a video tag? When I dynamically add the controls attribute using ...

Utilize mongoose-delete to bring back items that have been marked for deletion but are still

Whenever I remove an item from my list, it switches the properties of the data to true, marking it as deleted and moves it to the trash. However, when I try to restore the item from the trash, the deleted properties are no longer available and the data rea ...

Tips for utilizing Ajax and Jquery for redirecting a URL:

I am attempting to redirect a URL upon data submission. Here is the PHP code I am using: <?php $error = array(); $user_id=$_SESSION['email']; $apply_id=$_SESSION['id']; $purpose_amount=$_POST[ ...

The Collada model is displayed in a sleek black hue within the Three.js framework

Exploring the functionality of Three.js has been my recent project. I have a Collada model stored in a dae file and a dedicated Three.js webpage to showcase it. However, upon rendering, the model appears as a black shape without any discernible edges. Desp ...

Discover the power of the Logicify jQuery Location Picker Plugin - Manipulating Location Settings through Code

Having trouble with Logicify's Location Picker plugin for jQuery when trying to set the map location programmatically. This issue has been raised before without a resolution. Check out these links for more information: Logicify Location picker using ...

Uploading images with jQuery ajax and dealing with empty $_FILE variable

I've been facing an issue while trying to upload an image file to the server, as the $_FILE variable always seems to be empty for some reason. Below is the HTML code snippet: <form action='' id='ajax_form' method='pos ...

JavaScript encountered an issue when trying to display HTML content

Through my PHP code, I am attempting to create a popup window that displays the content of an HTML file. However, after adding script tags, no HTML content is displayed. When I tried echoing out $row2, only the word 'array' appeared on the screen ...

"Using AngularJS to display a blank option as preselected in an ng-option

Having an issue with displaying a preselected value as the selected option in my select element. Check out the code below: <select ng-model="data.company" ng-options="company as company.name for company in companies"></select> $scope.compani ...

What is the importance of utilizing clearInterval to restart the timer in ReactJS?

Consider the code snippet provided below: useEffect(() => { const interval = setInterval(() => { setSeconds(seconds => seconds + 1); }, 1000); return () => clearInterval(interval); }, []); What is the purpose of returning ...