Encountering a 400 error message (Bad Request) when attempting to send a "POST" request via Ajax to a website built on the

I've been struggling to successfully create a "Post" using ajax. However, every time I attempt to do so, I encounter a "400 (Bad Request)" error. I am unsure whether the issue lies within the Rails website or my ajax request. The Rails setup is just a basic scaffold:

 # POST /events
 # POST /events.json
def create
 @event = Event.new(event_params)
respond_to do |format|
  if @event.save
    format.html { redirect_to @event, notice: 'Event was successfully created.' }
    format.json { render :show, status: :created, location: @event }
  else
    format.html { render :new }
    format.json { render json: @event.errors, status: 409 }
  end
end
end

def event_params
  params.require(:event).permit(:name, :consult, :description, :category, :likes)
end

Here is the Ajax code that I am trying to get to work:

$("button").click(function () {

        $.ajax({
            url: 'http://localhost:3000/events',
            type: 'POST',
            cache: true,
            processData: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: { event: {  name: "testname", consult: 72, description: "this is a test", category: "dance", likes: 23 } },
            success: function (resp) {
                alert(resp);
            }
        });

Answer №1

Kindly update your

url: http://website.com/events to

url: http://website.com/events.json

Once done, inform me of the outcome.

Appreciate it!

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

Activate the jQuery function multiple times

I am currently working on the menu structure for my website <div class="header"> <ul> <li id="menu__lnk_one"><a href="#">Home</a></li> <li><a href="#">Our Story</a></ ...

Retrieving the passed argument variable and utilizing it as a key in a map

I've been working on a JavaScript project recently and I've encountered a situation where I believe my code could be significantly reduced - up to 50% - if I could access the passed arguments to a function and use them as keys. Since I'm sti ...

Proceed to the next request after the initial request has finished executing in node

Imagine there is an endpoint called /print. Each time a request is sent to this endpoint, it triggers the function printSomething(). If another user hits this endpoint while printSomething() is still processing, it will run the function again simultaneousl ...

It appears that ReactJS has a tendency to transform POST requests into GET requests

Currently, I am utilizing React along with the fetch API for a POST request to a user authentication backend. Surprisingly, when testing this POST request using Postman, I receive the correct JWT response. However, an interesting issue arises - when I impl ...

Localhost file not refreshing

I'm feeling quite frustrated at the moment. It seems like such a simple issue, but I can't seem to figure it out. I have created a basic webpage with a "tree-view" structure. In my readjson.js file, I am reading from a json file located in json/ ...

Receiving a JSON response from express.js via a jQuery get request is not functioning as expected

My goal is to send a JSON value from the back end to the front end of my application. Currently, I am using express.js and all post methods are working perfectly. When a button is clicked in the front-end of my application, I want to receive an invoice nu ...

How can one determine the most accurate box-shadow values?

I am trying to extract the precise box-shadow parameters from a CSS style rule generated by the server. My main focus is determining whether the element actually displays a visible shadow or not. There are instances where the shadow rule is set as somethi ...

Incorporating interactive markers onto a mapbox map file

I am in search of a method to incorporate markers onto a map I have designed on a webpage. Below is the code snippet for the page: <link href='//api.tiles.mapbox.com/mapbox.js/v1.3.1/mapbox.css' rel='stylesheet' /> <script s ...

Refresh collection of texts

I am attempting to update an item within a subarray of a document. The type of the subarray is an array of strings: Dictionary.findOne({ name: req.query.name }, function(err1, data){ if(err1){ logger.error(err1); res.send({ ...

Building a Dynamic Search Feature with jQuery, C#, and SQL Server Integration

Trying to implement jQuery autocomplete on dynamically generated textboxes for the first time. ASMX page code is generating results as expected, but facing issues with JavaScript autocomplete functionality. Even after debugging, the script does not call th ...

I'm curious if there is an eslint rule specifically designed to identify and flag any unnecessary spaces between a block comment and the function or

Can anyone help me find a solution to prevent the following issue: /** * This is a comment */ function foo() { ... } I need it to be corrected and formatted like this: /** * This is a comment */ function foo() { ... } ...

Storing data on the server for your Cocos2d JavaScript game

I've been struggling with implementing a savegame option for my cocos2d JavaScript game. After following a tutorial from Ray Wenderlich (thanks, Ray!), I gave up on trying to do it client-side and am now looking into saving XML files to a web server w ...

Executing an ajax post when a user clicks on a link or button

<tr> <td> <span id="id_1"> <a href="/Path" >Name</a> <a href="#">Delete</a> </span> </td> &l ...

What is the best way to extract data from a table and transmit it to the server using AngularJS?

I'm attempting to extract all the content from a table in HTML. Is it possible to retrieve all rows from one side and send them in a post request to the server? I've been struggling to figure out how to do this. Do I need to bind each row using n ...

Difficult exam question that is challenging me

Struggling with a mock exam assignment here - trying to create a conversion program from wind speed in meters per second to watts per hour. I've set up a chart with different ranges of m/s to watts, but for some reason, it's not working as expect ...

After a PHP script is executed, a Bootstrap modal will automatically appear on the same page

Seeking assistance with integrating a bootstrap modal into a contact form submission. Despite multiple attempts, I have been unsuccessful in achieving this integration and now find myself at an impasse. My objective is simple: Upon clicking the submit bu ...

The error message "data.map is not a function" is thrown in the getStatic

I am currently working on a blog project using Strapi in conjunction with Next.js My goal is to create dynamic pages by utilizing [id].js within the pages/posts/[id].js structure However, I've encountered an issue while attempting to map through the ...

Enhance the functionality of a directive by incorporating the ui-mask directive

Recently, I implemented a custom directive for an input field that adds a calendar icon with a datepicker to the input. I have used this directive in various sections of my application and now I am interested in incorporating ui-mask - another directive I ...

communicating between domains - js

Background: My latest project involves creating a web application that can download and display housing prices. The data source can be found at The Initial Plan: I aimed to fetch the data directly from the provided link using javascript, and then conver ...

Transform JSON data into React components using asynchronous AJAX requests

I'm facing an issue when trying to convert JSON data into React components using AJAX requests. The JSON file I am working with is located at "src/data/form-inputs.json". The structure of form-inputs.json is as follows: { "form_inputs": [ { ...