PHP Jquery POST - sends duplicate data

1.6k Views Asked by At

I have a PHP form that sends data with the help of jQuery. Whenever I click "submit" I see it sends the data twice which results in double database entries and so on.

Also I am still working on how to display "errors" and Exceptions from the try/catch block.

Note: This form worked on another site, I changed just fields and where it sends the data but can't get it to work.

THANK YOU for your help.


Registration form

<div id="registration" class="representativeForm">
 <div class="result">
 </div>
 <div class="formbody">
  <div class="left">
   <input required="required" type="text" name="name" placeholder="Your name" />
   <input required="required" type="text" name="surname" placeholder="Your surname" />
   <input required="required" type="text" name="birthdate" placeholder="Your birth date" />
   <input required="required" type="text" name="nationality" placeholder="Your nationality" />
   <?php  countriesSelection($con, $_LANG, "country"); ?>
   <input required="required" type="email"  name="email" placeholder="Your Email adress" />
   <input required="required" type="text" name="position" placeholder="Your title or job position" />
   <div class="schoolSelectionfields">
    <?php schoolSelection($con, $_LANG, "schools");  ?>
   </div>
   <input type="checkbox" id="schoolnotlisted" name="schoolnotlisted" value="1">Your school is not listed? Register school here.<br />
  </div>
  <div class="right">
   <div class="school_register">
    <?php  schoolRepresentativeRegistration($_LANG, $con); ?>
   </div>
  </div>
 </div>
 <input type="hidden" name="form" value="representativeForm">
 <input type="submit" value="Register" id="representativeSubmit" />
</div>


jQuery Code

 $("#representativeSubmit").click(function() { 

    var proceed = true;
    //simple validation at client's end
    //loop through each field and we simply change border color to red for invalid fields
    $("#registration.representativeForm input[required=true]").each(function(){
        $(this).css('border-color',''); 
        if(!$.trim($(this).val())){ //if this field is empty 
            $(this).css('border-color','red'); //change border color to red   
            proceed = false; //set do not proceed flag
        }
        //check invalid email
        var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; 
        if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))) {
            $(this).css('border-color','red'); //change border color to red   
            proceed = false; //set do not proceed flag              
        }
    });
    if(proceed) //everything looks good! proceed...
    {
        //get input field values data to be sent to server
        post_data = {
            'form'     : $('input[name=form]').val(),
            'name'     : $('input[name=name]').val(), 
            'surname'    : $('input[name=surname]').val(), 
            'birthdate'  : $('input[name=birthdate]').val(), 
            'nationality'  : $('input[name=nationality]').val(), 
            'email'  : $('input[name=email]').val(), 
            'position'  : $('input[name=position]').val(), 
            'country'  : $('select[name=country]').val(), 
        };

        if($("#schoolnotlisted").prop('checked') == true) {
            post_data += {
                'schoolName'  : $('input[name=schoolName]').val(), 
                'schoolAddress'  : $('input[name=schoolAddress]').val(), 
                'schoolZipcode'  : $('input[name=schoolZipcode]').val(), 
                'schoolCity'  : $('input[name=schoolCity]').val(), 
                'schoolCountry'  : $('select[name=schoolCountry]').val()
            };
        }
        else {
            post_data += {
                'schools'  : $('select[name=schools]').val()
            };
        }
        //Ajax post data to server
        $.post('registration.php', post_data, function(response){  
            if(response.type == 'error'){ //load json data from server and output message     
                output = '<div class="error">'+response.text+'</div>';
            }else{
                output = '<div class="success">'+response.text+'</div>';
                //reset values in all input fields
                $("#registration.representativeForm  input[required=true]").val(''); 
                $("#registration.representativeForm .formbody").slideUp(); //hide form after success
            }
            $("#registration .result").hide().html(output).slideDown();
        }, 'json');
    }
});
//reset previously set border colors and hide all message on .keyup()
$("#registration.representativeForm  input[required=true]").keyup(function() { 
    $(this).css('border-color',''); 
    $(".result").slideUp();
});
3

There are 3 best solutions below

3
Jan On

Try to change the event handler to the form itself rather than to the submit button and put an event.preventDefault() statement in there. As you did not post your form code, I have simply named it "form".

$( "#form" ).submit(function( event ) {
    event.preventDefault();
    // here comes everything from the click handler attached to "#representativeSubmit"
});

The reason for your doubling posting is that your function attached to the submit function is executed and afterwards the submit event is given to the form as well.

3
Kyle Domingo On

It sends duplicate data because you are binding to the click event of your submit button. After your bound function finishes, the form submits -- triggering a submit event, but you did not bind to this so it sends another request.

You did not include the wrapping form in your code so I am going to assume it exists and somewhere above in your code

Change your line

$("#representativeSubmit").click(function() { 

to

$("#representativeSubmit").closest('form').submit(function() { 

This selects the wrapping form, and binds your routine to that form's submit event.

Also, can you confirm in your browser's developer tool if there are in fact 2 AJAX calls? If you are using Chrome, press F12 and to go the Network tab and filter by XHR. Do this before clicking anything.

enter image description here

0
enqtran On

Fix duplicate request ajax when click

$('#representativeSubmit').unbind().bind('click', function(event){
    event.preventDefault();
    //.....
});