Solorzano Jose
Solorzano Jose

Reputation: 632

jQuery on submit issue

For some reason my submit event is not working, however, if i change it to click on the form, it works, this is my code:

JQUERY:

 <script>
(function(){
        $('form').on('click',function(){

                $.post("../includes/register.php",  $('form').serialize(),
                function(data){
                    $('body').append(data);                 
                });
        });
    })();
</script>

REGISTER.PHP:

<?php 

if(isset($_POST['username'])){
echo $_POST['username'];
}
?>

This works perfectly fine, it appends the username whenever I click on a form text input, however, when I try to use the submit method, it doesnt output anything:

<script>
(function(){
        $('form').submit(function(){

                $.post("../includes/register.php",   $('form').serialize(),
                function(data){
                    $('body').append(data);                 
                });
        });
    })();
</script>

As a matter of fact, it doesn't even work when I use button.on('click')

Upvotes: 0

Views: 64

Answers (3)

Ram
Ram

Reputation: 144699

You are using an immediately invoked function instead of document ready handler, also you should prevent the default action of the event, try the following:

$(function(){
    $('form').on('submit',function(event){
        event.preventDefault();
        $.post("../includes/register.php",  $(this).serialize(),
        function(data){
            $('body').append(data);                 
        });
    });
});

Upvotes: 1

Kyle d&#39;Oliveira
Kyle d&#39;Oliveira

Reputation: 6382

This is speculation right now since I do not know what your HTML code looks like.

But on submit the form will be submitted, and any active ajax requests will be cancelled. Try something like

<script>
(function(){
   $('form').submit(function(){    
     $.post("../includes/register.php",   $('form').serialize(),
       function(data){
         $('body').append(data);                 
     });
     return false;
   });
  })();
</script>

That will stop the submit event and you should get the post event to occur. Though it will NOT actually submit the form. So you'll have to do that manually.

Upvotes: 0

danronmoon
danronmoon

Reputation: 3873

The form will submit to the form's action by default. You need to prevent this from happening. You are waiting for a server response via ajax, so it is most likely you will never witness your callback executing before the default action occurs.

$('form').submit(function(e){
            e.preventDefault(); // put this first
            $.post("../includes/register.php",   $('form').serialize(),
            function(data){
                $('body').append(data);                 
            });
    });

Upvotes: 0

Related Questions