The story of introducing Ajax communication to ruby

Ajax communication with jQuery × Server processing with Rails

I would like to make a request via Ajax communication using jQuery code, perform the processing in Rails, and return it in a json format response. Specifically, "When you click the button, a request will be triggered, the set data will be sent to Rails, the response will be received by Kleinant, and the alert and the data sent on the console will be displayed." I would like to try it.

This time, in order to make it easier to understand the client side and the server side, I would like to process without using Erb. Therefore, the extension of the file used this time is as follows.

Client side

Server side

Code required in HTML file

-Code that reads the function that enables jQuery from the jQuery server (introduction of so-called jQuery)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

・ Code to read JavaScript file

<script src="sample.js"></script>

-Button to request to server

<input type="button" id="btn1" value="button">

The source code of html that combines these is as follows.

sample.html


<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>Ajax practice</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="sample.js"></script>
</head>
<body>
  <input type="button" id="btn1" value="button">
</body>
</html>

Code required for JavaScript file

Ajax communication code

I will use $ .ajax this time because of the following differences.

$.ajax You can write the processing when communication succeeds or fails
$.post Only the processing when communication is successful can be written

Parameters

-Specify the destination of the request from the client

url: "/test"

-Set the type of HTTP communication There are GET and POST, but this time POST is used to send the data.

type: "POST"

-Set the data format to receive the response from the server.

dataType: "json"

・ Contents of data sent to the server

data: { user: { name: "foo", age: 25 } }

Method

・ Successful processing

In order to make it easy to see if the communication was successful, the data is displayed in the alert. In Google Chrome, only alert is displayed as "object", so You need to add a special method (JSON.stringify).
done(function(human){
  alert(JSON.stringify(human));
});

・ Processing at the time of failure (optional)

When communication fails, the sent data is displayed on the console. responseText method is a method that can get data during Ajax communication.
fail(function(human){
  console.log(human.responseText);
});

・ Processing that is performed regardless of success or failure

always(function(){
  console.log(human);
});

The code of these jQuery is summarized below.

Supplement After clicking the button with id attribute btn1, perform the following Ajax communication ($ .ajax) -Send user data to / test by POST. -Receive data in JSON format when responding from the server. -When communication is successful, the returned data (variable human) is displayed on the browser as an alert. (.done) -When communication fails, the response data is displayed as a character string on the console. (.fail) -Display the response data on the console regardless of whether the communication succeeds or fails. (.always)

sample.js


$(function(){
  $('#btn1').click(function(){
    $.ajax({
      url: "/test",
      type: "POST",
      dataType: "json",
      data: { user: { name: "foo", age: 25 } }
    })
    .done((human) => {
      alert(JSON.stringify(human))
    })
    .fail((human) => {
      console.log(human.responseText)
    })
    .always((human) => {
      console.log(human)
    });
  });
});

Code required for Rails (server side)

·routing Set the request destination (/ test) described in the js file.

route.rb


Rails.application.routes.draw do
  get "/test", to: 'statics#test'
  post "/test", to: 'statics#test'
end

·controller

Receives the data to be sent described in the js file and returns it to the client in json format as a response. -Receive the sent data {user: {name: "foo", age: 25}} with the variable human -Respond the variable human in json format.

statics_controller.rb


class StaticsController < ApplicationController
  def test
    human = params[:user]
    render :json => human
  end
end

Finally##

Hopefully the display will look like the one below. スクリーンショット 2020-05-25 16.18.45.png

How was it? I think that asynchronous communication will enable light communication and will be a step toward an app that is well known to a large number of people.

However, it tends to be a complicated mechanism for beginners, so I hope you can refer to it.

Recommended Posts