简体   繁体   中英

Jquery: Ajax call is not working

I'm using Jquery to count the clicks and keypresses by the users.

$(document).ready(function(){
    var countClick = 0;
    var keyClick = 0;


    $("body").mousedown(function(){
        countClick ++;          
    });


    $("body").keypress(function(){
         keyClick ++;               
    });


    $("body").bind('keyup', function(e) {
        if(e.keyCode >= 37 && e.keyCode <= 40){
          keyClick ++;
        }
    }); 


});

Now, I want to send this to another page to save these data, when the user click in send button, but I presume the ajax call is not working and it's very simple.

$('#send').click(function(){        

    $.ajax({
     type: 'post',
     data: {mouse: countClick, teclado: keyClick},
     url: 'save.php',
     dataType: "json",
     success: function(data){
        alert(data);
     },
     error: function (e) {
        console.log(e);
     }
    });
});

But none alerts and console log is being shown. Do I need to "close" a form between button tag and specify method and action ?

<form method="POST" action="#">
 <button id="send"> Send Data </button>
</form>

Or that's not a rule, I don't need a form to make ajax call and send the data?!

You do not necessarily need a form for an ajax call.

  1. Your counter variables do not have scope within the $("#send").click method, they are undefined outside document.ready method

  2. Since you're using Ajax to post, you need to prevent form from submitting automatically when clicking on send button. Since you didn't use button type="button", it defaulted to button type ="submit".

Here's the solution that works

 var countClick = 0; var keyClick = 0; $(document).ready(function(){ $("body").mousedown(function(){ countClick ++; }); $("body").keypress(function(){ keyClick ++; }); $("body").bind('keyup', function(e) { if(e.keyCode >= 37 && e.keyCode <= 40){ keyClick ++; } }); }); $('#send').click(function(event){ $.ajax({ type: 'post', data: {mouse: countClick, teclado: keyClick}, url: 'save.php', dataType: "json", success: function(data){ alert(data); }, error: function (e) { console.log(e); } }); event.preventDefault(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="POST" action="#"> <button id="send" type="button"> Send Data </button> </form> 

Codepen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM