Search code examples
phpjqueryajaxform-submitpage-refresh

ajax request does not stop page from refreshing


what is wrong with this ajax request? the page is still reloading without giving any popups. if i remove everything after the "event.preventDefault();" it will stop page reload so i figure it must something with how i'm using the ajax method. This is for a php-self validating form

<script type="text/javascript">
             //attach submit event handler to the form
       $('#rsgform1').submit(function(event) {

           //prevent the form from submitting by default
           event.preventDefault();

         //Clear result div
       $("#rsgresult").html('');

         //get values from from
          var values = $(this).serialize();

           // do an ajax request   
         $.ajax({
             url: "contact.php",  
            type: "post",
            data: values,
            success: function(){
              alert("success");
              $("#rsgresult").html('Submitted successfully');
            },
            error:function(){
               alert("failure");
             $("#rsgresult").html('There is error while submit');
            }

        });
         </script>

Solution

  • your script has a missing pair of closing brackets }) at the end

    $('#rsgform1').submit(function (event) {
    
        //prevent the form from submitting by default
        event.preventDefault();
    
        //Clear result div
        $("#rsgresult").html('');
    
        //get values from from
        var values = $(this).serialize();
    
        // do an ajax request   
        $.ajax({
            url: "contact.php",
            type: "post",
            data: values,
            success: function () {
                alert("success");
                $("#rsgresult").html('Submitted successfully');
            },
            error: function () {
                alert("failure");
                $("#rsgresult").html('There is error while submit');
            }
    
        });
    });// <-- missing this closing pair