Its a fairly common requirement for any blogger to use a form to send data. But most of the time when the form is submitted it opens a page where it sends the data. Today, I will show how to send the form using AJAX without opening a new document page.
So what is AJAX?
AJAX is an acronym for Asynchronous JavaScript and XML. It allows us to send the data asynchronously to the server in the background and making it possible to update the page, without reloading. When the form is submitted an event listener attached to the form element passes the control to a JavaScript function which then proceeds to send data asynchronously using the XMLHttpRequest Object
First, we will design a simple form.
Copy and paste above into the HTML section of the page and it should look like below
Then comes the JavaScript to send the form to the server through AJAX.
Let us design a function to send the data.
You can replace this code above
const xmlhttp = new XMLHttpRequest();
with more browser-specific JavaScript code belowCopy and paste above into the HTML section of the page and it should look like below
Then comes the JavaScript to send the form to the server through AJAX.
Let us design a function to send the data.
The main drawback of the AJAX method, the page where the data is sent should be in the same domain. If it is not on the same domain then it will be blocked by the browsers. You can still do a workaround on this issue which I will tell you later in the article.
AJAX is not supported by all the browsers and there is a different way of implementing AJAX in different browsers. For example, Opera 8.0+, Firefox, Safari, and Chrome will support the new XMLHttpRequest(); but browser like Internet Explorer requires you to use the ActiveX Object for this purpose.
This is the example of the Front end code. You would also require a corresponding code on the server. Depending on the type of server, this can be done in PHP or Active Server Pages or any language available on the server. If it is a third-party API, then there will documentation guiding you with implementing the communication between the AJAX code and the Server.
When AJAX requests are sent to a domain that is not the same as where the page is stored, the requests are blocked by the browser as this causes CORS Issue. Read the below article to correct the CORS issue.
Knowing AJAX can help you make simpler pages that update using the response from the server. It is useful when communicating with various APIs on the internet.
References: You Might Not Need JQuery
No comments:
Post a Comment
Dear Readers,
Your feedback is appreciated. We will reply as soon as possible.
* Spam comments will be deleted.
* Links in comments will change to plain text when published.
* We may not reply to comments posted in a language other than English.