简体   繁体   中英

Nothing happening on jQuery post

Below is my jQuery function that is used to post the values of name, password and email to register.php and then display a message echoed in register.php in div#message .

However when I click the postBtn nothing happens and the console does not log clicked.

jQuery

$(document).ready(function() {
    $("#btnPost").on("click", function() {
        console.log('clicked'); 
        var thisBtn = $(this); 
        var parent = thisBtn.parent(); 

        name = parent.data('name'); 
        password = parent.data('password'); 
        email = parent.data('email');

        $.post(
            'register.php', 
            { 
                name: ('name'), 
                password: ('password'), 
                email: ('email')
            },          
            function(data) {
                parent.next('#message').html(data);
            }
        );
    });
});

This is the HTML block where all the data is input, however nothing seems to be happening when the button #postBtn is clicked.

<table>
    <tr>
        <td> Username: <td>
        <td> <input type = "text"  class = "field" name = "name"> </td>
    </tr>
    <tr>
        <td> Password: <td>
        <td> <input type = "password" class = "field" name = "password"> </td>
    </tr>
        <td > Email: <td>
        <td> <input type = "email" class = "field" name = "email"> </td>
    </tr>
    <tr>
        <td>  <td>
        <td> <button  class='regular' id = "btnPost" name='save'> Log In  </button></td>
    </tr>
    <tr>
</table>

I had a similar issue to yourself using the same syntax, I re-worked mine to something along the following lines and it solved the issue....

try:

$(document).on("click", "#btnPost", function() { //implementation });

You can change $(document) to the name of a containing div, or something at a lower-level, so long as #btnPost is contained within it.

Check the order of jQuery library files included in to the source(HTML). First jQuery library file and then your javascript file. It seems your code is working fine in jsfiddle. one of the reason may be the jQuery file is not there or loading order may be mismatched.

Your problem is your use of .next() , which returns the next sibling of the current element. And since you are passing in a selector, you will only get a result if the next sibling satisfies the selector, otherwise you get nothing. Just use $("#message") since #message is not the next sibling following the parent element of your button.

$.post( 
    'register.php',  
    {  
        name: ('name'),  
        password: ('password'),  
        email: ('email') 
    },           
    function(data) { 
        $('#message').html(data); 
    } 
); 

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