Answer the question
In order to leave comments, you need to log in
Why can't I make an AJAX request?
Hello colleagues! I recently encountered the following problem:
I have a registration form on my site. I want that after the user has entered a login in the form field, if the username entered by him, then he will receive a message saying that the login is busy. I'm trying to do this with AJAX, but I can't figure out why it doesn't work. An empty string just comes from the server.
The AJAX request processing script is located at the following path in relation to the Js script that sends the AJAX itself - modules/php/check_user_exists.php
Here is the Js itself (I left only the AJAX request for clarity):
var xhr = new XMLHttpRequest();
xhr.open("GET", "modules/php/check_user_exists.php?login=Citizen", true);
xhr.send();
var json = xhr.responseText;
document.write(json); //ничего не выводит
<?php
header("Content-Type:application/json");
include("db_connect.php");
include("form_validation.php");
$login = $_GET["login"];
if(check_user_exists($login)){
$json = array('user_exists'=>true);
echo json_encode($json);
exit;
}
$json = array('user_exists'=>false);
echo json_encode($json);
?>
{"user_exists":true}
Answer the question
In order to leave comments, you need to log in
What are you actually expecting? It shouldn't work like that.
AJAX - Asynchronous Javascript and XML Asynchronous
keyword .
xhr.send(); - the request is gone and you don't know when the response will arrive ,
but you immediately try to read the response
var json = xhr.responseText;
Of course, nothing works.
You need to subscribe to the onreadystatechange event
in it to check the status of the request, and in it to perform the necessary actions on successful / unsuccessful requests.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question