J
J
JackShcherbakov2018-04-06 20:41:43
AJAX
JackShcherbakov, 2018-04-06 20:41:43

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); //ничего не выводит

There are no errors in the console. The path is right.
Here is PHP itself:
<?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);
?>

What is wrong and what am I doing wrong?
I express my deep gratitude in advance to everyone who will help
UPD:
If you follow the link modules/php/check_user_exists.php?login=Citizen through the browser, then everything will work fine. Here is the output from the browser:
{"user_exists":true}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2018-04-06
@JackShcherbakov

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 question

Ask a Question

731 491 924 answers to any question