Jump to content

Need help determining error versus success.


webguync

Recommended Posts

Hi, I found a tutorial online for a form which used PHP/MySQL and JQuery to submit data. I am making some modifications and the form no-longer submits the data. The problem I have is no errors display so I am not sure where the problem lies. I need to be able to display a success or failure message on the form itself, but this is either not there or not working. The code is below.

 

<form id="ContactForm" action="">
                <p>
                    <label>First Name</label>
                    <input id="FirstName" name="FirstName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/>
				<span class="error" style="display:none;"></span>
                </p>
                <p>
                    <label>Last Name</label>
                    <input id="LastName" name="LastName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/>
				<span class="error" style="display:none;"></span>
                </p>
                <p>
                    <label>User Name</label>
                    <input id="UserName" name="UserName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/>
				<span class="error" style="display:none;"></span>
                </p>
                <p>
                    <label>Email</label>
                    <input id="email" name="email" class="inplaceError" maxlength="120" type="text" autocomplete="off"/>
				<span class="error" style="display:none;"></span>
                </p>
                <p>
                    <label>Website<span>(optional)</span></label>
                    <input id="website" name="website" class="inplaceError" maxlength="120" type="text" autocomplete="off"/>
                </p>
                <p>
                    <label>Your message<br /> <span>300 characters allowed</span></label>
                    <textarea id="message" name="message" class="inplaceError" cols="6" rows="5" autocomplete="off"></textarea>
				<span class="error" style="display:none;"></span>
                </p>
                <p class="submit">
                    <input id="send" type="button" value="Submit"/>
                    <span id="loader" class="loader" style="display:none;"></span>
				<span id="success_message" class="success"></span>
                </p>
			<input id="newcontact" name="newcontact" type="hidden" value="1"></input>
            </form>

 

<?php
require_once("config.php"); /* Configuration File */

class DB{

private $link;

public function __construct(){
	$this->link = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,DB_NAME);
	if (mysqli_connect_errno())
	    exit();
}

public function __destruct() {
	mysqli_close($this->link);
}

public function dbNewMessage($email,$FirstName,$LastName,$website,$message){
	$email 	 	= mysqli_real_escape_string($this->link,$email);
	$FirstName 	= mysqli_real_escape_string($this->link,$FirstName);
	$LastName 	= mysqli_real_escape_string($this->link,$LastName);
	$UserName 	= mysqli_real_escape_string($this->link,$UserName);
	$website 	= mysqli_real_escape_string($this->link,$website);
	$message 	= mysqli_real_escape_string($this->link,$message);

	mysqli_autocommit($this->link,FALSE);

	$query = "INSERT INTO contact_me(pk_contact,FirstName,LastName,UserName,email,website,message) 
			  VALUES('NULL','$FirstName','$LastName','$UserName','$email','$website','$message')";
	mysqli_query($this->link,$query);

	if(mysqli_errno($this->link))
		return -1;
	else{
		mysqli_commit($this->link);
		return 1;
	}
}   
};
?>


 

<?php
require_once("db.php");					/* Database Class */
require_once('utils/is_email.php');		/* Email Validation Script */

/* Handle Ajax Request */
if(isset($_POST['newcontact'])){
$contact = new Contact();
unset($contact);
}
else{
header('Location: /');
}

