Unable to submit multiple form using ajax without refreshing the page

Hello,

I have 2 form tags in my script which the user will submit separately without refreshing the page.
the example below has both forms. if i take out one of the form and the java script pertains to the form the script working and if in included both form and the js the script wontw ork.

Any ideas as to how to fix the problem?


<!DOCTYPE html>
<html>
	<head>
		<meta charset="ISO-8859-1">		
		<script src="http://code.jquery.com/jquery-latest.js"></script>
		<script type="text/javascript" >
			$(function()
			{	$(".submit1").click(function(e)
				{	
					var fname = $("#fname").val();
					var lname = $("#lname").val();
					var dataString = 'fname='+ fname + '&lname=' + lname;
					if(fname=='' || lname=='')
					{	$('.success').fadeOut(200).hide();
						$('.error').fadeOut(200).show();
					}
					else
					{	$.ajax(
						{	type: "POST",
							url: "data1.php",
							data: dataString,
							success: function()
							{	$('.success').fadeIn(200).show();
								$('.error').fadeOut(200).hide();
								$("#fname").val("");
								$("#lname").val("");
							}
						});						
					}
					return false;					
				});				
			});
/**************************************************************************/			
			$(function()
			{	$(".submit2").click(function(e)
				{	var fname2 = $("#fname2").val();
					var lname2 = $("#lname2").val();
					var dataString = 'fname='+ fname2 + '&lname=' + lname2;
					if(fname2=='' || lname2=='')
					{	$('.success').fadeOut(200).hide();
						$('.error').fadeOut(200).show();
					}
					else
					{	$.ajax(
						{	type: "POST",
							url: "data1.php",
							data: dataString,
							success: function()
							{	$('.success').fadeIn(200).show();
								$('.error').fadeOut(200).hide();
								$("#fname2").val("");
								$("#lname2").val("");
							}
						});						
					}
					return false;					
				});				
			});	
</script>
	</head>
	<body>
		<div style="width:500px; height:100px; border:1px solid red;">
			<div style="float:left; width:240px; border:1px solid green">
				<?php echo rand(10,1000); ?>
			</div>
			<div style="float:left; width:240px; border:1px solid blue">
				<form   method="post" name="form1">
					First name: <input name="fname" id="fname" type="text" /><br />
					Last name: <input name="lname" id="lname" type="text" /><br />
					<input type="submit" value="Submit" class="submit1"/>
					<span class="error" style="display:none"> Please Enter Valid amount</span>
					<span class="success" style="display:none"> Bid submitted</span>
				</form>
			</div>
		</div>
		<br><br>
<!--********************************************************************-->			
		<div style="width:500px; height:100px; border:1px solid red;">
			<div style="float:left; width:240px; border:1px solid green">
				<?php echo rand(10,1000); ?>
			</div>
			<div style="float:left; width:240px; border:1px solid blue">
				<form   method="post" name="form2">
					First name: <input name="fname2" id="fname2" type="text" /><br />
					Last name: <input name="lname2" id="lname2" type="text" /><br />
					<input type="submit" value="Submit" class="submit2"/>
					<span class="error" style="display:none"> Please Enter Valid amount</span>
					<span class="success" style="display:none"> Bid submitted</span>
				</form>
			</div>
		</div>		
		
	</body>
</html>

Maybe something like the following?

var dataString = { fname: fname, lname: lname } // Set parameters
myData = jQuery.param( dataString ); // Set parameters to corret AJAX format

//  code in between....

