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 :-

Post a Comment

Popular posts from this blog

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

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

SELECT COUNTRY WITH STATE AND IT'S CITIES RAILS

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

Building native extensions. This could take a while... ERROR: Error installing mysql: ERROR: Failed to build gem native extension.

CREATE API FOR USER SIGN UP, LOGIN AND CREATE PUBLISHER WITH CURRENT USER

UPLOAD ANY MEDIA FILE IN RAILS USING PAPERCLIP