Last updated on December 17, 2023
Table of Contents
Quick view
Overview
In this tutorial, I am going to show you 2 ways to submit data to server side. This tip will answer for some questions:
- How can submit form using JavaScript?
- How can submit form without reloading a page?
- How can submit form using ajax?
Methods
1. Submit form
As we have already known, when you want to submit a form data on view, we need to implement a HTML page with a <form> tag in it, such as:
<form method="post" action="/users/login"> <input name="sample_data" value="This is a test text" /> <button>Submit</button> </form>
In above example, when user click to Submit button, the form data will send to /users/login route, and in backend function that is set up for this route will receive a post data look like:
Array ( "sample_data" => "This is a test text" )
Okay, so what if we need to send this data to server side without writing HTML page? To do so, we use JavaScript to do it for us. Refer original method in this post https://stackoverflow.com/a/3259946
/** * sends a request to the specified url from a form. this will change the window location. * @param {string} path the path to send the post request to * @param {object} params the paramiters to add to the url * @param {string} [method=post] the method to use on the form */ function formSubmit(path, params, method = 'post') { // The rest of this code assumes you are not using a library. // It can be made less wordy if you use one. const form = document.createElement('form'); form.method = method; form.action = path; for (const key in params) { if (params.hasOwnProperty(key)) { const hiddenField = document.createElement('input'); hiddenField.type = 'hidden'; hiddenField.name = key; hiddenField.value = params[key]; form.appendChild(hiddenField); } } document.body.appendChild(form); form.submit(); }
Explain:
- In JS, we have an API calls document.createElement(); This method helps us to create a HTML element in DOM. So I call this and create a ‘form’ to form variable.
- The form variable now is an element object, so it contains the methods are same as HTML attributes (method, action, class, id…). On next line, we add method and action into this object.
- Next, I do a for to generate the input of this form based on params variable. The content of params should be an object data like:
{ "data_1": "value_1" "data_2": "value_2" "data_3": "value_3" ... }
- After add inputs to forms, we call document.body.appendChild(); method to add our form to view. Then, we submit form by calling form.submit();
- Don’t worry, the form will be added to view and page will submit right away, so our form won’t break your view.
Usage
const url = '/users/login'; const params = { user_id: '135246', type: 'admin' }; formSubmit(url, params, 'POST'); // Backend side Array ( "user_id" => "135246", "type" => "admin" )
2. Ajax call
Come back to Submit form example:
<form method="post" action="/users/login"> <input name="sample_data" value="This is a test text" /> <button>Submit</button> </form>
Submitting a form will make your page reload/refresh and sometimes we want to save data quietly and let the user could continue their browsing data. As everybody know, we will use Ajax such as:
$("button").click(function(){ $.ajax({url: "demo_test.txt", success: function(result){ $("#div1").html(result); }}); });
However, ajax() is an asynchronous HTTP request so we have to use callback() function to handle the return data form backend or API. To me, I usually use ajax in a Promise() to handle callback() functions. It is easier to read my code and easier to debug in future. So, I wrap all ajax call to a Promise (What is Promise?)
Read more: How to write AJAX function in promise
const callAjax = (url, type, data) => { return new Promise((resolve, reject) => { $.ajax({ type, url, data: JSON.stringify(data), datatype: 'json', success: function(response){ resolve(JSON.parse(response)); }, error: function(err) { reject(err); }, fail: function(err) { reject(err); } }); }); }
Usage
const url = '/users/login'; const data = { user_id: '135246', type: 'admin' }; async function anotherFunc() { let result = await callAjax(url, "POST", data); if(result.code === 200) { alert("I am successful to call AJAX"); } else { alert("I failed to call AJAX"); } } // Backend side Array ( "user_id" => "135246", "type" => "admin" )
Comments are closed.