AJAX for backend integration: asynchronous requests; sending AJAX requests to PHP; real-time search functionality; JSON data exchange with JavaScript and PHP

AJAX lets JavaScript in the browser talk to your PHP in the background: no page reload, so the portal can offer live search and instant updates, exchanging data as JSON.

10 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Search without the reload

The portal's organiser wants to find a registrant by typing their name and seeing matches appear INSTANTLY, letter by letter, with no page reload. A traditional PHP form would reload the whole page on every search: slow and jarring.

You already met the cure in BCA405-01: AJAX, where the browser's JavaScript talks to the server in the BACKGROUND. Back then the server was Node; now it is your PHP. This lesson closes the full-stack loop: a JavaScript front-end, a PHP back-end, and JSON flowing between them, using the prepared statements and json_encode you just learned.

Theory

The AJAX-to-PHP loop

The pattern has 4 steps, spanning both sides of the wire:

1. Browser (JS): an event (typing in the search box) fires a background request to a PHP endpoint, sending the query

2. Server (PHP): reads the input from $_GET/$_POST, runs a PREPARED query on MySQL, and echoes the results as JSON via json_encode

3. Browser (JS): receives the JSON, parses it, and updates the DOM with the matches

4. no page reload happens: only the results area changes

Everything you know converges here: BCA405-01's AJAX, this unit's prepared statements, and json_encode. PHP simply plays the role Node played before.

Practical

search.php: the PHP endpoint returns JSON

<?php
  $db = new mysqli("localhost", "root", "", "portal");
  $q  = $_GET["q"] ?? "";

  // Prepared statement with a LIKE search (still injection-safe)
  $stmt = $db->prepare("SELECT name FROM regs WHERE name LIKE ? LIMIT 10");
  $term = "%" . $q . "%";
  $stmt->bind_param("s", $term);
  $stmt->execute();
  $res = $stmt->get_result();

  $names = [];
  while ($row = $res->fetch_assoc()) {
    $names[] = $row["name"];
  }

  header("Content-Type: application/json");
  echo json_encode($names);   // e.g. ["Riya","Rahul"]
?>

Practical

The browser side (concept; run in a real page)

// As the user types, fetch matches from search.php WITHOUT reloading
function liveSearch(query) {
  fetch("search.php?q=" + encodeURIComponent(query))
    .then(function (response) { return response.json(); })  // parse JSON
    .then(function (names) {
      // names is the array PHP sent, e.g. ["Riya", "Rahul"]
      const list = names.map(function (n) { return "<li>" + n + "</li>"; });
      document.getElementById("results").innerHTML = list.join("");
    });
}
// The page never reloads; only #results changes.

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Quiz

In an AJAX search, what does the PHP endpoint send back to the JavaScript, and how?

  1. A whole new HTML page, which replaces the current one
  2. Just the data (e.g. matching names) as JSON via json_encode, which the JavaScript parses and uses to update part of the page
  3. Nothing: AJAX works entirely in the browser
  4. The raw MySQL connection object
Show the answer

Just the data (e.g. matching names) as JSON via json_encode, which the JavaScript parses and uses to update part of the page

The PHP endpoint returns just the DATA (the matching names) as JSON using json_encode, and the JavaScript parses that JSON and updates only the relevant part of the page (the results list), with no reload: the whole point of AJAX. Option A describes a traditional full-page request, exactly what AJAX avoids. Option C is false: AJAX specifically involves a background request to the SERVER (PHP here). Option D is nonsense: a connection object never leaves the server. The loop is: JS asks, PHP answers with JSON, JS updates the DOM: the same pattern as BCA405-01, now with PHP as the back-end.

Think first

Same loop, third back-end

In BCA405-01 your AJAX live search was answered by Node.js. Now the same front-end pattern is answered by PHP. What does this reveal about how front-end and back-end relate? Then tap.

Show the answer

It reveals that the FRONT-END and BACK-END are DECOUPLED: the browser's JavaScript does not care WHAT language answers, only that it gets JSON back. The identical fetch-and-update code works whether Node, PHP, Python, or any server responds, as long as the response is JSON. This is the core insight of modern web architecture: a clean contract (an HTTP request in, JSON out) lets the two sides evolve independently and be built in different languages. You have now written the SAME live search against 2 different back-ends: proof that once you understand the loop, the back-end language is a swappable detail. That portability is why JSON APIs dominate the web.

Watch out

AJAX-to-PHP traps

Dropping prepared statements: an AJAX endpoint takes user input too; still bind parameters (injection does not care that the request came via AJAX).

Not setting Content-Type: application/json: the browser may misparse the response.

Echoing HTML from user input: escape it; AJAX endpoints are XSS-vulnerable like any page.

Forgetting to encodeURIComponent: special characters in the query break the URL.

Blocking on every keystroke: heavy per-keystroke queries can lag; real apps debounce.

Theory

Scripts work; now, a framework

The portal is now a full-stack app: PHP + MySQL + AJAX + JSON. But it is a pile of individual scripts, and real teams do not build large apps as loose files. They use a FRAMEWORK that enforces structure. The last 2 Unit 3 lessons rebuild the portal on CodeIgniter (CI4), which organises everything into the MVC pattern: Models (data), Views (pages), Controllers (logic), plus routing. From scripts to professional structure.

Summary

Key takeaways

  • AJAX lets browser JavaScript send background requests to your PHP without reloading the page.
  • Loop: JS sends a request, PHP reads input, queries MySQL (prepared), echoes json_encode(results), JS parses and updates the DOM.
  • Use case: real-time search, where results appear as the user types.
  • The PHP endpoint returns just DATA as JSON, not a whole page; only part of the page updates.
  • AJAX endpoints still need prepared statements and output escaping: user input is user input.
  • Front-end and back-end are decoupled: the same JS worked against Node (BCA405-01) and now PHP.
  • Memory hook: JS asks, PHP answers with JSON, the page updates in place.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Database Interaction and CodeIgniter Framework

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

AJAX for backend integration: asynchronous requests; sending AJAX requests to PHP; real-time search functionality; JSON data exchange with JavaScript and PHP · Web Framework and Services (Major-12) · Gri-Learn