Solved

Validating form data with Multiple input fields

Posted on 2014-03-10
6
573 Views
Last Modified: 2014-03-11
I have code at the moment where is a user input multiple items into a text input separated by a comma, this gets submitted to php backend and using explode, I can retrieve the correct values and process them back through jquery.

 Here is my problem. I need to find a way to validate input using several input boxes. The maximum would be 8 and I am struggling to find a way to do this, using my existing code. Firebug states the the POST is 2 separate box_add posts. I cannot use [] because that will interfere with validator. I would be grateful if someone could show me the correct way to code this. Thanks

HTML relevant code

<a href="#" id="INTKAddMoreFileBox" class="btn btn-info">Add More Box Fields</a>
	<div id="INTKInputsWrapper">
	   <div><input name="box_add" type="text" id="box_add" />
              <a href="#" class="removeclass">&times;</a><a style="margin-left: 14px;" href="javascript:void(0)" title="Just an example" class="tooltip">Help</a>
           </div>
       </div>

Open in new window


PHP code

<?php
	session_start();
	
	$connect = mysql_connect("localhost", "root", "") or die ('{"opp":"error","box":"mysql_connect FAILED"}');
	
	$db = mysql_select_db("sample");


	// test vars from jquery form
	$status = mysql_real_escape_string($_REQUEST['status']);
	$company = mysql_real_escape_string($_REQUEST['company']);
	$requested = mysql_real_escape_string($_REQUEST['requested']);
	$activity = mysql_real_escape_string($_REQUEST['activity']);
	$address = mysql_real_escape_string($_REQUEST['address1']);
	$service = mysql_real_escape_string($_REQUEST['service']);
	$destroyDate = mysql_real_escape_string($_POST['datepicker']);
	$date = explode('/', $_POST['datepicker']);
	$newdate = $date[2].'-'.$date[1].'-'.$date[0];
	//$box = mysql_real_escape_string($_REQUEST['box_add']); // never used
	$authorised = mysql_real_escape_string($_SESSION['kt_name_usr']);
	$dept = mysql_real_escape_string($_REQUEST['dept']);
	$boxerrortext = 'Error';

	// Split the box if multiples
	$array = explode(',', $_REQUEST['box_add']);
	
	$outString = ''; 
	
	foreach ($array as $box) {
		$box = mysql_real_escape_string($box);
		$sql = "SELECT item FROM act WHERE item = '$box'";
		$result = mysql_query($sql) or die ('{"opp":"error","box":"' . mysql_error() . '"}');

		// If there are dupe entries, send message to jquery
		if (mysql_num_rows($result) > 0) {
		
			$outString .= $box . ' ';		
	} 	
	}
	if ($outString) {
		$error = array('opp' => "error", 'box' => $outString); 
	
		$output = json_encode($error);
		echo $output;
		exit();
	}

	foreach ($array as $box) {
		$outString .= "<br />company:  $company <br /> address: $address <br />service: $service <br />Destroy Date: $destroyDate <br />box: $box <br />";

		$box = mysql_real_escape_string($box);
		$sql = "INSERT INTO `temp` (service, activity, department, company, address, user, destroydate, date, item, new)";
		$sql .= "VALUES ('$service', '$activity', '$dept', '$company', '$address', '$requested', '$newdate', NOW(), '$box', 1)";
		$result = mysql_query($sql) or die ('{"opp":"error","box":"' . mysql_error() . '"}');
	}

	$json = array('opp' => 'insert', 'box' => $outString);
	$result = json_encode($json);
	echo $result;
?>

Open in new window


Script to add inputs

