[RUBY] Event firing with JavaScript library JQuery / Ajax (when implementing asynchronous communication)

Premise

--Asynchronous communication

スクリーンショット 2020-10-16 15.09.31.png

Make sure that something is done when the event fires

① What triggered (= what is the event?) ② What kind of place to execute in the wake of the event

Think about the code while thinking about these two things.

"This time, if you press the submit button, the (event) color panel will be added."

(1) I think that pressing the submit button is "when the form is submitted". (2) I think that some steps are required for the color panel to be displayed in the wake of the event. → Use Ajax (data related delivery) → Appearance after change in HTML (partial change in appearance triggered by event firing)

① What triggered (what was the event firing?)

The trigger is to submit the form

Described as "when the button on the form is pressed".

###.js(JavaScript file)


$(function(){
  $(*****).on(*****, function(){

  })
})

Put the class name set in the form in $ () and Add the meaning of pressing with ".on". Enter what to press after on (after "on (,"". This time I added a'submit' button.

<Description example>


$(function(){
  $('.js-form').on('submit', function(){

  })
})

Also, use console.log to check if the event is firing. You can check it by writing it on an empty line and pressing the send button. console.log ("test") Please put it in parentheses. スクリーンショット 2020-10-16 16.15.58.png If not, you should get an error in the verification console.

Next, stop submitting the form with the default settings

As it is, as the default setting, When the form is submitted, the screen changes (screen moves) as before (not asynchronous communication). Normal settings should be blocked. Use preventDefault () for asynchronous communication.

###.js(JavaScript file)



  $(*****).on(*****, function(e){
    e.preventDefault()
  
  })
})

Also in this case, put console.log in the empty line in the middle and check if there is an error.

② What kind of place to execute in the wake of the event

--Use Ajax (data related delivery) --Appearance after change in HTML (partial change in appearance triggered by event firing)

Use Ajax (data related delivery)

Basic code needed after this I added it from "$ .ajax ({") to the previous code.

javascripts/###.js


$(function(){
  $(*****).on(*****, function(e){
    e.preventDefault()
    //Additional description below from here
    $.ajax({
      url:Obtained request URL,  //"Path" in synchronous communication
      type: 'POST',  //"HTTP method" in synchronous communication
      data:Obtained FormData,  
      dataType: 'json',
      processData: false,
      contentType: false
    })
  })
})

↑ Even if you make this description, an error will occur if the view file (〇〇.json.jbuilder) of the transition destination is not created.

From now on, let's look at an example in which the send femme is used as an event.

<Example>


$(function() {
  $('.js-form').on('submit', function(e) {
    e.preventDefault();
    //Additional description below from here
    let formData = new FormData(this);
    let url = $(this).attr('action');
    $.ajax({
      url: url,
      type: "POST",
      data: formData,
      dataType: 'json',
      processData: false,
      contentType: false
    })
  });
});

"Write a description so that you can receive the value entered in the form"

FormData

Used to submit form data. Create FormData by using new FormData (form element). In this case, the argument of the object is this. When this is used in the function set in the event, Refers to the node element where the event occurred. In this case, we are getting the information of the form with the class called js-form. You can also get it by ID.

About Form Data of <Example>


   let formData = new FormData(this);

attr method

You can get the value of the attribute specified in the argument.

<Example> about attr method and url


let url = $(this).attr('action');

In the example,'action' is specified as an argument, so the value of the action attribute of the from element (here this) can be obtained. スクリーンショット 2020-10-16 19.16.40.png

"/ Songs / 3 / songscolors" This path is taken from action and put in the url. I think that url is related to the Ajax url.

Set the options required for asynchronous communication in the "$ .ajax" part

<Example>$.Description from ajax


    $.ajax({
      url: url,
      type: "POST",
      data: formData,
      dataType: 'json',
      processData: false,
      contentType: false
    })
option Contents
type Describe the type of HTTP communication. There are two communication methods, GET and POST.
url Describe the URL to which the request is sent. Transition destination, path
data Describe the value to be sent to the server. This time, the one that stores the data is entered.
dataType Specifies the type of data returned by the server.
processData The default is true. Query string for the object specified in data(Example: msg.txt?b1=%E3%81%8B&b2=%E3%81%8D )The role of converting to.
contentType A header that tells the server the file format of the data. Always set to false when getting form information using FormData. For more detailsHere

