Dynamically adding/removing input fields not submitting

Evening all,

its been awhile posting on here last couple of days i have been working on a section on my website i have ran into an issue that i am having i have this page for adding/removing multiple input fields but the only problem is the submitting part of my script.

you see when i click on submit no errors,the page just gets refreshed and redirected to my main login area member section but what it should be doing is inserting the multiple data into the database but lookjs like nothing is be display or even called

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
            <script>  
 $(document).ready(function(){  
      var i=1;  
      $('#add').click(function(){  
           i++; 
		   $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="username" /></td><td><input type="text" name="emaill" /></td><td><button type="button" name="remove" id="'+i+'" class="btn_remove">Remove</button></td></tr>');  
      });  
      $(document).on('click', '.btn_remove', function(){  
           var button_id = $(this).attr("id");   
           $('#row'+button_id+'').remove();  
      });
	  	$('#recruitmember').click(function(){
		$.ajax({
			url:"include/includeajax/MassRecruitInsert.php",
			method:"POST",
			data:$('#add_me').serialize(),
			success: function(data)
			{
				$('#add_me')[0].reset();
			}
		}); 
});  
 });  
 </script> 
<form action="" method="post" name="add_me" id="add_me">
                            <table style="color:#FFF;" id="dynamic_field">
                            <td><input type="hidden" name="password[]" value="<?php echo randAlphaNum(8); ?>"></td>
                                <tr>
                                    <td colspan="3">Recruit Multiple Members</td>
                                </tr>
                                <tr>
                                    <td>Username:</td>
                                    <td>Email:</td>
                                    <td>Task</td>
                                </tr>
                                <tr>
                                    <td><input type="text" name="username[]" /></td> 
                                    <td><input type="text" name="email[]" /></td>
                                    <td><input type="button" name="add" id="add" value="Add Another" /></td>
                                </tr>
                            </table>
                            <input type="submit" name="recruitmember" id="recruitmember" value="Recruit Member"/>
                        </form>

and the php submit code for the inserting is

