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

A guide to locating a dynamic JSON array using the JSON Path Finder tool in Node.js

I am looking to extract some dynamic IDs from a JSON file using the JSON path finder in an npm package. Sample.json [ { "4787843417861749370": [ { "type": "Fast delivery", ...

Resolution for Vue3: Understanding why a component instance's template ref cannot locate a defined function

LoginInfo.vue <script setup lang="ts"> import { rules } from './config/AccountConfig' import { reactive } from 'vue' import { ref } from 'vue'; import { ElForm } from 'element-plus'; const info = reac ...

unable to display loading image prior to upload

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="en"> <head> <title>Unique Prints</title> <meta charset="utf-8"> <meta name="viewport" conte ...

Jackson serializes the subclass by treating its fields as part of the superclass

I am attempting to achieve a specific outcome. class Foo{ public Bar bar; public int f1 = 1; } public class Bar{ public int b1; public int b2; } When serialized to JSON, it currently looks like this: { "bar" : { "b1" : 1, ...

Is there a way to see the default reactions in a browser when keyboard events such as 'tab' keydown occur?

Whenever I press the 'tab' key, the browser switches focus to a different element. I would like to be able to customize the order of focused elements or skip over certain elements when tabbing through a page. While I am aware that I can use preve ...

The onClick event handler is triggered on page load instead of waiting for a click

Recently delving into React, I encountered an issue while attempting to call a function set as a prop. Take a look at my component below: class SamplesInnerLrg extends Component { playSampleAction(sample,sampleId) { console.log(sample); } ...

What is the proper way to add a string to a TypeScript array?

When attempting to add a string to a TypeScript array, I am encountering an error stating 'cannot push to undefined'. Is this the correct approach, or should I be using the spread operator instead? api.ts const api: IConfigName = {name: "getKey ...

What is the best way to strip out a changing segment of text from a string?

let: string str = "a=<random text> a=pattern:<random text (may be fixed length)> a=<random text>"; In the given string above, let's assume that a= and pattern are constants. It is possible that there may or may not be a ...

Guide to dynamically displaying location data using JSON string on Google Maps in ASP.NET

A script is being used to display locations on a Google map: <script type="text/javascript"> $(document).ready(function () { var markersdetails = { "Iran": { "title": "Iran", "lat": "32.000000", ...

What is the best way to incorporate this CodePen snippet into a Vue project?

Can anyone help me figure out how to incorporate this awesome animation from CodePen (link here: https://codepen.io/iprodev/pen/azpWBr) into a Vue project? I've tried implementing it like so: <template> <div> <canvas heigh ...

Designing a nested function within a function encapsulated within a class

Suppose I have a class with a function inside: var myClass = class MyClass() { constructor() {} myFunction(myObj) { function innerFunction() { return JSON.stringify(myObj, null, 2); } return myObj; } } In this scenario, callin ...

Extracting every other value from an array can be achieved by iterating through the

Hi, I'm looking to create a function that will log every other value from an array. For example, if we have: var myArray = [1,45,65,98,321,8578,'orange','onion']; I want the console.log output to be 45, 98, 8578, onion... Does ...

Comparison: executing an immediately invoked function expression (IIFE) and a separate

During my recent refactoring of some legacy code, I stumbled upon the following example: // within another function const isTriggerValid = await (async () => { try { const triggers = await db.any(getTriggerBeforeBook, { param ...

Tips for creating a loading page that displays while your website loads in the background

Is there a way to display a loading animation or image while my website is loading in the background? I've noticed that it takes about a minute for my website to fully load. I attempted to use <meta http-equiv="refresh" content="1000 ...

"Utilize URL parameters to specify a date range when working with Django Rest

In my JSON structure, I have data entries with timestamps and names: [ { "date": "2017-12-17 06:26:53", "name": "ab", }, { "date": "2017-12-20 03:26:53", "name": "ab" }, { "date": "2017-12- ...

The error message from the mongoose plugin is indicating a problem: it seems that the Schema for the model "Appointment" has not been properly registered

I need help troubleshooting a mongoose error that is being thrown. throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model "Appointment". Use mongoose.model(name, schema) I have double-c ...

Issue with two Jquery slider forms

Within a Jquery slider, I have implemented two distinct forms (using this specific Jquery slider: http://tympanus.net/Tutorials/FancySlidingForm/) . My goal now is to establish JavaScript/jQuery validation for these two forms separately BASED on the form ...

Transforming a JavaScript object into a different shape

I need help converting a list of team objects containing team names, reporters, and statuses for each day into date-based objects with all teams and their respective statuses for each date. I attempted the following code snippet but did not achieve the de ...

Varied JSON results within RSpec

Currently, I am in the process of creating RSpec test files for a controller that exclusively responds in JSON format. The primary function of this controller is to serialize a Service object into a JSON object, and so far, this functionality is performing ...

Is it possible for Angular.js to interact with JSTL expression language?

Is it possible for angular.js to interact with JSTL expression language? I am trying to generate ng-options using an array. Here is an example of what I am attempting to accomplish: <select ng-model="detail" ng-init="Categories = '${Categories}& ...