Appearance after change in HTML (partial change in appearance triggered by event firing)

The data returned as the result of asynchronous communication (change in the appearance of the browser) is received as the argument of the function of done (function (data) {processing}). Use the done method.

Also, based on the argument () received by the done method, assemble HTML after "function build HTML ~".

javascripts/###.js


$(function(){
  //Add the bottom 5 lines from here
  function buildHTML(***js file name***){
    let html = `<*******>
                </*******>`//`From`HTML is inserted between.
    return html;
  }
  $(*****).on(*****, function(e){
    e.preventDefault()
    let formData = new FormData(this); //This sentence is needed when fetching data from a form.
    let url = $(this).attr('action'); //You need this sentence if you need what is specified for the action of the form.
    $.ajax({
      url:Obtained request URL,  //"Path" in synchronous communication
      type: 'POST',  //"HTTP method" in synchronous communication
      data:Obtained FormData,  
      dataType: 'json',
      processData: false,
      contentType: false
    })
   //Add the following from here
    .done(function(data){
      let html = buildHTML(data);
      $('.***Button class***').prop('disabled', false) //The send button, which cannot be pressed once it is pressed, can be pressed continuously.
      $('***Specify the location you want to add to the original HTML***').prepend(html);//.prepend Adds the content specified by the argument to the beginning of the specified element
    })
  })
})
done method

.when () is the process you want to execute first. .done () is the process you want to execute later. You can set when you want to process like.

$ ('. Button class'). prop ('disabled', false)

In the description that sets the disabled attribute to false, cancel the fact that the submit button cannot be pressed with false.   function buildHTMLL( ){let html = `<></>return html;} Assemble HTML based on the argument () received by the done method. The HTML construction is completely different each time, so I haven't written it here, but I'll take my code as an example.

<Example> Picking up the HTML part


  function buildHTML(songcolor){
    let html =
      `<li class="color-box" style="background-color:${songcolor.color}"></li>`
    return html;
  };

It is very easy to understand if you look at the HTML you want to add with the verification tool, Use $ {} to display database information, It may be easier to understand if you remember that the information brought here was set in the .json.jbuilder created in the corresponding viwe.

prepend method

Decide which part of the original HTML to add by specifying the class etc. Can be added to the beginning of a specified element (class, etc.). There are other methods to add at the end.

By using various methods like this, The text box can be emptied or set after the event.

If it can be implemented by firing an event ...

Imagine if you couldn't do that

javascripts/###.js


$(function(){
  function buildHTML(******){
    let html = `<*******>
                </*******>`
    return html;
  }
  $(*****).on(*****, function(e){
    e.preventDefault()
    let formData = new FormData(this);
    let url = $(this).attr('action');
    $.ajax({
      url:Obtained request URL,
      type: 'POST',
      data: FormData,  
      dataType: 'json',
      processData: false,
      contentType: false
    })
    .done(function(data){
      let html = buildHTML(data);
      $('.******').prop('disabled', false)
      $('******').prepend(html);
    })
   //Add the following from here
    .fail(function(){
      alert('error');
   });
  })
})
fail method

Fail is called instead of done in case of server error.

alert method

An alert is called. The characters inside ('****') are displayed in the alert.             that's all! This is the end of asynchronous communication work. There are many other settings that can be made, so this is not the only option. It ends here once.

One last word

Summarize up to here I could understand the meaning of each description better. However, it is also because I actually developed my own original application. I think it led to this understanding.

New questions and challenges

――I'm worried if I can implement it while remembering the procedure for asynchronous communication. --Assembly HTML that is an argument of done method --Various descriptions after done ――Can the settings after Ajax be applied elsewhere? ――There are things you can do with JavaScript other than asynchronous communication, but what kind of mechanism is it?

Can it be used in the implementation even if it is deeply understood? Also, I would like to learn the parts that I have not yet caught up with.     When I first saw JS, I thought I couldn't read it like this I'm happy that I'm a little used to it now and can see each part.         Thank you for reading to the end! see you~

Recommended Posts

Event firing with JavaScript library JQuery / Ajax (when implementing asynchronous communication)
API (when implementing asynchronous communication)
Timeless search with Rails + JavaScript (jQuery)