Mihail Ivanchev Mihail Ivanchev - 6 months ago 10
Ajax Question

Hide one button and show another one after ajax completes

I have a form for registration, that is a two step process. For that reason, I have two buttons:

<button style="display: block" type="submit" name="check" id="check" class="btn btn-primary btn-block"><?php esc_html_e('Check', 'theme'); ?></button>
<button style="display: none;" type="submit" name="book" id="book" class="btn btn-primary btn-block"><?php esc_html_e('Book', 'theme'); ?></button>


My idea is you check something when pressing the first button, that calls on my JavaScript code, that runs an AJAX request. At the end of the request, I want to hide the first button, and show the second one, that is used to submit the whole form (first button checks dates, and then shows more fields).
However, this does not work. Here is my JavaScript code:

$("#reservationform").submit(function(e) {
var url = document.getElementById('reservationform').action,
fromDate = document.getElementById('checkin').value,
toDate = document.getElementById('checkout').value,// the script where you handle the form input.
dataString = 'fromDate=' + fromDate + '&toDate=' + toDate;
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function(name)
{
document.getElementById('rooms').innerHTML = name;
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
$("button#check").css("display", "none");
$("button#book").css("display", "block");
});


Code works up until the last 3 lines, as the default event is blocked, my code is submitted and I get the requested data back as specified in a div with id="rooms". What am I doing wrong, because the buttons are not being hidden/shown?

Answer
$("#reservationform").submit(function(e) {
    var url = document.getElementById('reservationform').action,
        fromDate = document.getElementById('checkin').value,
        toDate = document.getElementById('checkout').value,// the script where you handle the form input.
        dataString = 'fromDate=' + fromDate + '&toDate=' + toDate;
    $.ajax({
        type: "POST",
        url: url,
        data: dataString,
        success: function(name)
        {
            document.getElementById('rooms').innerHTML = name;
        },
        complete: function() {
          // write it here

          $("button#check").css("display", "none");
          $("button#book").css("display", "block");
        }
    });

    e.preventDefault(); // avoid to execute the actual submit of the form.

});