简体   繁体   中英

PHP and AJAX: How to send/handle error responses?

There are 3 elements to this.

  • An HTML form
  • The AJAX connection which sends the form values and receives and parses response from the PHP script
  • The PHP script which decides whether the values are good/bad or not and sends back an appropriate response (probably in XML format for easy parsing by the javascript function?)

When the PHP looks at and handles the sent data, inserting it into a database or doing whatever with it, it needs to send back a response or maybe a collection of responses so that javascript can display a proper error message(s) to the user. Maybe also putting a red border or something around the elements that have the bad input.

How is this usually done, on both ends? I'm thinking that PHP should just send back simple numeric error codes and javascript will set the proper text error messages in different divs. But I'm not really sure, and I'm not really sure what I should be googling to find an answer.

(BTW I'm not talking about HTTP error codes)

Use this jquery ajax function to post data to php file
Then do whatever with data (send in data base or make some collections ) then echo result that you will catch within success section.
Then put your result in a div or where you want.

$.ajax({           
            type: "POST",  
            url:"scripts/dummy.php",  
            data:"dummyData="+dummyData,

            beforeSend: function()
            {                   

            },
            success: function(resp)
            {               
                $("#resultDiv").html(resp);
            }, 

            complete: function()
            {

            },

            error: function(e)
            {  
            alert('Error: ' + e);  
            }  

    }); //end Ajax

What you are asking is called validation.
There is server side validation, and client side validation.

The first is the most important one, as you don't want users to corrupt your database. The second is important for your customer. As it gives him prompt response about anything that's invalid with the form (red border).

If you want to validate the form client side, it is usually done with Javascript. For server side validation, I would use JSON, as the communication between server and client, as both php and javascript know how to handle it well.

For php:
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php

for JS. just access the result parameter:

   success: function(response){
        var json = $.parseJSON(response.responseText);
   }

Example for Ajax contact form: (Was originally in dutch and it's kinda old and badly coded)

Keep in mind you need jquery for this example. Just download the jquery.js from their website and add it to your scripts in the of your HTML

form.html

<form id="frm_contact" name="contactformulier">
<label>Naam<span style="color:red">*</span></label><br/>
<input type="text" size="15" maxlength="50" name="naam" />
<br/><br/>

<label>Bedrijf</label><br/>
<input type="text" size="15" maxlength="50" name="bedrijf" />
<br/><br/>

<label>Email<span style="color:red">*</span></label><br/>
<input type="text" size="15" maxlength="50" name="tmail" />
<br/><br/>

<label>Bericht<span style="color:red">*</span></label><br/>
<textarea name="tekst">
</textarea>
<br/><br/>
(<span style="color:red">*</span>) Required fields!
<br/><br/>
<div id="subbutton">Send</div>
</form>
<div id="error-msg"></div>

form.html (javascript code)

<script>
$(document).ready(function(){
var err="";
$("#subbut").click(function(){
$.post("PHP/ajax_contact.php", $("#frm_contact").serialize(),
function(data){
switch(data){
case '0':
err="<span><center>Thanks for contacting us!</center></span>";
$("#frm_contact").hide();
break;
case '1':
err="Invalid email!";
break;
case '2':
err="Fill in all fields please!";
break;
case '3':
err="Error sending this mail.";
break;
default:
err="<center>Mail server is offline.</center>"; //Or whatever error
$("#frm_contact").hide();
}
$("#error-msg").html("<br/>"+err+"<br/>");
});
});
});
</script>

PHP/ajax_contact.php

<?php

function check_email_address($email) {
  if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    return true;
}
return false;
}

$naam = trim($_POST['naam']);
$bedrijf = trim($_POST['bedrijf']);
$tmail = trim($_POST['tmail']);
$tekst = trim($_POST['tekst']);
if(isset($naam ) && isset($tmail) && isset($tekst)){
    if(!empty($naam) && !empty($tmail) && !empty($tekst)){
        if(check_email_address($tmail)){
            $to      = 'name@something.com';
            $subject = 'Some subject';
            $message = 'Name: '.$naam.'  ////  Company: '.$bedrijf.'
-------------------------------------------------------
'.$tekst.'
-------------------------------------------------------
Sended on: '.date("F j, Y, g:i a").' - from: www.somthing.com';
            $headers = 'From: '. $tmail . "\r\n" .
                'Reply-To: '. $tmail . "\r\n" .
                'X-Mailer: PHP/' . phpversion();

            mail($to, $subject, $message, $headers);
            echo '0'; //Succes <3
        }else{
            echo '1'; //Invalid mail adres
        }
    }else{
        echo '2'; //Empty fields
    }
}else{
    echo '3'; //Fail post
}

?>

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