Example Code of AJAX Request - Coding Cyber

Example Code of AJAX Request

In this step, we will see how to create a Real example of Ajax Request with GET & POST using the input field. We will apply all the techniques learned in the previous steps.

Let’s start it with sending values in URL with GET method.

Submitting AJAX Request with GET Method

Here we will learn to send values in URL with GET and using this values in the PHP file and receiving the response and updating it the HTML document.

We have already created the div element with id ajax, I’m going to use this element to update the content from PHP file.

Other Articles in Learn AJAX

And I’m going to use the ajax.php file we created in previous sections with name variable assigned with GET superglobal.

Inside JavaScript function Ajax, I’m creating a variable with the name or URL. With this url, I’m passing the name value. And I’ll use this variable url in open function.

Here is the code that it looks like

And the entire function code, you can replace it with the previous code.

In the above code, I’m passing a static value in URL, I’ll convert this into submitting values through form input field.

Using Input Field to Submit AJAX Request with GET Method

In this step, we will see how to use the input field to submit values with GET method.

Our code remains same, but we just need to migrate it to work with the input field.

First of all, I’m going to add the input field before the submit button and your code should look like this.

We should get this input fields value after executing the ajax function. We can get this value with the value attribute of the input field.

First I’m finding the input element with id and assigning it to a variable, then with the variable, I’m going to assign the value to a new variable. Finally, we will use this variable nameVal to pass the values.

This the complete code of the ajax function.

In the above code, I’m using GET method. In the next step, we will see it with POST method.

Using Input Field to Submit AJAX Request with POST Method

In this step we are going to submit a request with the POST method, previously we have seen how to submit POST request with values.

For POST request we should change the content type with setRequestHeader function.

Here is the code

We will pass the values with POST method in Send function.

With above code, you should successfully send POST request and the response should be updated inside HTML if you are following from the previous steps.

Now we should make the change to send the values from the input field instead of the manual value.

And the complete code of the Ajax Function

Related Posts
No related posts for this content
Vivek Vengala
 

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: