AJAX form not displaying succes or error message

前端 未结 3 1523
忘了有多久
忘了有多久 2021-01-26 07:08

I\'ve asked this question before, but I still didn\'t figure it out. I\'ve made some changes, but I unfortunately still didn\'t get any luck. The form itself works, but it shoul

3条回答
  •  一个人的身影
    2021-01-26 07:16

    Here is how I would do it. I simplified the code for better understanding.

    Option 1: One file (contact.php), one form, no ajax, no onclick event:

    
    
    
    
        
            
            
            
            
    
            Demo
    
            
        
        
    
            
    The email was successfully sent.

    Option 2: Two files, an ajax, an onclick event, no form at all:

    contact.php:

    
    
        
            
            
            
            
    
            Demo
    
            
    
            
        
        
    
            

    send-email.php:

    ' . $error . '
    '; } } elseif ($emailSent) { $response .= '
    The email was successfully sent.
    '; } /* * ================== * Print the response * ================== */ echo $response;

    Optional: Option 1 with client-side validation as well:

    You can validate the form before submission and, if at least one field is not valid (empty value, false email address, etc), you can stop the submission and display a corresponding error message instead:

    
    
    
    
        
            
            
            
            
    
            Demo
    
            
    
            
        
        
    
            
    The email was successfully sent.

    Of course, for option 2, you can achieve such a validation easily, by including the validation code inside the onclick handler, and not running the ajax request if the input is not valid.

    Good luck!

提交回复
热议问题