[CODE]
include(“dbconnect.php”);
$number = count($_POST[“username”]);
for($i=0; $i<$number; $i++)
{
$pQuery=“insert into members (username,password,rank,email,disable,Recruitedby,LastedLogin,joineddate,web,recruits,signons,ia,joineddate2) values('”.mysqli_real_escape_string($con, $_POST[“username”][$i]).
“‘,’”.mysqli_real_escape_string($con, $_POST[“password”][$i]).
“‘,‘1’,’”.mysqli_real_escape_string($con, $_POST[“email”][$i]).
“‘,‘1’,’$recruiter’,‘$today’,‘$today’,‘0’,‘0’,‘0’,‘0’,‘$today4’)”;
echo $pQuery;
$LQuery=“INSERT INTO logs Values(‘’,‘$rank’,‘$recruiter’,‘sucessfully recruited $username on’,‘$today’,‘Recruitment’)”;
$rQuery=“update members set recruits=recruits+$number where username='”.$_SESSION[‘user’].“'”;
$result=mysqli_query($con,$pQuery);
$result=mysqli_query($con,$LQuery);
$result=mysqli_query($con,$rQuery);
if(!$result)
{
echo “Error:”.mysqli_connect_errno();
echo “
Error2:”.mysqli_error($con);
}
else
{
echo “

Member Add to Clan

The Recruits Login information is as follows:



Username: $user

Password: $password





Please Make Sure the Recruit Logins and Changes his password”;
$clanwebsite=$_SERVER[‘HTTP_HOST’];
mail(“$email”, “Welcome to $ClanName!”, "$username
Welcome to $ClanName! You are now, the newest member of our great clan!
____________________________________________________________
Here is your information:
User Name: $user
Password: $password

				Website For Clan is $clanwebsite
				
				Ensure you don't lose this information.  If you have a problem with loggin in, please
				feel free to contact an officer and they can assist you.
				____________________________________________________________");
			}

}
echo “Data Inserted Successfully”;[/CODE]

now the main file (mass recruit) where the html code is presented is in the directory includes and the massrecruitinsert.php is based in the includeajax folder

so for example

massrecruit.php file is based in http://www.mysite.com/includes/massrecruit.php
massrecruitinsert.php file is based in http://www.mysite.com/includes/includesajax/massrecruitinsert.php

so when i click on the the submit button nothing is coming back or returning and i know there is a problem some where but cant find it.

is there somthing wrong with the way i am doing things?

I know nothing about this but shouldn’t you have the array brackets after the name attributes here.

$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="username" /></td><td><input type="text" name="emaill" /></td><td><button type="button" name="remove" id="'+i+'" class="btn_remove">Remove</button></td></tr>');

e.g.
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="username[]" /></td><td><input type="text" name="emaill[]" /></td><td><button type="button" name="remove[]" id="'+i+'" class="btn_remove">Remove</button></td></tr>');

You are using them in the standard html but not in your appended code.

Not sure if it has anything to do with your problem though :slight_smile:

1 Like

nope didnt fixed.

If you leave out the action attribute, the form will still get submitted to the page itself – basically just causing a page refresh here. To post the form data with AJAX instead, you’ll have to prevent the event’s default action:

$('#recruitmember').click(function (event) {
  event.preventDefault()

  $.ajax({
    url: 'include/includeajax/MassRecruitInsert.php',
    method: 'POST',
    data: $('#add_me').serialize(),
    success: function (data) {
      $('#add_me')[0].reset()
    }
  })
})

You might actually specify the action in the form though as a fallback in case something goes wrong with the JS:

$('#add_me').submit(function (event) {
  event.preventDefault()

  $.ajax({
    method: 'POST',
    url: event.target.action,
    data: $(event.target).serialize(),
    success: function (data) {
      event.target.reset()
    },
    error: console.error
  })
})

In addition, you’ll also have to use the bracket notation as @PaulOB said.

1 Like

i just change that code

$('#add_me').submit(function (event) {
  event.preventDefault()

  $.ajax({
    method: 'POST',
    url: event.target.action,
    data: $(event.target).serialize(),
    success: function (data) {
      event.target.reset()
    },
    error: console.error
  })
})

where it says url: event.target.action o the part where the code block above says url: ‘include/includeajax/MassRecruitInsert.php’,

so its like this??

('#recruitmember').submit(function (event) {
  event.preventDefault()

  $.ajax({
    method: 'POST',
   	url: 'include/includeajax/MassRecruitInsert.php',
    data: $(event.target).serialize(),
    success: function (data) {
      event.target.reset()
    },
    error: console.error
  })
})

??

Ah sorry forgot to mention that I also changed

$('#recruitmember').click(/* ... */)

to

$('#add_me').submit(/* ... */)

so that event.target refers to the form, not the submit button. Apart from that both variants are mostly equivalent here, but you’ll have to use either of them – there’s no submit event getting dispatched on a button.

ok so this is my code now

	  	$('#recruitmember').submit(function (event) {
		  event.preventDefault()
		  $.ajax({
			method: 'POST',
			url: 'include/includeajax/MassRecruitInsert.php',
			data: $(event.target).serialize(),
			success: function (data) {
			  event.target.reset()
			},
			error: console.error
		  })
		})
 });  

because i get this error

jQuery.Deferred exception: “#add_me”.submit is not a function TypeError: “#add_me”.submit is not a function

so my code looks like

That’s still the same as in your previous reply…?

This suggests you’re trying to call .submit() on the string "#add_me", not the jQuery element $('#add_me').

There’s no code to see… did you maybe forget to format it as code? If it contains HTML, it will get completely filtered out otherwise to prevent code injection.

this is my jquery code now

	  	$('#recruitmember').submit(function (event) {
		  event.preventDefault()
		  $.ajax({
			method: 'POST',
			url: 'include/includeajax/MassRecruitInsert.php',
			data: $(event.target).serialize(),
			success: function (data) {
			  event.target.reset()
			},
			error: console.error
		  })
		})
 });  

and html code now

<form method="post" name="add_me" id="add_me">
                            <table style="color:#FFF;" id="dynamic_field">
                                <tr>
                                    <td colspan="3">Recruit Multiple Members</td>
                                </tr>
                                <tr>
                                    <td>Username:</td>
                                    <td>Email:</td>
                                    <td>Task</td>
                                </tr>
                                <tr>
                                    <td><input type="text" name="username[]" /></td> 
                                    <td><input type="text" name="email[]" /></td>
                                    <td><input type="button" name="add" id="add" value="Add Another" /></td>
                                </tr>
                            </table>
                            <input type="submit" name="recruitmember" id="recruitmember" value="Recruit Member"/>
                        </form>

