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 : '';
}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.
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';
}
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.