3

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

3
  • 1
    whether the alert is working Commented Mar 1, 2014 at 15:32
  • 1
    Could you show the example that works? Would be easier to spot the differences. Are you sure you have not changed anything else? Commented Mar 1, 2014 at 15:32
  • show us how the other code is like, which the ajax call works fine. I mean how do you run this without click function. Commented Mar 1, 2014 at 15:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Cool! I saw that you are using the AJAX call to get an HTML... take a look to the jQuery load function: api.jquery.com/load , it will save you a couple of lines of code :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.