Link to home
Start Free TrialLog in
Avatar of Moses Dwana
Moses Dwana

asked on

HOW TO INSERT DYNAMIC INPUT FIELD IN DATABASE USING AJAX TO SUBMIT FORM

on my form, i want to be able to insert one or more phone numbers. i created a dynamic input field to get this done but, when i insert more then one phone number and submit, i can only see one phone number in the database. i want the phone number to be inserted like this ( firstnumber,secondnumber,thirdnumber....). thanks in advance for the help. see the code:

this is the html and the script to generate the dynamic input
<table id="nameBoxWrap">
					<tr id="nameBox">
						<input type="text" id="phonenumber" name="phonenumber[]"  placeholder="phone number">
						<input type="button" value="ADD MORE" onclick="addNameSection()" ><br>
						
					</tr>
					
				</table>
				
            </div>
			<input type="hidden" id="addSectionCount" value="1" name="addSectionCount" >

<script>function addNameSection(){
	var addSectionCount=$("#addSectionCount").val();
	addSectionCount++;
	$("#addSectionCount").val(addSectionCount);
	$("#nameBoxWrap").append('<tr id="nameBox'+addSectionCount+'"><td></td><td><input type="text" placeholder="phone number" id="phonenumber'+addSectionCount+'" name="phonenumber[]"></td><td><input type="button" value="REMOVE" onclick=removeNameSection("'+addSectionCount+'")></td></tr>');
}	</script>

Open in new window


this is the js script to submit the form
<script>
//script that manage form data submission to database

    $(function(){
        $('#submitdata1').on('click',function(e){
            e.preventDefault();  // do not allow the default form action
            var phone = $('#phonenumber').val();
			
            $.ajax({
                method: "POST",
                url: "processveh.php",
                data: { phonenumber: phone
				        
         			    }
				
				        
            })
                .done(function( data ) {  // capture the return from process.php
                    var obj = $.parseJSON( data );
                    var ph = obj.phon;
					 var phonemessage = obj.msg_phone;
					

                   
					if(ph == 1){  // place results on the page
					     $('input[name="phonenumber"]').removeClass('textBoxError');
                        $('#veresult10').html('<div  class="valid"></div>');
                    } else {
						 $('input[name="phonenumber"]').addClass('textBoxError');
                        $('#veresult10').html('<div class="error">'+assignmessage+'</div>');
					
                    }
					
					
					
                });
        });
    });
 
	
	
	
</script>

Open in new window


this is the php script. it's call processvh.php
<?php
 include('section.php');
if(isset($_POST)){
    $phone = $_POST['phonenumber'];
	
	
	    
         
	
	$mysqli = new mysqli("localhost","root","","extenderaid");
if($mysqli-> connect_error){
die("database connection fail".$mysql->connect_error);}	
//$chk='';  
   //foreach($phone as $chk1)  
     // {  
         // $chk .= $chk1.",";  
       //}
	
   	// capture post
	/*$mode = 1;
	
	$pho = 1;
	 $msg_phone = '';
	 
	
     // set value of each possible return value to blank.

    if (empty($phone)) {  // test for valid email
        $msg_phone = "*  phone number is require. ";
        $pho = 0;  // if bad, set valid flag to 0
    }
	  

	if($msg_phone==''){

 
		 $query =mysqli_query($mysqli,"insert into itequipment(phone_number) values ('$phone')");	
        
     
	 }
	
	
	

    $result1 = array('pho' => $pho, 'msg_phone' => $msg_phone);  // create an array to be converted to json

    echo json_encode($result1);  // echo out json encoded response 
}
?>

Open in new window

Avatar of M. Tariq
M. Tariq
Flag of Oman image

Hey Moses,
With
 var phone = $('#phonenumber').val(); 

Open in new window

obliviously it will get you one phone number.
As I can see you are adding phone number text boxes with the ID +  digit, so you can check the last digit which is [addSectionCount] and iterate through all the inputs, then store their values in an array or concatenate them as a comma separated string.
Another way is you can assign all of them one class for example [phoneCls] and on submit, you can iterate through them like this :
$.each('.phoneCls',function(){
 // Do your stuff here
})

Open in new window

Avatar of Nitin Sontakke
Somehow, I am not been able to see where you are concatenating the phone numbers from the div ids, phonenumber, phonenumber1, phonenumber2, etc.

Could you please mention line number and block where this is done.

It must be done, before you submit the form.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa 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
Avatar of Moses Dwana
Moses Dwana

ASKER

i have been using something like this in php to get it done without ajax, but this method is not working since i decided to pass through ajax to submit.
//  
$phone = $_POST['phonenumber']; 

$chk='';  
   foreach($phone as $chk1)  
      {  
          $chk .= $chk1.",";  

$query =mysqli_query($mysqli,"insert into itequipment(phone_number) values ('$chk')");	
        
       }

Open in new window

I think here you need to pass the array through to your PHP script and then concatenate the values in there before adding to your Db. Depending on how your form is set up, you can either serialize the whole form, or just the phone numbers. Here's an example of just sending the phone numbers

// jQuery
$('#myForm').on('submit',function(e){
	e.preventDefault();

	$.ajax({
	    method: "POST",
	    url: "processveh.php",
	    data: $('input[name="phone[]"]').serializeArray()
	})
	.done(function( data ) {
		...
	});
});

Open in new window

// PHP - join the values together with a comma
$phoneNumbers = join(',', $_POST['phone']);

Open in new window

i have been using something like this in php to get it done without ajax, but this method is not working since i decided to pass through ajax to submit.
That is because in direct php you are accessing the element via their name attribute hence it used to work. Using ajax, you will have to access the elements somehow [there are many ways to achieve that obviously] and then you pass them to php the way you see fit either it is an array or a comma separated string.
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
you are great julian!! thanks very mush!!! i refuse to follow your adverse first not knowing that is the  best and easy way to submit using ajax. using  "serialize()" got it done.
Julian, the error message for the phone field is not displaying  since i use serialize(). before using serialize(), the error message for the phone field was displaying but the phone number for the dynamic field was not inserting in the database, but right now that is resolve. the problem now is: the error message for the phone field is no longer displaying,
 
$phone = isset($_POST['phonenumber']) ? $_POST['phonenumber'] : false;

if (empty($phone)) {  // test for valid email
        $msg_phone1 = "* state phone number";
        $phon1 = 0;  // if bad, set valid flag to 0
		$valid3 = 1;
    }

Open in new window

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
it's now working perfectly thanks so mush!!!!
Cleanup vote:
Julian Hansen #a42271984 (500 points) Best Solution
Julian Hansen #a42272233 (500 points) Assisted Solution
OP acknowledged the best answer.