<script type="text/javascript">
$(function() {

var MaxInputs       = 8; //maximum input boxes allowed
var InputsWrapper   = $("#INTKInputsWrapper"); //Input boxes wrapper ID
var AddButton       = $("#INTKAddMoreFileBox"); //Add button ID

var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added

$(AddButton).click(function (e)  //on add input button click
{
        if(x <= MaxInputs) //max input box allowed
        {
            FieldCount++; //text box added increment
            //add input box
            $(InputsWrapper).append('<div><input type="text" name="box_add" id="box_add" /><a href="#" class="removeclass">&times;</a></div>');
            x++; //text box increment
        }
return false;
});

$("body").on("click",".removeclass", function(e){ //user click on remove text
        if( x > 1 ) {
                $(this).parent('div').remove(); //remove text box
                x--; //decrement textbox
        }
return false;
}) 

});
</script>

Open in new window

0
Comment
Question by:peter-cooper
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 39918184
You would have to get the raw querystring and strip it down manually, as the last value in a querystring will overwrite any previous values
e.g.

$pairs=explode('&',$_SERVER['QUERY_STRING']);
foreach($pairs as $item){
	$items=explode("=",$item);
	if($items[0]=="my-named-pair"){
		echo $items[1];
	}
}

Open in new window

0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39918434
It's hard to eat an elephant all in one sitting.  It's hard to write a complete web app all at once, too!

I think you might want to deconstruct the problem a little bit.  Set the jQuery part aside and just concentrate on getting the HTML form right, and seeing what it looks like in PHP by using var_dump()to visualize the data.  Once you're satisfied that you can get the data the way you want, add the data base queries into the script.  And once all of this is working correctly from the browser address bar, then integrate the jQuery part of things.

At least, that is how I would do it.
0
 
LVL 34

Accepted Solution

by:
Slick812 earned 500 total points
ID: 39919348
greetings  peter-cooper, I'll tell you some about adding to a structure (html <form> in this case), in order to retrieve any of the added Parts, they MUST BE uniquely Identified, since the POST identifies these BY NAME, you MUST have a Unique Name for each, what I mostly do is just add an increasing number to a name (or ID)

you might try to add the FieldCount like this -
$(InputsWrapper).append('<div><input type="text" name="box_add'+FieldCount+'" id="box_add" /><a href="#" class="removeclass">&times;</a></div>');


or maybe the x could do it, I can not tell, I can not really see what you are doing in your javascript,  with the x or the FieldCount? ?
could be better coded for JS use.
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

Author Comment

by:peter-cooper
ID: 39920048
Hi Slick
Thanks very much. Works like a charm with slight modification:

 name="box_add[]'+FieldCount+'"

Open in new window


Many thanks
0
 

Author Closing Comment

by:peter-cooper
ID: 39920050
Thanks once again.
0
 
LVL 34

Expert Comment

by:Slick812
ID: 39920895
glad it works, suggestion 4 u, If you ask about javascript, as you do here, you need to put this question in the javascript, and jquery EE zones FIRST, the experts there can see what u got and what u need, ,  faster than the PHP , "Miscellaneous Web Development" zones.

a note to consider, you do not seem to have the experience in JS or PHP to see what to do in a Two Computer (server, browser) separate code dependence, needed for successful Ajax. Take time to try to do things with Ajax NOT related to building your current Form submit page here in dis question. You must take time to learn the basics and use, for JS (jquery) AND PHP in Ajax exchange, you can't get to where you want to go in Ajax with just some blind, no-knowledge, copy-paste code work, I do not tell you this just for "You", as I have seen too many others in questions here at EE about Ajax, that think it is simple and an ignorant anyone can do it. Copy-paste is one thing, but getting a good Ajax page requires much more than that.
0

Featured Post

Report: Liquid Web beats Amazon, Rackspace & More

A study by performance analyst firm Cloud Spectator finds that Liquid Web beats rivals Amazon, Rackspace and DigitalOcean when it comes to website and cloud application performance.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Bootstrap - BootBox - PHP - MYSQL - Response Trigger 6 62
history of pages 7 54
Convert complicated date to yyyy-mm-dd format 22 53
php time 12 29
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question