so the above code in jquery does that look ok or need to be fixed.

Please see my reply #6 again. It should be either

$('#recruitmember').click(/* ... */)

or

$('#add_me').submit(/* ... */)

but not

$('#recruitmember').submit(/* ... */)

In case you want to refer to the form as event.target, you’ll have to use the 2nd variant… personally I find this a bit cleaner, but that’s a matter of taste I suppose. There’s also a small performance benefit in that you don’t have to query the DOM for $('#add_new') anew but can directly reference the DOM element itself.

Sorry for the confusion! ^^

ok so i went ahead and and made that change the jquery code is below

  	$('#add_me').submit(function (event) {
		  event.preventDefault()
		  $.ajax({
			method: 'POST',
			url: 'include/includeajax/MassRecruitInsert.php',
			data: $(event.target).serialize(),
			success: function (data) {
			  event.target.reset()
			},
			error: console.error
		  })
		})
 });  

but does not print any error this is correct as to what i have at the moment isnt it??

Yes. :-) It should also clear the form when the response arrived.

but still nothing gets returned or inserted into my database this is my php code


include("dbconnect.php");
$number = count($_POST["username"]);
 for($i=0; $i<$number; $i++)
 {
	 $pQuery="insert into members (username,password,rank,email,disable,Recruitedby,LastedLogin,joineddate,web,recruits,signons,ia,joineddate2) values('".mysqli_real_escape_string($con, $_POST["username"][$i]).
				"','".mysqli_real_escape_string($con, $_POST["password"][$i]).
				"','1','".mysqli_real_escape_string($con, $_POST["email"][$i]).
				"','1','$recruiter','$today','$today','0','0','0','0','$today4')";
			echo $pQuery;
				$LQuery="INSERT INTO logs Values('','$rank','$recruiter','sucessfully recruited $username on','$today','Recruitment')";
				$rQuery="update members set recruits=recruits+$number where username='".$_SESSION['user']."'";
				$result=mysqli_query($con,$pQuery);
				$result=mysqli_query($con,$LQuery);
				$result=mysqli_query($con,$rQuery);
				if(!$result)
				{
					echo "Error:".mysqli_connect_errno();
					echo "<br/>Error2:".mysqli_error($con);
				}
				else
				{
					echo "<br/><br/>Member Add to Clan<br/>
					The Recruits Login information is as follows:<br/>
					<br/>
					Username: $user <br/>
					Password: $password <br/>
					<br/>
					<br/>
					Please Make Sure the Recruit Logins and Changes his password";
					$clanwebsite=$_SERVER['HTTP_HOST'];
					mail("$email", "Welcome to $ClanName!", "$username
					Welcome to $ClanName!  You are now, the newest member of our great clan!  
					____________________________________________________________
					Here is your information:
					User Name:			$user
					Password:			$password
					
					Website For Clan is $clanwebsite
					
					Ensure you don't lose this information.  If you have a problem with loggin in, please
					feel free to contact an officer and they can assist you.
					____________________________________________________________");
				}
 }
 echo "Data Inserted Successfully";

Please use the browser console to confirm in the Network tab that the form get submitted properly.
You can also var_dump $post to confirm that the information arrived properly.

If there are any further issues beyond that relating to PHP, I recommend that that they be followed up with by our experts in the PHP forum.

1 Like

nothing gets posted back.

I’ve commented in the thread you started on the PHP forum - there’s quite a few variables in that PHP code that don’t appear to have been defined anywhere. If the table requires them and you post nulls, that would prevent the insert.

I’m learning jquery / JS, but it seems to me that your PHP code does send error codes and responses, but you don’t display any of the return from it, you just clear the form. If you do this, does it tell you anything?

ok so i went ahead and and made that change the jquery code is below

  	$('#add_me').submit(function (event) {
		  event.preventDefault()
		  $.ajax({
			method: 'POST',
			url: 'include/includeajax/MassRecruitInsert.php',
			data: $(event.target).serialize(),
			success: function (data) {
// *** ADD THIS LINE
alert(data);

			  event.target.reset()
			},
			error: console.error
		  })
		})
 });

