AJAX - Query Strings in AJAX

1) What are Query Strings?

  • Query strings are the key-value pairs appended to a URL after a ?.

  • They allow you to pass extra information (parameters) to the server when making a GET request.

  • Multiple parameters are joined with &.

Example URL with query string:

https://example.com/search?keyword=ajax&page=2&sort=asc
  • keyword=ajax

  • page=2

  • sort=asc


2) Query Strings in AJAX (Basic Example)

Using fetch

const keyword = "ajax";
const page = 2;
const url = `/search?keyword=${encodeURIComponent(keyword)}&page=${page}`;

fetch(url)
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

Using XMLHttpRequest

const xhr = new XMLHttpRequest();
xhr.open("GET", "/search?keyword=ajax&page=2", true);
xhr.onload = () => {
  if (xhr.status === 200) {
    console.log(JSON.parse(xhr.responseText));
  }
};
xhr.send();

3) Encoding Query Strings

  • Always use encodeURIComponent() to make sure special characters don’t break the URL.

    const city = "New York"; // has space
    const url = "/weather?city=" + encodeURIComponent(city);
    // becomes: /weather?city=New%20York
    
  • Without encoding, spaces, &, ?, =, or other symbols can cause errors.


4) Building Query Strings Programmatically

With URLSearchParams

const params = new URLSearchParams({
  keyword: "ajax",
  page: 2,
  sort: "asc"
});

fetch("/search?" + params.toString())
  .then(res => res.json())
  .then(data => console.log(data));

Resulting URL:

/search?keyword=ajax&page=2&sort=asc

5) When to Use Query Strings

  • GET requests (read-only, no sensitive data).

  • Filtering, searching, sorting, pagination.

  • Tracking parameters (like utm_source=google).


6) Limitations of Query Strings

  • URL length limit: Different browsers and servers have practical limits (around 2000 characters in many cases). For large data, use POST instead.

  • Not secure: Data in query strings is visible in the browser’s address bar, logs, and caches — never send passwords or sensitive info.

  • Caching: Browsers/proxies may cache GET requests with query strings.


7) Server-Side Access

  • On the backend, you read query strings differently depending on the language:

    • Node.js (Express)req.query.keyword

    • PHP$_GET['keyword']

    • Python (Flask)request.args['keyword']


Summary:
Query strings are a lightweight way to send data with AJAX GET requests. Always encode special characters, keep them for non-sensitive, short parameters, and use POST with a body for bigger or private data.