$.ajax({
	type:"post",
	url:"data1.php",
	data: myData,
	success:function(info) {
		$('#result').html(info); // Display the result back when saved: 
                // your code....
	}

I would imagine you would have to do something like that to the second form as well…

I’m not an expert in Ajax, but I consider myself pretty good at it. So this may or may not help?

I know it’s not PHP, but I used the php tags for I think it looks nicer. :smiley:

The first thing to notice is that you have two nearly identical sets of scripting code, which is a huge “code smell”, in this case that you are violating the principle of DRY - don’t repeat yourself. To deal with that we can remove the nearly duplicate set of scripting code, and adjust the script so that it can easily work across multiple copies.

Currently the script is attached to the form by attaching to a unique class name, which is not the best way to do things. When attaching to the submit event of a form, it’s usually best to use the jQuery’s on method, such as:


$('form').on('submit', function (e) {

If there are other forms that you don’t want to attach to, then a next-best approach is to use a class name on the forms themself, as this allows multiple copies of that form to co-exist:

Note: the name attribute that you currently have in your code is next to useless, so remove it.


<form method="post" class="bid">


$('form.bid').on('submit', function (e) {

Moving on down the script to the next line, it is not appropriate to use unique identifiers in a script that is designed to handle multiple forms. The unique identifiers need to be removed from your script, and the HTML code, so that you can more easily work with things.

The best way to access form elements such as first and last name is via the elements collection of the form. Because the submit event is attached directly to the form, you can easily reference the form via the this keyword., and access other form elements from there.


First name: <input name="fname" type="text" /><br />
Last name: <input name="lname" type="text" /><br />


var form = this,
    fname = form.elements.fname,
    lname = form.elements.lname,

The above fname and lname references to the field itself and not their text values, so that we can easily reference the fields later on when a successful post is made.

Speaking of posting, when posting form data the easiest and most guaranteed way to ensure that you post all of the form fields is to use the serialize() method:


var dataString = $(form).serialize();

With the success and error parts, those can be referenced individually with respect to the form that they are in too. (The error should fadeIn instead of fadeOut, too):


$('.success', form).fadeOut(200).hide();
$('.error', form).fadeIn(200).show();

Checking fname and lname just checks their value, and later in the success method they are cleared too.


if (fname.value === '' || lname.value === '') {
...
fname.value = '';
lname.value = '';

And lastly, returning false from an event can be misleading. What are you disabling? Are you disabling the bubbling up of the event to parent elements, or are you preventing the default behaviour, or both?

It’s better to just make it clear just what you are doing instead with preventDefault:


e.preventDefault();

Here’s a working version of what has been discussed:


<!DOCTYPE html>
<html>
    <head>
        <meta charset="ISO-8859-1">
    </head>
    <body>
        <div style="width:500px; height:100px; border:1px solid red;">
            <div style="float:left; width:240px; border:1px solid green">
                <?php echo rand(10,1000); ?>
            </div>
            <div style="float:left; width:240px; border:1px solid blue">
                <form method="post" class="bid">
                    First name: <input name="fname" type="text" /><br />
                    Last name: <input name="lname" id="lname" type="text" /><br />
                    <input type="submit" value="Submit" />
                    <span class="error" style="display:none"> Please Enter Valid amount</span>
                    <span class="success" style="display:none"> Bid submitted</span>
                </form>
            </div>
        </div>
        <br><br>
        <div style="width:500px; height:100px; border:1px solid red;">
            <div style="float:left; width:240px; border:1px solid green">
                <?php echo rand(10,1000); ?>
            </div>
            <div style="float:left; width:240px; border:1px solid blue">
                <form method="post" class="bid">
                    First name: <input name="fname" type="text" /><br />
                    Last name: <input name="lname" type="text" /><br />
                    <input type="submit" value="Submit" />
                    <span class="error" style="display:none"> Please Enter Valid amount</span>
                    <span class="success" style="display:none"> Bid submitted</span>
                </form>
            </div>
        </div>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript" src="submitbid.js></script>
    </body>
</html>


$(function () {
    $('form.bid').on('submit', function (e) {
        var form = this,
            fname = form.elements.fname,
            lname = form.elements.lname,
            dataString = $(form).serialize();
        if (fname.value === '' || lname.value === '') {
            $('.success', form).fadeOut(200).hide();
            $('.error', form).fadeIn(200).show();
        } else {
            $.ajax({
                type: "POST",
                url: "data1.php",
                data: dataString,
                success: function () {
                    $('.success', form).fadeIn(200).show();
                    $('.error', form).fadeOut(200).hide();
                    fname.value = '';
                    lname.value = '';
                }
            });
        }
        e.preventDefault();
    });
});