HOW TO CALL RAILS API FROM SIMPLE HTML PAGE.

Calling the rails API from simple HTML page.

Step 1:  Create new form in the HTML page.

index.html.erb

<form action="javascript:void(0)">
  <input type="text" name="first_name" id="first_name">
  <select name="resident" id="resident">
    <option value="">Select</option>
    <option value="true">true</option>
    <option value="false">false</option>
  </select>
  <textarea type="textarea" name="notes" id="notes"></textarea>
  <input type="file" name="image" id="image">
  <button type="button" name="submit" id="form_submit_api">Send Data</button>
</form> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>

Step 2:  Write the script for passing the form data and post the data content to the Controller action using ajax.

<script type="text/javascript">
    $("#form_submit_api").on("click", function(){
      var formData = new FormData();
      formData.append('image', $('input[type=file]')[0].files[0]);
      formData.append('first_name', $("#first_name").val());
      formData.append('resident', $("#resident").val());
      formData.append('notes', $("#notes").val());
      $.ajax({
        type: "POST",
        url: "http://localhost:3000/api/v1/users",
        data: formData, 
        processData: false,
        contentType: false,
        success: function(response) {
          window.location.href = window.location.href;
        },
        error: function(response) {
          alert(response.statusText);
        }    
      }); 
});   
</script>

Now passing the image and other form data in the FormData :-

Comments

Popular posts from this blog

psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

CARRIERWAVE - UPLOAD ANY MEDIA (AUDIO , VIDEO AND IMAGE ) FILE IN RAILS

SELECT COUNTRY WITH STATE AND IT'S CITIES RAILS

RAILS: UPLOADING PHOTOS VIA AMAZON S3 AND PAPERCLIP (UPLOADING FILES TO S3 IN RUBY WITH PAPERCLIP)

SEARCHING USING AJAX IN RAILS

UPLOAD ANY MEDIA FILE IN RAILS USING PAPERCLIP

UNINITIALIZED CONSTANT PAPERCLIP::STORAGE::S3::AWS

CURL COMMAND ON RUBY ON RAILS

CHECK PASSENGER RUBY PATH