Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Ajax Request in JavaScript

Ajax Request in JavaScript

? AJAX Request in JavaScript

An AJAX request is a way to send data to a server and receive a response without reloading the webpage. JavaScript provides two main ways to make AJAX requests:


? 1. Using XMLHttpRequest (Old Method)

? GET Request Example

function getData() {  const xhr = new XMLHttpRequest();  xhr.open("GET", "data.txt", true); // Request to server file  xhr.onload = function () {    if (xhr.status === 200) {      document.getElementById("output").innerHTML = xhr.responseText;    }  };  xhr.send(); // Send the request}

HTML:

<button onclick="getData()">Load Data</button><div id="output"></div>

? POST Request Example

function postData() {  const xhr = new XMLHttpRequest();  xhr.open("POST", "process.php", true);  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  xhr.onload = function () {    if (xhr.status === 200) {      console.log(xhr.responseText);    }  };  xhr.send("name=John&age=30");}

? 2. Using fetch() (Modern Method)

? GET Request

function getData() {  fetch("data.txt")    .then(response => response.text())    .then(data => {      document.getElementById("output").innerHTML = data;    });}

? POST Request

function postData() {  fetch("process.php", {    method: "POST",    headers: {      "Content-Type": "application/x-www-form-urlencoded"    },    body: "username=JohnDoe"  })  .then(response => response.text())  .then(data => {    console.log(data);  });}

? Request Types in AJAX

TypePurposeExample Use
GETGet dataLoad list, display message
POSTSend dataSubmit form, save user input
PUTUpdate dataUpdate user record
DELETERemove dataDelete a row or item

?? AJAX Request Tips

  • Use GET for simple reads and POST for form submissions.

  • Always handle errors using .catch() (in fetch) or onerror (in XMLHttpRequest).

  • Prefer fetch() for modern applications — it's cleaner and promise-based.


Would you like an example that connects to a PHP/MySQL database or does live search/autocomplete?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql