如何在HTML页面上显示PHP的响应

How to display response from PHP on HTML page?

本文关键字:显示 PHP 响应 HTML      更新时间:2023-09-26

我在HTML页面上有一个文本字段和一个按钮。还有一个para标签,它将在验证时显示错误。

如果字段为空,它将被更改为Name must be filled out

并在验证时更改为

现在当我输入一个字符串并按下提交按钮....该值应该传递给PHP页面,并检查条件,并相应地在HTML页面上打印消息…但是当我点击提交的消息是打印在index.php页面本身。

我应该如何使用AJAX代码,使它打印与id错误的para标签上的消息?

请帮助。提前谢谢。

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">    </script>
    <script type="text/javascript" src="java123.js"></script>
  </head>
  <body>
    <form action="index.php" method="post" onsubmit="return validateForm()">
      <input type="text" name="name" id="name">
      <input type="submit">
    </form> 
    <p id="error"></p>
  </body>
</html> 
PHP代码

   <?php
   $name = $_POST['name'];
   if($name == "thistext"){
       $arr = array("sth"=>"hello");
       echo json_encode($arr);
   }else{
       $arr = array("sth"=>"User does not exist");
       echo json_encode($arr);
   }
   ?>
JAVASCRIPT代码

var invalid = 0;
function validateForm() {
/* WHERE SHOULD I PUT THIS CODE
    $.ajax({
      url: "index.php",
      type: "POST",
      dataType: "json",
      success: function(response) {
         $("#error").html(response.sth);
      }
    });
 */
    invalid = 0;
    name = document.getElementById("name").value;
    if(name == ""){
      document.getElementById('error').innerHTML = "Name must be filled out";
      invalid = 1;
    }else{
      document.getElementById('error').innerHTML = "";
    }
    if(invalid != 0){
      return false;
    }else{
      return true;
    }
 }  
 function validateForm() {
    invalid = 0;
    name = document.getElementById("name").value;
    if(name == ""){
        document.getElementById('error').innerHTML = "Name must be filled out";
        invalid = 1;
    }else{
        document.getElementById('error').innerHTML = "";
    }
    if(invalid != 0){
    $.ajax({
    url: "index.php",
    type: "POST",
    dataType: "json",
    success: function(response) {
        $("#error").html(response.sth);
    },
error: function(data){
            console.log("error");
            console.log(data);
        }
    });
    }
    }   

try this

function validateForm() {
    var name = $('name').value;
    if(name == ""){
        $('error').innerHTML = "<b>Name must be filled out</b>";
        // you need to send data also
        $.ajax({
            url: "index.php",
            type: "POST",
            dataType: "json",
            data: { 'name': name },
            success: function(res) {
               // $("#error").html(res.sth);
                console.log(res);
            },  
            error: function(err){
                console.log(err);
            }
        });
    }else{
        $('error').innerHTML = "";
    }
   /* Always return false because this will prevent actual form submit.
      You are submitting form with ajax. 
   */
   return false
}