ojek
ojek

Reputation: 10056

How to execute .load() on http post?

In my application, I have a piece of code that "catches" all the clicks on an anchor, and loads it into my page:

$("a").live("click", function () {
    var src = $(this).attr("href");
    if ($(this).attr("target") === "_blank")
        return true;
    $("#myPage").load(src + " #myPage");
    return false;
});

Now this works on all anchor tags. How can I make all my POST requests (sending forms data) behave like that?

Edit: As Kevin said, I tried using .post, but it doesn't work for me, what did I do wrong? Here's the code:

$("form").post("submit", function () {
    var src = $(this).attr("action");
    $("#myPage").load(src + " #myPage");
    return false;
});

Upvotes: 0

Views: 81

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Use the form submit event to handle form POST case

$(document).on('submit', 'form', function(){
    var $this = $(this);

    $.ajax({
        url: $this.attr('action'),
        type: 'POST',
        data: $this.serialize()
    }).done(function(responseText){
        $("#myPage").html(responseText)
    });

    return false;
})

Since you are using jquery 1.9, you may have to rewrite the a handler as

$(document).on("click", 'a', function () {
    var src = $(this).attr("href");
    if ($(this).attr("target") === "_blank")
        return true;
    $("#myPage").load(src + " #myPage");
    return false;
});

Upvotes: 1

Related Questions