/* Class Contact */
class Contact{

private $db; 						/* the database obj */

private $errors 		= array();  /* holds error messages */
private $num_errors;   				/* number of errors in submitted form */

public function __construct(){
	$this->db = new DB();
	if(isset($_POST['newcontact']))
		$this->processNewMessage();
	else
		header("Location: /");
}

public function processNewMessage(){

	$email		= $_POST['email'];
	$FirstName		= $_POST['FirstName'];
	$LastName		= $_POST['LastName'];
	$UserName		= $_POST['UserName'];
	$website	= $_POST['website'];
	$message	= $_POST['message'];

	/* Server Side Data Validation */

	/* Email Validation */
	if(!$email || mb_strlen($email = trim($email)) == 0)
		$this->setError('email','required field');
	else{
		if(!is_email($email))
			$this->setError('email', 'invalid email');
		else if(mb_strlen($email) > 120)
			$this->setError('email', 'too long! 120');
	}

	/* FirstName Validation */
	if(!$FirstName || mb_strlen($FirstName = trim($FirstName)) == 0)
		$this->setError('FirstName', 'required field');
	else if(mb_strlen(trim($FirstName)) > 120)
		$this->setError('FirstName', 'too long! 120 characters');

		/* LastName Validation */
	if(!$LastName || mb_strlen($LastName = trim($LastName)) == 0)
		$this->setError('LastName', 'required field');
	else if(mb_strlen(trim($LastName)) > 120)
		$this->setError('LastName', 'too long! 120 characters');

		/* UserName Validation */
	if(!$UserName || mb_strlen($UserName = trim($UserName)) == 0)
		$this->setError('UserName', 'required field');
	else if(mb_strlen(trim($UserName)) > 120)
		$this->setError('UserName', 'too long! 120 characters');

	/* Website Validation */
	if(!mb_eregi("^[a-zA-Z0-9-#_.+!*'(),/&:;=?@]*$", $website))
		$this->setError('website', 'invalid website');	
	elseif(mb_strlen(trim($website)) > 120)
		$this->setError('website', 'too long! 120 characters');

	/* Message Validation */
	$message = trim($message);
	if(!$message || mb_strlen($message = trim($message)) == 0)
		$this->setError('message','required field');
	elseif(mb_strlen($message) > 300)
		$this->setError('message', 'too long! 300 characters');

	/* Errors exist */
	if($this->countErrors() > 0){
		$json = array(
			'result' => -1, 
			'errors' => array(
							array('name' => 'email'		,'value' => $this->error_value('email')),
							array('name' => 'FirstName' ,'value' => $this->error_value('FirstName')),
							array('name' => 'LastName' ,'value' => $this->error_value('LastName')),
							array('name' => 'UserName' ,'value' => $this->error_value('UserName')),
							array('name' => 'website'	,'value' => $this->error_value('website')),
							array('name' => 'message'	,'value' => $this->error_value('message'))
						)
			);				
		$encoded = json_encode($json);
		echo $encoded;
		unset($encoded);
	}
	/* No errors, insert in db*/
	else{
		if(($ret = $this->db->dbNewMessage($email, $FirstName, $LastName,$UserName, $website, $message)) > 0){
			$json = array('result' 		=> 1); 
			if(SEND_EMAIL)
				$this->sendEmail($email,$name,$website,$message);
		}	
		else
			$json = array('result' 		=> -2); /* something went wrong in database insertion  */
		$encoded = json_encode($json);
		echo $encoded;
		unset($encoded);
	}
}

public function sendEmail($email,$name,$website,$message){
	/* Just format the email text the way you want ... */
	$message_body		= "Hi, ".$name."(".$email." - ".$website.") sent you a message from yoursite.com\n"
								."email: ".$email."\n"
								."message: "."\n"
								.$message; 
	$headers			= "From: ".EMAIL_FROM_NAME." <".EMAIL_FROM_ADDR.">";

	return mail(EMAIL_TO,MESSAGE_SUBJECT,$message_body,$headers);
}

public function setError($field, $errmsg){
	$this->errors[$field] 	= $errmsg;
	$this->num_errors 		= count($this->errors);
}

public function error_value($field){
	if(array_key_exists($field,$this->errors))
		return $this->errors[$field];
	else
		return '';
}

public function countErrors(){
	return $this->num_errors;
}
};
?>

 

and the JQuery

$(document).ready(function() {
contact.initEventHandlers();
});
var contact = {
initEventHandlers	: function() {
	/* clicking the submit form */
	$('#send').bind('click',function(event){
		$('#loader').show();
		setTimeout('contact.ContactFormSubmit()',500);
	});
	/* remove messages when user wants to correct (focus on the input) */
	$('.inplaceError',$('#ContactForm')).bind('focus',function(){
		var $this 		= $(this);
		var $error_elem = $this.next();
		if($error_elem.length)
			$error_elem.fadeOut(function(){$(this).empty()});
		$('#success_message').empty();	
	});
	/* user presses enter - submits form */
	$('#ContactForm input,#ContactForm textarea').keypress(function (e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
			$("#send").click();
			return false;  
		} 
		else  
			return true;  
	});
},
ContactFormSubmit	: function() {
	$.ajax({
		   type		: 'POST',
		   url		: 'php/contact.php?ts='+new Date().getTime(),
		   dataType	: 'json',
		   data		: $('#ContactForm').serialize(),
		   success	: function(data,textStatus){
						  //hide the ajax loader
						  $('#loader').hide();
						  if(data.result == '1'){
						      //show success message
							  $('#success_message').empty().html('Message sent');
							  //reset all form fields
							  $('#ContactForm')[0].reset();	
							  //envelope animation
							  $('#envelope').stop().show().animate({'marginTop':'-175px','marginLeft':'-246px','width':'492px','height':'350px','opacity':'0'},function(){
							      $(this).css({'width':'246px','height':'175px','margin-left':'-123px','margin-top':'-88px','opacity':'1','display':'none'});
							  });
						  }
						  else if(data.result == '-1'){
							  for(var i=0; i < data.errors.length; ++i ){
							      if(data.errors[i].value!='')
							          $("#"+data.errors[i].name).next().html('<span>'+data.errors[i].value+'</span>').fadeIn();
							  }
						  }						  
					  },
		   error	: function(data,textStatus){}
	});
}  
};

Link to comment
Share on other sites

I think it is a PHP problem, but for some reason the success msg. doesn't appear which is done through JQuery. Not getting any JS errors when viewing in the Firefox JS console. I am getting data submitted in MySQL table, but some field are empty (when they shouldn't be) and the form data doesn't match up with where it should be appearing in the DB. I double checked and can't see anything I missed, but something is definitely wrong.

Link to comment
Share on other sites

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.