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>
<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>
$("#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>
Comments