Jump to content

Recommended Posts

I need some help with getting JQuery AJAX to work with a method in one of my PHP classes. I validated the form using a PHP class and which extends a Database class. I just need the AJAX to work and I'm good. How do you get AJAX to work with OO PHP? I have been stuck on this for the past few days and have researched all across the internet and have not found anything that works. Can someone maybe post a simple example of getting JQuery's AJAX function to work with a PHP method?

 

Here is the PHP method that returns whether the user passed validation or not (contact.class.php which extends database.class.php):

public function isValidData() {

if ($this -> firstName() && $this -> lastName() && $this -> email() && $this -> subject() && $this -> message()) {

        return true;
    } else {
        return false;
    }

}

 

Here is the Jquery. The Ajax is at the bottom:

//Submit function called when the user clicks the submit button
$('#contact_form').submit(function(e) {

	//Prevent submission until the user passes validation
	e.preventDefault();

	//If all the functions return true, then send form to the AJAX function
	if(validFirstName() && validLastName() && validEmail() && validSubject() && validMessage()) {
		//Serialize the data in the form for the AJAX Request
		var formData = $('#contact_form').serialize();

		//submitForm(formData);
		//Displays success message, clears contact form and hides the lightbox
		$('#contact_form').fadeOut(1000, function() {
			$('.success').html('Form submission successful.' + '<br/>' + 'Thank you ' + $('input.first').val() + "!").fadeIn(4000, function() {
				//Clears contact form
				$('.first').val('');
				$('.last').val('');
				$('.email').val('');
				$('.subject').val('');
				$('.message').val('');
				//Hides success message
				$('.success').hide();
				//Hides lightbox
				$('.mask, .main_contact').css('display', 'none');
			});

		});
		return true;

	} else {
		return false;
	}

});

//Validates the user's first name
function validFirstName() {
	var firstName = $('.first').val();
	if(firstName.length <= 2 || firstName == '') {
		$('.error').show().html('3 Characters required!<br/>');
		$('.first').css('box-shadow', ' 0 0 10px #B40404');
		return false;
	} else {
		$('.first').css('box-shadow', '0 0 4px #000');
		$('.error').hide();
		return true;
	}

}

//Validates the user's last name
function validLastName() {
	var lastName = $('input.last').val();
	if(lastName.length <= 2 || lastName == '') {
		$('.error').show().html('3 Characters required!<br/>');
		$('input.last').css('box-shadow', '0 0 10px #B40404');
		return false;

	} else {
		$('input.last').css('box-shadow', '0 0 4px #000');
		$('.error').hide();
		return true;
	}
}

//Validates the user's email
function validEmail() {
	var email = $('.email').val();
	if(!email.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
		$('.error').show().html('Invalid email address!<br/>');
		$('.email').css('box-shadow', ' 0 0 10px #B40404');
		return false;

	} else {
		$('.email').css('box-shadow', '0 0 4px #000');
		$('.error').hide();
		return true;
	}

}

//Validate the subject input in the contact form
function validSubject() {
	var subject = $('.subject').val();
	if(subject.length <= 2 || subject == '') {
		$('.error').show().html('3 Characters required!<br/>');
		$('.subject').css('box-shadow', ' 0 0 10px #B40404');
		return false;
	} else {
		$('.subject').css('box-shadow', '0 0 4px #000');
		$('.error').hide();
		return true;
	}
}

//Validate the message input
function validMessage() {

	var message = $('.message').val();
	if(message.length <= 2 || message == '') {
		$('.error').show().html('3 Characters required!<br/>');
		$('.message').css('box-shadow', ' 0 0 10px #B40404');
		return false;
	} else {
		$('.message').css('box-shadow', '0 0 4px #000');
		$('.error').hide();
		return true;
	}

}

});

