Updating wordpress form via AJAX does not work the second time

I have built a theme options page in wordpress using settings api. I want to update the forms on the page using ajax. They seem to be working fine the first time, but when I click “submit” again without refreshing the page, the whole page just gives me a “0”.
Please note that since i am handling errors and validation using wordpress native, the whole form is reloaded using AJAX. I know this is weird since the form that triggers the ajax request itself is reloaded. Let me know if there is a workaround for this. Here is the code

$cg("#cgform").submit(function(){
    var b = $cg(this).serialize();
    var cgdata =  { action : "cg_options_save", cgnonce: cgform.cgnonce ,data: b };
    cg_ajax_request(cgdata,cg_form_callback);  
    return false;
});

//Ajax request
function cg_ajax_request(data,fcall){
    $cg.post(ajaxurl, data, function (response) {fcall(response);}); 
}

The cg_ajax_callback function populated the received form inside a div.

Read More

Please let me know the “correct” way to handle this

Related posts

Leave a Reply

1 comment

  1. The problem is that the event handler is bound to the form which is reloaded by the ajax call. The second time you try to submit the form it’s actually the new instance that was inserted by the first ajax call, which doesn’t have an event handler attached to it. Use the on method to bind the event handler instead, this will dynamically bind the event handler to the new form when it’s inserted.

    $cg(document).on('submit', "#cgform", function(){
        var b = $cg(this).serialize();
        var cgdata =  { action : "cg_options_save", cgnonce: cgform.cgnonce ,data: b };
        cg_ajax_request(cgdata,cg_form_callback);  
        return false;
    });