Send GET Requests with AJAX and PHP

Send a GET request with fetch()

Use URLSearchParams to encode the name before sending it to PHP. The endpoint reads the same txt parameter used by the live example below.

async function sendName(name) {
  const params = new URLSearchParams({ txt: name });
  const response = await fetch(`ajax-get-testck.php?${params.toString()}`);
  const text = await response.text();
  document.getElementById('ajax-get-output').value = response.ok ? text : '';
}
Name:
Output:

Enter your name to send a GET request and display the server response.

The browser sends the value in the txt query parameter to ajax-get-testck.php. The PHP endpoint validates the value, then returns a short plain-text response. See GET form data in PHP for more about $_GET and XMLHttpRequest for the request-object API used below.

The XMLHttpRequest example performs the same request as the fetch() example: build an encoded query string, send the request, wait for a successful response, and place the returned text in the output field.
<script>
function ajaxFunction(str) {
  const httpxml = new XMLHttpRequest();
  const params = new URLSearchParams({ txt: str });

  httpxml.onreadystatechange = function () {
    if (httpxml.readyState === 4 && httpxml.status >= 200 && httpxml.status < 300) {
      document.getElementById('ajax-get-output').value = httpxml.responseText;
    }
  };

  httpxml.open('GET', 'ajax-get-testck.php?' + params.toString(), true);
  httpxml.send();
}
</script>
At the server end we have the file ajax-get-testck.php, check this line
var url="ajax-get-testck.php";
The code inside the file ajax-get-testck.php is here.
<?php
header('Content-Type: text/plain; charset=UTF-8');

$in = trim((string)($_GET['txt'] ?? ''));

if ($in === '') {
    http_response_code(400);
    echo 'Enter a name';
} elseif (strlen($in) >= 20) {
    http_response_code(400);
    echo 'Too Long Data';
} else {
    echo $in . ' Welcome';
}
?>




Ajax XML


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer