Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

Displayindividual error messages for each text field using php validation with jquery and ajax

I got a lot of valuable help via live help here on EE last night, but I am still having a hard time trying to figure out how to display individual error messages.

In PHP only I would do something like this (just using empty() for simplicity, would normally use preg_match() )

$message = "";

if(empty($_POST['first_name'])) {

$message .= "First name required <br/>";

}

if(empty($_POST['last_name'])) {

$message .= "Last name required <br/>";

}

if($message) {

echo "<div class='alert alert-danger'>There are errors in your form: <br/>" . $message . "</div>;

} else {

// send email, write to db, etc. 

Open in new window


So, I am trying to figure out how to do the above with this:

<?php
if ($_POST) {
  $response = new stdClass;
  $response->message = "";
  $response->status = false;
  $email = isset($_POST['email']) ? $_POST['email'] : '';
 
  if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $response->status =  true;
  }
 
  if($response->status === false) {
    $response->message = <<< MSG
    <div class="red-error">
      <b>There were errors in your form:</b><br/>
      Invalid email address. <br/>
    </div>
MSG;
  } 
  else {
    // WRITE TO DB HERE
    // SEND EMAIL HERE
    $response->message = <<< MSG
    <div class="green-success">Thank you. We will respond to your enquiry as soon as possible.</div>
MSG;
  }
  
  die(json_encode($response));
}		
		

Open in new window



<script>
$(function() {
  $( "#send" ).click(function(e){
    e.preventDefault();
    $( "#send" ).prop( "disabled", true );
    $( ".loader" ).show();
    $( "#send" ).html( "Sending <img src='img/ajax-loader.gif'>" );
    var form_data = $( "#contact-form" ).serialize();
    $.ajax({
      type: 'POST',
      url: 't2329.php',
      data: form_data,
      dataType: 'JSON'
    }).done(function(response) {
      $( ".loader").hide();
      $( "#server-results" ).hide().html(response.message).fadeIn("slow");
      $('#send').html('Send Enquiry').prop({disabled: false});
      if (response.status) {
        $('#contact-form').hide();
      }
    });
  });
});
</script>

Open in new window


<form id="contact-form" method="post">
  <div class="col-sm-6 col-xs-12">
    <label class="contact">Email Address*</label>
    <input type="email" name="email">
  </div>
  <div class="col-sm-6 col-xs-12">
    <label class="contact">First Name*</label>
    <input type="text" name="first_name">
  </div>
  <div class="col-sm-5 col-md-4 col-xs-6">
    <button id="send" type="submit" name="submit" class="btn btn--primary type--uppercase">Send Enquiry</button>
  </div>
</form>
<div id="server-results"></div>

Open in new window

SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
As you continue to accumulate code and complexity, you will eventually discover why we use frameworks and unit tests.  These things are free, open-source, already tested, animal-friendly, low-calorie, high-performance, easy-to-use, etc.
https://laravel.com/
https://phpunit.de/

Bonus: Someone else supports them so you don't have to!
Ray is correct - personally I like re-inventing the wheel - for academic purposes the code above might be useful but in the long run a framework has enough up sides to make it an option to seriously consider.

Having said that, I am not really in favour of using a tool that works by "magic" i.e. that does what it does without me knowing how it does it. I believe in truly understanding the technology one works with. By attempting to solve problems such as these one gains both insight into how they work and a sense of how valuable making use of an existing solution is (like a framework).
Avatar of Crazy Horse

ASKER

@ Ray,

Firstly, lol @
animal-friendly, low-calorie

Yes, I am aware that there are frameworks that significantly reduce the grunt work but I am trying to learn how to do things from scratch to try and better understand. I have every intention of working my way up to Laravel. I am not going to bet money on it, but I think one needs a basic understanding of OOP before diving into Laravel. I had intended to be learning OOP by now but life has had other plans for me which has delayed that. But I will get there. Eventually...

Thanks Julian, I will play with the code and check out the article.