Help With popup after validating duplicate entries into database

Hello,

I have a popup that accepts a text value. The pop up also has an ADD button. When the button is pressed, this value is validated against the database to see if the value exists or not. If the value exists, it will return the error, if the value does not exist then it should insert into the database.

In case of error, pressing add button triggers the error displays on the browser console. When user hits OK button on the error console, I need the control to return to the popup that originated the error.

How can I achieve this? Please advise.

Below is the code.

if (isset($_POST['cmdWordAdd']) )
	{
  // 	$arg = "RUCHIRTEST1";
//	ctltrace($arg);

	$sql = mysql_query("SELECT count(*) FROM cxs_common_words WHERE word_name='$WORD_NAME'");
    $result = mysql_num_rows($sql);

     if($result !=="0"){
        alert('The word you have chosen already exists!. Please enter a unique word'); 
        return false;
	 }

     else {
		$WORD_NAME = isset($_POST['WORD_NAME'] )? $_POST['WORD_NAME']: false;
		$ACTIVE_FLAG = '0';
		if(isset($_POST['CheckboxActive']))
		{
			$ACTIVE_FLAG = '1';
		}
				
		$insArr['WORD_NAME']= trim($WORD_NAME);		
		$insArr['ACTIVE_FLAG']=($ACTIVE_FLAG==1)?"Y":"N";
		$insArr['CREATION_DATE']= date('Y-m-d');
		$insArr['CREATED_BY']= $LoginUserId;
		$insArr['LAST_UPDATED_BY']= $LoginUserId;
		$insArr['SITE_ID']= $SiteId;
		
		insertdata("cxs_common_words",$insArr);

		$_SESSION['cw_msg']='<div class="alert alert-success"><i class="icon-ok"></i> Common Word inserted successfully.</div>';
		
		$LastInsertedUserId = mysql_insert_id();
		header('Location:site-settings.php');
	}

<form method="post" id="frmNewCommonWord" action="" onsubmit = "return true">
		<div class="modal fade bs-example-modal-lg custom-modal" id = "ModalAddAccountingPeriod" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">		
			<div class="modal-dialog modal-lg cus-modal-lg" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
						<h4 class="modal-title " id="myModalLabel"> Commonly Used Word Exclusion List </h4>
					</div>
					<div class="modal-body"> 
						<!-- field start-->
						<div class="col-sm-12">
							<div class="cus-form-cont">
								<div class="col-sm-6 form-group cus-form-ico">
									<label> Word </label> <label id = "lblHeaderId" style = "display:none" > <?php echo $HeaderId;?> </label>
									<input type="text" id="WORD_NAME" name="WORD_NAME" class="form-control requirefieldcls form_datetime" maxlength="50" >									
								</div>
								<div class="col-sm-6 form-group cus-form-ico">
								  <label style = "width:150px;"> &nbsp;&nbsp; </label> <br>
								  <label > Active &nbsp;&nbsp;</label> <input type="checkbox" id="CheckboxActive" name="CheckboxActive" value="1" >
								</div>
							</div>
						</div>
					<!-- end --> 
					</div>
					<div class="clear-both"></div>
					<div class="modal-footer cr-user">
						<button type="submit" id="cmdWordAdd" name="cmdWordAdd" class="btn btn-primary btn-style">Add</button>
					</div>
				</div>
			</div>
		</div>
		<input type="hidden" id="h_duplicate" name="h_duplicate" value=""/>
	</form>

I’m not entirely sure how to fix the problem as I’m not that familiar with JS, modal pop-ups and the like. I do see two things, though:

  1. You’re still using the old no-longer-supported mysql functions to access the database - you should change either to mysqli or PDO.

  2. You seem to be trying to do an alert() from inside your PHP code.

if($result !=="0"){
        alert('The word you have chosen already exists!. Please enter a unique word'); 
        return false;
	 }

As far as I know, unless you have a function of that name defined somewhere, then alert() is a JavaScript thing. Keep in mind that your PHP is running in the background on the server, so while it can certainly send stuff back to the browser, interactive stuff like alert() isn’t really the right thing.

What I think you need to do is call the PHP code using Ajax, and pass the success or failure back via the appropriate function called on return from the PHP. Your JS calling code can then decide whether to give an error message or a success report.

At the end of your PHP code you try to do a header redirect, which isn’t an appropriate way to return control to a pop-up form because it will cause the whole page to be re-drawn. Immediately before it, you set a variable to the last insert-id, but when you do the redirect, that will be lost as you don’t save it anywhere like a session variable or cookie.

The alert is indeed not right! within the php function. Instead the form could be submitted using AJAX and then use a http_response_code within the PHP function:

if($result !=="0"){
	http_response_code(400);
	echo "The word you have chosen already exists!. Please enter a unique word";
	exit;
}

AJAX

$("#form").on("submit", function(e) {
	$.ajax({
		type: "POST",
		url:  "//php function",
		data: $(this).serialize()	
	})
	.done(function(data) {
		//success message
	}
	.fail(function(data) {
		//error message
	}
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.