//Ajax Request
function submitForm(formData) {

$.ajax({
	type : "POST",
	url : "includes/function.php",
	data : formData,
	dataType: 'json',
	cache : false,
	success : function(formData) {
		if(formData.success) {

			alert(formData.msg);
		} else {
			alert("Error");
		}
		console.log(formData);

	}
});

 

The Jquery seems to disable my PHP serverside validation too. When the JQuery is disabled, the server side validation works fine. Any idea why JQuery would disable the server validation? I am kinda new to programming and I would appreciate any help, thanks.

Link to comment
https://forums.phpfreaks.com/topic/263053-oo-php-and-ajax-form-validation/
Share on other sites

Of course it's possible.  That's what AJAX is - JavaScript sending a request to some server code, and then handling the results.  That server code can be just about anything: PHP, Ruby, Python, Perl, C#, VB, C++, etc. 

 

In your case, you're sending data via POST, but, according to the code you have above, don't touch $_POST.

 

AJAX works just like synchronous requests.  If you send something via GET in your JavaScript, you need something in your PHP that can handle the corresponding $_GET values.  The same thing goes with POST.

 

You'd be wise to step back and make small test scripts to see how it all works.  Trying to get a live component to work when you haven't even played with AJAX before is just asking for heartbreak.

Edit: Sorry, I should have formatted the code better.

database.class.php

class Database {
      
   //Host name for database
   protected $host = "localhost";
   //Database name
   protected $database = "project";
   //Authorized database user
   protected $user = "root";
   //Database password
   protected $password = "";

   //Database table name
   protected $table;

   //Result of the query() method
   protected $query;

   //Result of numrows() method
   protected $rows;

   //Result of fetch() method
   protected $assoc;

   //Result of cleanData() method
   protected $string;
   
   

   
   public function __construct() {

   }

   //----------------------------------------
   //   Connects to MYSQL Database server
   //----------------------------------------
   public function connect() {

      $connect = mysql_connect($this -> host, $this -> user, $this -> password) or die("Could not connect to the host!");
      mysql_select_db($this -> database) or die("Could not find the database!");
   }

   //----------------------------------------
   //   Queries the MYSQL Database server
   //----------------------------------------
   public function query($query) {

      $this -> query = $query;
      $this -> query = mysql_query($this -> query) or die("Query to database failed.");
      return $this -> query;

   }

   //-------------------------------------------
   //   Stores database informatio into an array
   //-------------------------------------------
   public function fetch($assoc) {
      $this -> assoc = $assoc;
      $this -> assoc = mysql_fetch_assoc($this -> assoc);
      return $this -> assoc;

   }

   //--------------------------------------------
   //   Counts the number of records in the database
   //---------------------------------------------
   public function numrows($rows) {
      $this -> rows = $rows;
      $this -> rows = mysql_num_rows($this -> rows);
      return $this -> rows;
   }
   
   //----------------------------------------------------------
   //   Cleans user data and protects against MYSQL injections
   //----------------------------------------------------------
   public function cleanData($string) {
      $this -> string = $string;
      $this -> string = mysql_real_escape_string(strip_tags(stripcslashes(trim($this -> string))));
      return $this -> string;
   }

   

   

}

contact.class.php



class Contact extends Database {

   private $firstName;
   private $lastName;
   private $email;
   private $subject;
   private $message;
   private $errors;

   private $numeric;
   private $empty;
   private $stri;
   private $alphaNum;
   private $alpha;

   public function __construct() {

      $this -> firstName = $this -> cleanData($_POST['first']);
      $this -> lastName = $this -> cleanData($_POST['last']);
      $this -> email = $this -> cleanData($_POST['email']);
      $this -> subject = $this -> cleanData($_POST['subject']);
      $this -> message = $this -> cleanData($_POST['message']);
      $this -> errors = array();

   }

   public function isValidData() {

      if ($this -> firstName() && $this -> lastName() && $this -> email() && $this -> subject() && $this -> message()) {
         echo json_encode(array("returnvalue" => "Response from contact class"));
         //return true;
      } else {
         echo json_encode(array("returnvalue" => "Response from contact class"));
         //return false;
      }

   }

   //---------------------------------------
   //   Validates first name
   //---------------------------------------

   public function firstName() {

      if ($this -> stringLength($this -> firstName) > 2 && !$this -> isEmpty($this -> firstName)) {
         //echo " ";

         return true;

      } else {

         $this -> errors[] = "Invalid first name.";

         return false;

      }

   }

   //--------------------------------------------
   //   Validates last name
   //--------------------------------------------
   public function lastName() {

      if ($this -> stringLength($this -> lastName) > 2 && !$this -> isEmpty($this -> lastName)) {

         return true;
      } else {

         $this -> errors[] = "Invalid last name.";
         return false;
      }

   }

   //----------------------------------------------
   //   Validates and filters the email
   //----------------------------------------------
   public function email() {
      if ($this -> isValidEmail($this -> email) && $this -> stringLength($this -> email) > 2 && !$this -> isEmpty($this -> email)) {
         return true;
      } else {
         $this -> errors[] = "Invalid email.";
         return false;
      }

   }

   //----------------------------------------------
   //   Validates the subject line of the message
   //----------------------------------------------
   public function subject() {

      if ($this -> stringLength($this -> subject) > 2 && !$this -> isEmpty($this -> subject)) {

         echo ' ';
         return true;
      } else {
         $this -> errors[] = "Invalid subject.";
         return false;
      }

   }

   //------------------------------------------------
   //   Validates the acutal message
   //------------------------------------------------
   public function message() {

      if ($this -> stringLength($this -> message) > 2 && !$this -> isEmpty($this -> message)) {

         return true;
      } else {
         $this -> errors[] = "Invalid message.";
         return false;
      }

   }

   //-------------------------------------------------
   //   Alpha-numeric values only
   //-------------------------------------------------
   public function isAlphaNumeric($str) {
      $this -> alphaNum = $str;
      if (ctype_alnum($this -> alphaNum)) {
         return $this -> alphaNum;
      } else {

      }
   }

   //--------------------------------------------------
   //   Numberic values only method
   //--------------------------------------------------
   public function isNumeric($num) {
      $this -> numeric = $num;

      if (ctype_digit($this -> numeric)) {
         return $this -> numeric;
      } else {

      }
   }

   //--------------------------------------------------
   //   Alphabetic characters only
   //--------------------------------------------------
   public function isAlphabetic($str) {
      $this -> alpha = $str;
      if (ctype_alpha($this -> alpha)) {
         return $this -> alpha;
      }
   }

   //-------------------------------------------------
   //   Checks if the string is empty
   //-------------------------------------------------
   public function isEmpty($str) {
      $this -> empty = $str;
      if (empty($this -> empty)) {
         return $this -> empty;
      } else {

      }
   }

   //-------------------------------------------------
   //   Get the string length
   //-------------------------------------------------
   public function stringLength($str) {
      $this -> stri = $str;
      $this -> stri = strlen($this -> stri);
      return $this -> stri;
   }

   //---------------------------------------------
   //   Validates email address
   //--------------------------------------------
   public function isValidEmail($em) {
      $this -> email = $em;
      $this -> email = filter_var($this -> email, FILTER_VALIDATE_EMAIL);
      return $this -> email;

   }

   //------------------------------------------------
   //   Show errors
   //-----------------------------------------------
   public function showErrors() {

      foreach ($this->errors as $key => $error) {
         return $error;

      }

   }

}

Header.php (This file is included at the top of each page)

include 'includes/database.class.php';
include 'includes/contact.class.php';


ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('display_errors', '0');
$database = new Database();
$database -> connect();
$contact = new contact();
$errors = $contact -> showErrors();
$flag = 0;

if (isset($_POST['submit'])) {

   $first = $database -> cleanData($_POST['first']);
   $last = $database -> cleanData($_POST['last']);
   $email = $database -> cleanData($_POST['email']);
   $subject = $database -> cleanData($_POST['subject']);
   $message = $database -> cleanData($_POST['message']);

   $contact = new contact();
   if ($contact -> isValidData()) {
      
      $flag = 1;
      $result = $database -> query("INSERT INTO contact (first_name, last_name, email, subject, message) VALUES ('$first', '$last', '$email', '$subject', '$message') ");
      
   } else {
      $flag = 0;

   }
}




 

 

 

 

 

Yeah, your code is all over the place.

 

For starters, it's not a good idea to have your Contact class derive from your Database class.  Ask yourself this question: "Is a contact a database?"  The answer is no.  Inheritance creates what are known as is-a relationships, meaning that whatever you have for a child class is, in the eyes of PHP, also an object of the parent class.  If something isn't considered something else (like a contact isn't considered to be a database) in real life, it shouldn't in your code, either.

 

Inheritance should only be used if you want to create a family of similar classes.  You should NOT use inheritance because you merely want one object to access another.  There are far better ways to do that.

 

Let's look at Contact itself: is a contact a validator?  Again, no.  You should have a standalone validation object that you can pass a contact into, like so:

 

$validator = new Validator();
$validator->validate($contact);

if ($validator->hasErrors()) {
   // handle the errors
}

 

Every class should have a single responsibility.

 

Beyond that, you have a lot of logical oddities.  You make two contact objects for one set of data.  You call showErrors before anything is actually done with a contact.  You treat the isValidData method as a boolean, but then never return anything from it.

 

My best advice is to drop the OOP and just try to get it working procedurally.  You can always refactor it back into OOP after that.

 

And since you want to learn OOP, you should get a good resource.  The following book is the best resource for OOP in PHP available: http://www.amazon.com/Objects-Patterns-Practice-Experts-Source/dp/143022925X/ref=sr_1_1?ie=UTF8&qid=1337892781&sr=8-1

Thanks for the advice. I managed to get the AJAX working without object oriented code. I will take your advice and switch back to procedural. I was trying to do something different with this project, but I will make my life easier and use procedural. Thanks again for helping me and leading me in the right direction. I will check out that book too, thanks.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.