Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax call doesn't work within click() in Javascript

I'm trying to update my page dynamically using ajax and php. The ajax call works fine until I put it within a click() function. The alert works ok

$(document).ready(function(){
    $("#formbutton").click(function(){
        alert("test");
        $.ajax({
            url: 'url.php',
            type: 'GET',
            dataType: 'html',
            success: function (data) {
                $("#response").html(data);
            }
        });
    });
});

This works fine in debugging:

$(document).ready(function(){
    alert("test");
    $.ajax({
        url: 'url.php',
        type: 'GET',
        dataType: 'html',
        success: function (data) {
            $("#response").html(data);
        }
    });
});

What am I doing wrong? Thanks

like image 487
gls Avatar asked Mar 26 '26 06:03

gls


1 Answers

Is the button inside a FORM tag?

If that is the case, take into account that the default behavior of a button is to submit the form, probably you don't see the AJAX response because the default event handler of the submit form is executed before the AJAX success handler.

Try to:

  • Remove the FORM if you don't need it.

  • If you want to keep the form, use a "preventDefault":

    $('#formbutton').click(function(evt) { evt.preventDefault(); /* ... */ });
    
  • If you are using a button tag, you can also change the type to "button": <button type="button">, so you ensure that the browser is not using type=submit as default.

like image 86
Diego Avatar answered Mar 27 '26 20:03

Diego



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!