In theory that will show a pop-up with whatever your PHP script outputs.

But did you check the network panel if the request gets sent in the first place? If so, what’s the response code?

1 Like

Sweet baby Jesus there are so many things wrong with your code. I got a headache trying to read your code my friend, especially the mail(); part.

<?php
//Instead of doing include(dbconnect.php); just copy and paste it like you see below
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}


$number = count($_POST["username"]);
for ($i=0; $i<$number; $i++) {
	$post_username = mysqli_real_escape_string($con, $_POST["username"][$i]);
	$post_password = mysqli_real_escape_string($con, $_POST["password"][$i]);
	$post_email = mysqli_real_escape_string($con, $_POST["email"][$i]);
	
	//Where is the value for these coming from? If you are not inserting anything into
    //these fields in the DB DO NOT include them in your INSERT SQL
	$rank = ?
	$recruiter = ?
	$today = ?
	$Recruitment = ?
	$pQuery="INSERT INTO members (username, password, email) VALUES ('$post_username', '$post_password', '$post_email')";
    //What are the fields for the insert for INSERT INTO logs? 
	$LQuery="INSERT INTO logs () VALUES ('$rank','$recruiter','$username','$today','$Recruitment')";
	$rQuery="UPDATE members SET recruits = recruits+$number WHERE username='$_SESSION[user]'";

	$result = mysqli_query($con, $pQuery);
	$result = mysqli_query($con, $LQuery);
	$result = mysqli_query($con, $rQuery);

	if (!$result) {
		echo "Error:".mysqli_connect_errno();
		echo "<br/>Error2:".mysqli_error($con);
	} else {
		echo "<br/><br/>Member Add to Clan<br/>
		The Recruits Login information is as follows:<br/>
		<br/>
		Username: $user <br/>
		Password: $password <br/> 
		<br/>
		<br/>
		Please Make Sure the Recruit Logins and Changes his password";

		$clanwebsite = $_SERVER['HTTP_HOST'];
		$email = mysqli_real_escape_string($con, $_POST["email"][$i]);
		$ClanName = ?

		$mail_to= 'To: '.$email. "\r\n";
		$subject = 'Welcome to '.$ClanName;
		$body_message = "$username, welcome to $ClanName! You are now, the newest member of our great clan!<br><br>";
		$body_message .= "Here is your information:<br>";
		$body_message .= "User Name: $user<br>";
		$body_message .= "Password: $password<br>"; //This is not a good idea
		$body_message .= "Website For Clan is $clanwebsite. ";
		$body_message .= "Ensure you don't lose this information. If you have a problem with loggin in, please ";
		$body_message .= "feel free to contact an officer and they can assist you.<br>";

		$headers  = "From: Enter your name or business name < myemail@mail.com >\n";
		$headers .= "X-Sender: Enter your name or business name < myemail@mail.com >\n";
		$headers .= 'X-Mailer: PHP/' . phpversion();
		$headers .= "X-Priority: 1\n"; // Urgent message!
		$headers .= "Return-Path: myemail@mail.com\n"; // Return path for errors
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: text/html; charset=iso-8859-1\n";

		$mail_status = mail($mail_to, $subject, $body_message, $headers);

		echo "Data Inserted Successfully"; // Why was this placed outside of the if statement? What happens if the INSERT is not successfull? It's still going to keep showing this error because you placed it outside of your IF statement
	}
}

mysqli_close($conn);

?>

Hi William,

For all of your JavaScript sections of code, I’ve been testing them using jsfiddle and have found that they all result in browser console errors that say: Uncaught SyntaxError: Unexpected token }

You have an additional }) line that’s not required.

The working JavaScript code is:

$('#add_me').submit(function(event) {
    event.preventDefault()
    $.ajax({
        method: 'POST',
        url: 'include/includeajax/MassRecruitInsert.php',
        data: $(event.target).serialize(),
        success: function(data) {
            event.target.reset()
        },
        error: console.error
    });
});

Thanks for the help only issue now is trying to figure out how to pass multiple usernames and emails for form submission

what i mean is if i create users like

user1 email
user2 email2
user3 email3

when i click on my submit those 3 users shud be inserted with their email addresss for each row.

any idea on how to go about that? i thought the way i coded my php form submission code it would fix it.