I've created a form using a bit of jquery, ajax and php. The ajax, validation and php processing works well. I came up with the following code to hide my form after submitting, but I don't know if this is the good way to do that. I would like your advise.
Below the js script with the ajax call
<script type="text/javascript">
$(document).ready(function(){
$("#submitContact").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'form/process.php',
data: $("#contact_form").serialize(),
success: function(response) {
$("#formstatus").hide().html(response).slideToggle(600);
}
});
});
});
</script>
The above code will call the php to validate and populates the div#formstatus to notify the user if the form is sent or not.
Within my process.php, I will hide the form if there are no errors found using echo js script.
// If no errors found echo succes message
if (!($formerrors)) :
//Hide the form
echo '<script type="text/javascript">
$(document).ready(function(){
$("#contact_form").hide();
});
</script>';
// display success message
echo '<div>
Your message has been sent. <br />
Thank you for contacting us!
</div>';
Etc....
To sum up:
Should I use this method to hide my form? (Because it does work)
Note. I'm new to jquery and ajax :)
I think it would be better to return a JSON object which contains the information relevant to the request.
For example:
if (!($formerrors)){
echo json_encode(array(
'success'=> true,
'message'=> 'Your message has been sent. <br> Thank you for contacting us!'
));
}
else{
echo json_encode(array(
'success'=> false,
'message'=> 'Error processing form',
'errors'=> array(
'phone'> 'A phone number is required'
)
));
}
This will be easy to work with on the client side (jQuery will automatically parse the json)
<script type="text/javascript">
$(document).ready(function(){
$("#submitContact").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'form/process.php',
data: $("#contact_form").serialize(),
success: function(response) {
if(response.success){
$("#formstatus").hide().text(response.message).slideToggle(600);
}
else{
jQuery.each(response.errors,function(){ ... });
}
}
});
});
});
I think you'll find you have more manageable code if you separate display concerns from functional concerns. For php I agree with Walkerneo.
Javascript AJAX Success Handler
success: function(response) {
var response = $.parseJSON(response);
if(response.status === 'true') {
$("#formstatus").hide().html(response.message).slideToggle(600);
$("#contact_form").hide();
} else {
$("#formstatus").hide().html(response.message).slideToggle(600);
}
}
PHP
if(!$formerrors) {
exit(json_encode(array('status' => 'true', 'message' => 'Your message has been sent.
Thank you for contacting us!')));
} else {
$message = '<p class="error">' . implode('</p><p>', $formerrors) . '</p>';
exit(json_encode(array('status' => 'false', 'message' => $message)));
}
I recommend avoiding this method. You should instead return information about the status and message to display to the user. For example, here's how you can do it without reloading the page.
We prevent the default event, so that the page doesn't reload. Because of the below HTML changes, we also can make or code more general.
$('form').submit(function(e){
e.preventDefault();
var $this = $(this);
$.ajax({
cache: false,
type: 'POST',
url: 'URLHERE',
data: $(this).serialize(),
dataType: 'jsonp',
success: function(response) {
We display the error or success message here. Depending on the status
field, we make the text green or red, and decide whether to hide the form or not.
$("#formstatus").hide().text(response.msg).show(600);
if (response.status === "success") {
$this.hide();
$("#formstatus").css({color: "green"});
}
else {
$("#formstatus").css({color: "red"});
}
}
});
return false;
});
Our PHP simply returns a JSON object.
function callback($data){
$json = json_encode($data);
return $json;
}
if ($valid === true) {
echo callback(
array(
"msg" => "Your message has been sent.
Thank you for contacting us!",
"status" => "success"
)
);
}
else {
echo callback(
array(
"msg" => "Please fill in all fields.",
"status" => "error"
)
);
}
The HTML is also changed to use a submit button, which allows us to target the form instead of the button. The code may now be transported more easily.
<div id="formstatus"></div>
<form>
<input placeholder="First Name" name="name">
<input placeholder="Email" name="email">
<input placeholder="Comment" name="comment">
<input type="submit">
</form>