Step-by-step guide on sending a JSON object to a web API using Ajax

I have created a form on my website with various fields for user entry and an option to upload a file. After the user fills out the form, my JavaScript function converts the inputs into a JSON file. I am attempting to send this generated JSON data along with the uploaded file to a web service, but I keep encountering an error message that reads:

405 OPTIONS

Below is the Ajax function that I have written. The formData.serializeObject() function helps me convert the form data into a JSON format.

$(function() {
    $('form').submit(function() {
        ($('#file')[0].files[0].name);

        var formData = new FormData($("form")[0]);
        formData.append("filename", $('#file')[0].files[0].name);
        var obj = new FormData();
        
        $.ajax({
            url: "Webserviceurl:port/function_to_send_json",
            type: "POST",
            data: JSON.stringify(formData.serializeObject()),
            dataType: "json",
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            success: function(data) {
                $.ajax({
                    url: "Webserviceurl:port/function_to_send_file",
                    type: "POST",
                    data: obj,
                    contentType: false,
                    success: function(data) {

                    },
                    error: function(data) {
                        console.log("An Error Occurred");
                    }
                });
                return false;
            },
            error: function(data) {
                console.log("An Error Occurred");
            }
        });
    });
});

What could potentially be causing the issue in my code?

Answer №1

The reason for the error message being displayed is due to the fact that a preflighted request is being made. In this scenario, the browser sends an OPTIONS request in order to obtain permission to proceed with a POST request.

Furthermore, the server is responding to the OPTIONS request with a 405 error to signal that "You are unable to send an OPTIONS request to this specific URL!"


However...

data: JSON.stringify(…),

If your intention is to send JSON data, then it's essential to specify the content type as application/json, rather than:

contentType: "application/x-www-form-urlencoded;charset=UTF-8",

It's worth noting that there is no method named serializeObject on formData objects. As a result, calling formData.serializeObject() would trigger an exception.


This particular question addresses how to upload files using Ajax.

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 steps should I take to incorporate this feature into my Meteor project?

After successfully installing the type.js package, I discovered that the code works fine when directly executed in the console. Here is the code snippet: $(function(){ $(".typedelement").typed({ strings: ["You don&apo ...

Why aren't my cookies being successfully created on the frontend of my application when utilizing express-session and Node.js?

Having trouble setting cookies while using express-session in my MERN stack project. When accessing endpoints from frontend localhost:3000 to backend localhost:8080, the cookies do not set properly. However, everything works fine when both frontend and b ...

unable to clear form fields after ajax submission issue persisting

After submitting via ajax, I am having trouble clearing form fields. Any help in checking my code and providing suggestions would be greatly appreciated. Here is the code snippet: jQuery(document).on('click', '.um-message-send:not(.disabled ...

Guide on implementing register helpers with node.js and express handlebars

When loading a record, I have a select option on my form and want to pre-select the saved option. Here is the code: The Student.hbs file displays the form, with the act obj coming from the student.js route student.hbs <form> <div class="for ...

Efficient communication across angular modules on a global scale

Currently, I am working on a project that involves Angular2 with multiple modules. One of the main modules is called BaseModule, and in addition to that, there are two extra modules - FirstModule and SecondModule. Each module has its own routing mechanis ...

Utilize a JSON file to create a dynamic and interactive graph using d3

New to d3.js and looking to implement the line-chart example from: line-chart-example using an external JSON file located in the same folder as index.html. After changing the source to .json, the page displays blank. How should I modify the section to suc ...

Managing consecutive synchronous side effects that are dependent on each other using React hooks

I am currently in the process of transitioning my application from using Redux to the new context and hooks, but I am facing challenges when it comes to handling a series of synchronous side-effects that rely on the response of the previous one. In my exi ...

How can I fetch data from a ManyToMany jointable using Typeorm?

Is there a way to retrieve the categories associated with posts when fetching user data? Data Models: @Entity() export class Category extends BaseEntity { @PrimaryGeneratedColumn() id: string; @Column() name: string; @Column() description: s ...

React: Using Chart.js to visualize negative values with a different color in the area

I am implementing a line chart using Chart.js and react-chartjs-2 to display positive and negative values. For positive values, I want the filled area to be green, and for negative values, I want it to be red. Check out the code here import React from &qu ...

Creating an object with an array of objects as a field in MongoDB: A step-by-step guide

I have a unique schema here: const UniqueExerciseSchema = new Schema({ exerciseTitle: { type: String }, logSet: [{ weight: { type: Number }, sets: { type: Number }, reps: { type: Number }, }], }); After obtaining the da ...

Constructing a new mongoose request without nesting by sending multiple requests

Currently, I am working on an application where I receive a POST request with two variables. I then extract information from three collections based on these variables and use the collected data to make a save request to another collection. The structure o ...

Leaflet.js obscuring visibility of SVG control

I am currently working with Leaflet 0.7.1 and I am looking to create a radial menu (similar to openstreetmap's iD editor) using d3 and display it on top of the map. I have come across some examples that use Leaflet's overlayPane to append the svg ...

performing an AJAX request to the controller method in a Rails application

I am currently facing an issue with making an ajax call to my controller class PatientRecordController < ApplicationController def export .... end end Within my javascript file, the code snippet is as follows: $(document).ready(function(){ ...

Executing Statements in a Specific Order with Express and Sqlite3

I am having an issue creating a table and inserting an item into it using the node command. Despite my efforts to reorganize my script, the item is being inserted before the table is created. Interestingly, manually inputting the commands in sqlite3 works ...

I am facing an issue where using JSON stringify in React Native successfully returns my array, but it is unable to display

Every time I input {alert(JSON.stringify(cart[0]))} in my react-native application, the result displayed is the complete array of objects as shown below: [{ "id": 3, "name": John, . . }] However, when I try {alert(JSON.stringif ...

What is the most effective method for displaying a child modal within a map?

Project link: Check out my project here! I have two key files in my project - App.js and PageFive.js. In App.js, there is an array defined as follows: state = { boxes: [ { cbIndex: "cb1", name: "Bob" }, { cbI ...

Is it possible for an independent perl script to execute a function from a website's javascript?

Looking at this complex setup, I find myself in a situation where I must find a way to trigger the $.ajax function on a webpage using a separate Perl script. The scenario involves a webpage making $.ajax calls to a Perl file, which retrieves data and send ...

When setting up an SQS Event on an S3 Bucket using CloudFormation, the notification destination service region must match the bucket's location constraint to be valid

As I work on creating a cloudformation template that will generate a private bucket and then set up event notification to send a message to a queue whenever an object is created in the bucket, I encounter the following error when running the stack: The no ...

Learn how to smoothly transfer a URL from JavaScript to HTML and initiate the download process

I created a website that solely relies on HTML5, CSS and JavaScript to function. The core functionality of this website involves utilizing YouTube URLs. I have stored the URL of a specific YouTube video as a variable, now I am looking for a way to transfer ...

Trigger the click event of the button that triggered the pop-up when the modal pop-up window is closed

There are two buttons on my page: save and update. When either button is clicked, a pop-up window opens using the Model Pop-up extender, with an "ok" button to close it. What I want is for the function OnClick_save() or OnClick_update() to be called base ...