C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » AJAX

Sending parameters with the AJAX request

In this article, we are going to learn how to pass your variables to the server as parameters by using send method in AJAX?
Submitted by Abhishek Pathak, on October 09, 2017

While back, I have written a simple article on getting started with AJAX. If you have missed it, here is the link, Getting dynamic response with AJAX.

In that post, we have discussed how to set up your first AJAX request. Now, a little more deep, pass your variables to the server. It is easy with JavaScript, just pass parameters with the send method. Here is the code of the basic AJAX structure that we have also learned how it works in previous article?

Code:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if(this.readyState === 4 && this.status === 200)
    alert(this.responseText);
}
xhr.open('GET', '/submit-data.php', true);
xhr.send();

Here, we were sending the xmlHttpRequest object blank. To add parameters, pass the parameters in a nice key value pair as a string. The key value pair might look familiar to you and would render in server as,

www.example.com/submit-data.php?name=John&age=50

These are & separated pairs in the first part is key, acts a variable and other one is value, the value of this variable. So, in similar format, change the xhr.send() method to,

xhr.send('name=John&age=50');

The final code would look like this,

Code:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if(this.readyState === 4 && this.status === 200)
    alert(this.responseText);
}
xhr.open('GET', '/submit-data.php', true);
xhr.send('name=John&age=50');

That's it. It's done. Now you can easily pass parameters with your AJAX request.

If you like this post, share your thoughts below in comments.









COMMENTS