Struggling to get your HTML to Express app Ajax post request up and running?

I’m currently in the process of creating a Node Express application designed for storing recipes. Through a ‘new recipe’ HTML form, users have the ability to input as many ingredients as necessary. These ingredients are then dynamically displayed using jQuery and stored within an ‘ingredients’ array. Due to limitations with sending arrays via HTTP, I am attempting to send a new recipe object through an AJAX post request. While my experience with AJAX is somewhat limited, I am struggling to understand why the post request isn’t functioning as expected. Below is the front-end jQuery code:

script type="text/javascript">
    //$(document).ready(() => alert("Jquery works!"));
    $(document).ready(() => {
        $("#addIngBtn").click(() => {
            let ingredient = $("#ingredient").val();
            let quantity = $("#quantity").val();
            $("#ingredient").val(""); //reset ingredient input
            $("#quantity").val("");
            $("ul").append(
                "<li>" + ingredient + " - " + quantity + "</li>"
            );
        });
    })

    $("#newRecipeForm").submit(() => {
        event.preventDefault();
        var ingredients = [];
        $("#ingredientListUL li").each((index, element) =>
            ingredients.push($(element).text())
        )
        var recipe = {
            name: $("#name").val(),
            image: $("#image").val(),
            oneLiner: $("#oneLiner").val(),
            method: $("#method").val(),
            ingredients: ingredients
        }
        $.ajax({
            url: "/recipes",
            type: "POST",
            dataType: "json",
            data: recipe,
            contentType: "application/json",
            complete: function () {
                console.log("process complete");
            },
            success: function (data) {
                console.log(data);
                console.log("process success");
            },
            error: function () {
                console.log(err);
            }
        })

    })

In terms of back-end development:

// note this is located within the router file where the default route "/" equates to "/recipes"
router.post("/", (req, res) => {
    console.log(req.body.recipe);

})

What could potentially be causing these issues? Any insights would be greatly appreciated.

Answer №1

I may not be a pro in this field, but it seems like the information you're transmitting is missing the recipe key. You might want to check your backend for any issues.

router.post("/", (req, res) => { 
    console.log(req.body.name); 
}) 

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

External JavaScript file not executing defined function

My homepage includes a register form that should open when the register button is clicked. However, I am encountering an issue where the function responsible for opening the form from another JavaScript file is not being triggered. Here is the HTML code: ...

Troubleshooting: Ruby on Rails and Bootstrap dropdown issue

Having some issues with implementing the bootstrap dropdown functionality in my Ruby on Rails application's navigation bar. I have made sure to include all necessary JavaScript files. Below is the code snippet: <div class="dropdown-toggle" d ...

Storing progress of a multi-step form in Laravel 5.6 on both the database and local drive

I've been working on implementing a multi-step form using JQuery Steps in Laravel 5.6. Instead of just saving all the data at the end, I want to save each step of the form in the MySQL database and on the user's local drive. This way, I can track ...

Issue with Jquery change event not functioning as expected

My webpage consists of the following HTML code: <form id="fileuploadform"> <input type="file" id="fileupload" name="fileupload" /> </form> Accompanied by this snippet of jQuery code: $(':file').change(function(){ var ...

Utilize Npm.depends to declare the test's dependency

Is there a way to specifically declare a dependency on an Npm module in Meteor only for testing purposes? During the testing of a package, it is simple to declare an Npm dependency in package.js through the following code: Npm.depends({ ... 'sin ...

What causes the index link to break when react-router's setRouteLeaveHook is used?

Issue: Whenever I include router.setRouteLeaveHook() or router.listenBefore() in my component, it causes the logo homepage Link to path="/" to break Scenario: I am attempting to implement a confirmation prompt before leaving a section. Below is the code f ...

Determining when a text area has selected text without constant checking

class MarkdownEditor extends React.Component { constructor(props) { super(props); this.timer = null; this.startIndex = null; this.endIndex = null; } componentDidMount() { this.timer = setInterval(() => { this.setSelectio ...

When clicked, verify whether the div is already open. If it is closed, open it using the .show method. If it is already

Currently, I am utilizing the jquery .show method to reveal a hidden div. While it is functioning as intended, I am grappling with how to implement a check to see if the div is already visible. If it is, I do not want the .show action to be repeated unnece ...

The node app's response fails to provide any data, even though it is expected to return

I'm currently running a nodeJS server using the express framework. When sending a request to the server, it should respond with data in an array format. However, instead of receiving the expected data, I am getting ''. The specific test I& ...

Replacing CSS conditional statements with jQuery

My CSS code is set to hide the #global-widget-base tag and display a tab #aside-expander when the browser width is less than 1200px. @media screen and (max-width: 1200px) { aside#global-widget-base { display: none !important; } #aside- ...

Deactivating a form field depending on a selected radio button in Angular 2

If I have two radio buttons, with a click function called localClick for the first button to give value 1 and the second button to give value 2. <div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"&g ...

What are the advantages of using npm-ci in a developer's NPM workflow?

My team consists of about 10 developers working on a sizable project. We ensure package.json and the resulting package-lock.json are committed, with our continuous integration pipeline running npm ci to restore packages based on package-lock.json. Current ...

I'm having trouble retrieving the request body in Postman

I am currently working on a controller function along with an endpoint: controller uploadSalesOrderFromExcel : async function (req,res) { console.log(req.body); if (!req.body.branchId) { return res.status(400).send({ Error: "B ...

Express.js and gridfs-stream are unable to retrieve the error

Imagine an effortless image download server where Express.js takes the request, fetches an image from MongoDB GridFS, and serves it as a response. Everything works fine when the request is valid and the file exists. The issue arises when it fails to catc ...

Using PHP and Ajax to upload substantial data through Ajax (413 HTTP Code)

After dedicating a solid 48 hours to resolving this issue, I've hit a point of desperation. The problem arises when attempting to upload file content via Ajax, resulting in a "Request Entity Too Large" error code. My server is Apache-based and while I ...

JSON AJAX script is failing to capture the data inputted into the form field

I am struggling to retrieve the $productid from the form. Not sure what I'm missing here. Any suggestions? The selected files do get uploaded, but not to the specified product folder, and there is no indication of success returned to index.php It&ap ...

Utilizing jQuery to Record the Status of HTML5 Forms

Can jQuery be used to track the status of an HTML5 form element? For instance, if a user enters an invalid email address in the email field, can jQuery detect this event and take action such as disabling the submit button until a valid email is entered? ...

Is there a way to achieve a similar effect to "object-fit: cover" for CylinderGeometry in three.js while utilizing THREE.VideoTexture()?

I'm really interested in creating something similar to this: https://i.sstatic.net/mWuDM.png Imagine the checkered background as a texture, and I want the jar to be a cylinder with that texture applied to it. My knowledge of three.js is limited, so ...

User interaction with a checkbox triggers a state change in Angular

Here is the code snippet I am working with, where clicking should set the checked value to false: @Component({ template: ` <input type="checkbox" [checked]="checked" (change)="onChange()"> ` }) export class AppC ...

How can I use `app.js` in Zendesk to connect to an external API using the complete URL

As someone new to developing Zendesk apps, I've been following the step-by-step guide available here. To Summarize I'm facing an issue with passing external API URLs to the AJAX call syntax within Zendesk's app.js file. You can find my sim ...