Interacting with my Rails API through JavaScript requests

Exploring the world of Rails and diving into creating a basic rails-api. Currently facing an issue while trying to incorporate user addition to my model using a JavaScript request...

Let's take a look at my HTML file named add-user.html:

<script type="text/javascript" charset="utf-8">
    $(function () {
        $('#adduser').submit(function(e){
            $.post('http://localhost:3000/users', {user: {username: $("#usr").value}, user: {password:$("#psw").value}});
    });
    });
</script>

<form id="adduser" data-ajax="false">
<input type="text" id="usr" placeholder="Username"/>
<input type="password" id="psw"  placeholder="Password"/>
<input type="submit" value="Add User" id="usradd" name="login"/>
</form>

Upon clicking submit, I noticed that $.post() simply appends the data to my URL rather than including it in my model...

Here's a snippet from my users_controller code:

def new
   @user = User.new
   render json: @user
end

def create
@user = User.new(params[:user])

if @user.save
  render json: @user, status: :created, location: @user
else
  render json: @user.errors, status: :unprocessable_entity
end
end

Answer №1

Instead of using $.post, you can simply submit the form by setting the action URL in the form tag itself. Take a look at the example below for reference.

<form action="/users/register" method="post">
        <input type="text" id="username" placeholder="Username"/>
        <input type="password" id="password" placeholder="Password"/>
        <input type="submit" value="Register User" id="registerBtn" name="register"/>
  </form>

Answer №2

Yauhen's solution seems to be the way to go. It's important to note that using the full URL in a POST request like this may not be advisable as you move your code across different environments, such as staging and production. This could lead to complications down the line.

Answer №3

Here is a suggestion to improve your code:

<input type="text" id="usr" placeholder="Username"/>
<input type="password" id="psw"  placeholder="Password"/>
<input type="button" value="Add User" id="usradd" name="login"/>

$(function () {
    $('#usradd').click(function(e){
        var user = {
            username: $("#usr").val(),
            password: $("#psw").val()
        }
        $.post('/users/create', user);
    });
 });

If you are unsure about the '/users/create' route, consider using the rake:routes command to confirm it.

Edit:

In this scenario, omitting the form element could be beneficial.

Edit #2: If a redirect is necessary after creating a user, ajax might not be required. Utilize the form_for rails helper to construct a form for the user model without any javascript code needed.

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

Learn the process of displaying Json in Utf8 format using PHP

Could someone please advise me on how to properly print Json using php? I have the following code that works fine for English language, but when it comes to other languages, the output shows unknown characters like ??????? ??????? ???? ?? - ????? - ?????? ...

Is that file or directory non-existent?

While working on developing a Discord bot, I keep encountering an error message stating: "Line 23: no such file or directory, open 'C:\Users\Owner\Desktop\Limited Bot\Items\Valkyrie_Helm.json']" even though the filep ...

Activate the counter as soon as the error message appears

To effectively track the number of errors generated upon form submission, I require a counter mechanism. The errors are identified by the CSS class .validmissing. For instance, if a user encounters 5 errors upon submitting the form, the counter should be ...

Remove the directory structure from the output when using grunt-concat-json

I have a scenario where my JSON files are stored in the specified path. I am looking to merge them into a single JSON file with keys matching the filename. src/ john/ doe/ one.json two.json three.json If my grunt-concat-json co ...

ReactJS component disappearing behind the Navbar

When using my React app, I have a navigation bar at the top. The Navbar component is called in App.js, and the code snippet below shows how it is implemented. export default function App() { return ( <Router> <Fragment> ...

Troubleshooting a Problem with Binding Knockout Select to JSON Response from Web API in ASP.NET

Hey, I'm in need of some assistance. I've come across what seems to be a simple issue, but for some reason, I just can't seem to figure it out. Here's the situation: I am fetching a list from Web.API using EF public JsonResult Retrie ...

"Navigate back to a previous page in Vue Router without having to

I am currently exploring the option of creating a back button in my Vue.js application using vue-router that mimics the behavior of the browser's native back button. The challenge I'm facing is that when using history mode for the router and tryi ...

How can JavaScript onClick function receive both the name and value?

My current challenge involves a function designed to disable a group of checkboxes if they are not checked. Originally, this function was set to work onClick(), with one argument being passed from the checkbox element. Now, I need this function to be trigg ...

What is the best way to perform an action in the database using JavaScript without needing to refresh the page

I have written a code that retrieves data from a table, with each row containing two buttons for updating the database with a fixed value and deleting the row. I am looking to perform these actions without reloading the page. Below is the table code: &l ...

A step-by-step guide on increasing native Time variables in JavaScript

How can I dynamically and repetitively add time (both hours and minutes) in JavaScript to effectively increment a date object? There are times when I need to add minutes, or hours, or a combination of both - and I want the resulting total time to be return ...

choose a unique jQuery id without any duplicates

Trying to implement a simple system comment feature similar to Facebook, but struggling with selecting the right ID for submission. The issue I'm facing is that the first form works correctly, but for subsequent forms, I always retrieve the data-id fr ...

Incorporating custom HTML5 player to watch Youtube videos on my website

I'm trying to display YouTube videos on my website using a simple video tag. I've managed to retrieve the encoded url of the video from the page source and successfully download it through IDM, but when I try to use this URL as the source for an ...

When provided with varied inputs, new Date() yields distinct values for various time zones

var date1 = "2015-03-29"; console.log(new Date(date1)); //Output:Sun Mar 29 2015 05:30:00 GMT+0530 (India Standard Time) var date2 = "1869-12-31"; console.log(new Date(date2)); //Output:Fri Dec 31 1869 05:53:20 GMT+0553 (India Standard ...

Validating JSON data with REST assured

When it comes to validating Json Objects, I rely on https://code.google.com/p/rest-assured/wiki/Downloads?tm=2. import static com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; import static org.hamcrest.MatcherAssert.asse ...

Combining rows from a joined query in Postgresql and storing them in a new column as an

Can someone help with this (Postgres) query: SELECT p.*, row_to_json(c.*) as "connection" FROM connections c INNER JOIN people p ON p.id = c.connected_to_id WHERE c.entity_id = 1 AND c.entity_table = 'releases' AND c.connected_to_table = ...

The callback function in JavaScript is not updating AngularJS unless it is written in shorthand form

Within an angular controller designed for user login functionality, the code snippets below are extracted from an angular-meteor tutorial: this.login = function() { Meteor.loginWithPassword(this.credentials.email, this.credentials.password, (e ...

Dealing with errors in Express.js within the service or controller layers

Currently, I am developing an Express.js application with a distinct controller layer and service layer. Below you can find the code snippet I have implemented so far: user.service.js exports.registerUser = async function (email, password) { const hash ...

Error 403: ACCESS DENIED - The server comprehended the inquiry, yet declines to carry it out

Encountering a persistent 403 error when making an AJAX call to an API. This issue is specific to Microsoft Edge, while other browsers like IE, Chrome, Firefox, and Safari work without any errors. The page doesn't utilize bootstrap, as there have be ...

Exploring the Dynamic Connection: AngularJS and MongoDB

As someone who is new to MEAN stack, I am currently working on creating a simple one-page application. My goal is to connect to MongoDB and retrieve values from a specific collection using a controller. During my search for an answer, I stumbled upon this ...

Guide to configuring browserify

After installing the modules (browserify, react, reactify), I attempted to process a JSX file using browserify. var React = require("react"); var App = React.createClass({ render: function () { return <h1>111</h1> } }); React ...