简体   繁体   中英

JavaScript AJAX XMLHttpRequest on "Post" request the call back function "onload" does work

Here I have tried to use AJAX for sending data to server, In server side I have used PHP,I used post request, data gets sent to the server successfully and also sends message to the client side, but on the client side the "onload" call back function doesn't get called. Please Help.

Here the frontend code:

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">

    function postUser() {
      if(validityCheck()) {
          let xhr = new XMLHttpRequest();
              xhr.open("POST", "./api/user/create.php", true);
              xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
              xhr.send(extractFormValues());
            xhr.onload = function() {
                alert("Hi");
            }
      }
      else {
        alert("Please fill the form correctly");
      }

    }

    function validityCheck() {
        if(document.getElementById("name").checkValidity()) {
            if(document.getElementById("age").checkValidity()) {
                return true ;
            }
        }
        else {
            return false ;
        }
    }

    function extractFormValues() {
        let nam = document.getElementById("name").value;
        let age = document.getElementById("age").value;
        let user = {"name":nam,"age":age}
        return (JSON.stringify(user))
    }
</script>
<div>
  <h2>Let AJAX</h2>
    <form method="post">
      <label for="name">Name:</label><br>
      <input type="text" id="name" name="name" required><br>
      <label for="age">Age:</label><br>
      <input type="text" id="age" name="age"><br><br>
      <input type="submit" value="Submit" onclick="postUser()">
    </form>
</div>

</body>
</html>

Here is the server side code in php:

<?php
  // Headers
  header('Access-Control-Allow-Origin: *');
  header('Content-Type: application/json');
  header('Access-Control-Allow-Methods: POST');
  header('Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization,X-Requested-With');

  include_once '../../config/Database.php';
  include_once '../../models/User.php';
  // Instantiate DB & connect
  $database = new Database();
  $db = $database->connect();

  // Instantiate blog post object
  $user = new User($db);

  // Get raw posted data
  $data = json_decode(file_get_contents("php://input"));

// need to check the data is valid or not

  $user->name = $data->name;
  $user->age = $data->age;

  // Create Category
  if($user->create()) {
    echo json_encode(
      array('message' => 'User Created')
    );
  } else {
    echo json_encode(
      array('message' => 'User Not Created')
    );
  }

I have tested the server code using api tester it works fine also gives the response. The only problem is the user gets created but the onload function doesn't gets called.

You have to call onload() before you call send(). It's called after send is called. When you assign it to onload, you're not calling it. You're just defining it so that it's there when XHR needs to call it.

let xhr = new XMLHttpRequest();
          xhr.open("POST", "./api/user/create.php", true);
          xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
          xhr.onload = function() {
                  alert("Hi");
               };
          xhr.send(extractFormValues());

MDN Docs Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM