简体   繁体   中英

How to send data to the server via Ajax?

The registration form must be Ajax , to send data to the server via Ajax . When you click the submit appears a spinning gear . If the registration was successful then a message " You have successfully registered " If not occur with the error message " Invalid Email Address " or " username already exists " , etc.

  • We include the jQuery library page
  • JQuery add an event that no longer do submit the form
  • Added an event with jQuery , when making submit to execute ajax
  • Depending on the message came to Ajax , whether to show success or failure

This is all greatly simplified but on the javascript side, you could do this:

var params = {"email": $("input#email")
$.post(yourserver.php, params, validate, "json")

function validate(response) {

  if (response.success) {
    console.log("Allgood")
  } else {
    console.log(response.message)
  }

}

and on the php server side, your server.php could look like this:

<?
  if ( $_REQUEST["email"] ) {
    $response = array("success" => true)
  } else {
    $response = array("success" => false, "message" => "Missing email");
  }

  echo json_encode($response);
?>
function success(answer) {

 $(".loader").hide(); // Hide loader element

 // Back-end side must return 3 numbers, where is
 // 1 - success
 // 2 - invalid email
 // 3 - username already exists

 if (answer === 1) {        // if returned code "1" then output message of success
  console.log("You have successfully registered");
 } else if (answer === 2) { // if returned code "2" then output message of invalid email
  console.log("Invalid Email Address");
 } else if (answer === 3) { // if returned code "3" then output message of username already exists
  console.log("Username already exists");
}

function loading() {
 $(".loader").show(); // Show loader element
}

$("#submit").on("submit", function() {
 $.ajax({
  url: ("/handler"), // url address of your handler
  type: "POST",
  data: ({
   email: $("input#email"),
   login: $("input#login"),
   password: $("input#password")})
  beforeSend: loading, // should call loading() without arguments
  success: success,    // should call success(answer) where answer is result which returned your server
 });
});

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