Ad

Replace Form With Results After AjaxSubmit

- 1 answer

I am trying to dynamically replace a form with the results from the POST response. For this example, I am closing an announcement and would like the "Close Announcement" submit button / form to be replaced by simply "Announcement Closed" upon its success. The POST works fine and I can return the results as expected, just not in the specific div.

I figure the $post->ID would be a unique ID so I can remove that div, but I don't know how to pass it to the ajaxSubmit function.

<div id="<?php echo $post->ID;?>">
  <form action="" method="post" id="openclose">
    <input type="hidden" name="id" value="<?php echo $post->ID;?>"/>
    <input type="hidden" name="action" value="ocVehicleWanted"/>
    <input type="hidden" name="oc" value="close">
    <button type="submit" style="padding:1px;background-color:#c41f1f;" >Close Announcement</button>
  </form>
</div>

This is my current jQuery, the only portion that is not working is the .html(data) for replacing the form data in the $post->ID div. This current code replaces all of the form divs that were output for the page. I have 25 of these per page.

jQuery('#openclose').submit(ajaxSubmit);

function ajaxSubmit(){

var vehicledata = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: vehicledata,
success:function(data){
jQuery("#openclose").html(data);
}
});

return false;
}
Ad

Answer

Change ID's to class since ID's must be unique in a page

You can replace the whole form several ways by starting with this and a traverse to parent() or by using replaceWith() as well as several other ways

function ajaxSubmit() {
    var $form = jQuery(this);// cache form as jQuery object
    var vehicledata = $form.serialize();
    jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: vehicledata,
        success: function(data) {
            // replace form parent html
            $form.parent().html(data);
            // or replaace form element
            $form.replaceWith(html);
        }
    });
}
Ad
source: stackoverflow.com
Ad