Tim C
Tim C

Reputation: 5714

Ajax form duplicating on submit

I have 3 selectboxes the value of each selectbox gets populated based on the selection of the selectbox before it:

selectbox1 =>populates => selectBox2 => populates selectBox 3:

enter image description here

Now when user clicks submit I want to use the values from the selectboxes to query my database

My Problem

When I click submit:

enter image description here

So in short the variables are being passed correctly to my php code but the form duplicates on submit...

Code for sending form data

I believe the problem is somewhere in this code

 <script type="text/javascript">
jQuery(document).click(function(e){
    var self = jQuery(e.target);
    if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
        e.preventDefault();
        var form = self.closest('form'), formdata = form.serialize();
        //add the clicked button to the form data
        if(self.attr('name')){
            formdata += (formdata!=='')? '&':'';
            formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
        }
        jQuery.ajax({
            type: "POST",
            url: form.attr("action"), 
            data: formdata, 
             success: function(data) {$('#resultForm').append(data);  }
        });
    }
});
</script>

HTML

<form method="post" id="resultForm" name="resultForm">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
    include('connect.php');
 $sql="SELECT distinct sport_type FROM events";
 $result=mysql_query($sql);
 while($row=mysql_fetch_array($result))
 {
  ?>
        <option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
        <?php
 } 
?>
</select>

<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>


<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>

Upvotes: 1

Views: 1253

Answers (1)

Sulthan Allaudeen
Sulthan Allaudeen

Reputation: 11320

You're appending the result.

If you don't want to duplicate then replace the new content with old one.

Just change this

success: function(data) {$('#resultForm').append(data);  }

to

success: function(data) {$('#resultForm').replaceWith(data);  }

or even

success: function(data) {$('#resultForm').html(data);  }

See more details about replacewith here

Upvotes: 3

Related Questions