katie hudson
katie hudson

Reputation: 2893

Ajax - Injecting content before page load

I have a basic form with three inputs

<div class="container main-container">
    <form class="form-horizontal" id="my_form">
        <div class="form-group">
            <label for="inputMobile" class="control-label col-xs-3">Mobile</label>
            <div class="col-xs-9">
                <input type="text" class="form-control" id="inputMobile" name="inputMobile" required>
            </div>
        </div>
        <div class="form-group">
            <label for="inputfName" class="control-label col-xs-3">First Name</label>
            <div class="col-xs-9">
                <input type="text" class="form-control" id="inputfName" name="inputfName" required>
            </div>
        </div>
        <div class="form-group">
            <label for="inputlName" class="control-label col-xs-3">Last Name</label>
            <div class="col-xs-9">
                <input type="text" class="form-control" id="inputlName" name="inputlName" required>
            </div>
        </div>
        <div class="form-group">
            <div class="col-xs-10">
                <button type="submit" class="btn btn-primary" id="sbtBtn"></button>
            </div>
        </div>
    </form>
</div>

What I am aiming to do is inject some values into the inputs before this form loads. So via css, I do

.main-container{
    display:none;
}

I then have the following Ajax

$body = $("body");

$(document).on({
    ajaxStart: function() { $body.addClass("loading"); },
    ajaxStop: function() { $body.removeClass("loading"); }
});

$(function () {
    $.ajax({
        method: "POST",
        url: "php/obtainData.php",
        dataType: "json",
        data: { dataUrl: window.location.href }
    }).done(function( response ) {
            if(response === false || response === 'false') {
                $('.main-container').css('display', 'none');
            } else {
                $('.main-container').css('display', 'block');
                $('input[name="inputMobile"]').val(response.mobile);
                $('input[name="inputfName"]').val(response.fname);
                $('input[name="inputlName"]').val(response.lname);
            }
        }).fail(function( jqXHR, textStatus  ) {
            console.log(textStatus);
        });
    return false;
});

What it essentially does is grab a parameter from the url and passes it to my backend code. My backend then does an API call and returns some values. When it receives its response, if it is ok, then it will display the main-container and append the values to the inputs.

Now it seems to work, but I have noticed some inconsistencies. Sometimes, the main container does not display. But if you refresh the screen a few times, it will display with the data injected. So my guess is that the API call is not given enough time to get the data which needs injecting, or the DOM is being loaded to early.

Is there anything I can do to make this more optimised?

I also have a second ajax request which is only used when the form is submitted. At the moment I have it placed within its own

$(function () {

});

If it is not needed until the form is submitted, does it make any difference if I use the above, or should I place it in its own function which is called on the first ajax requests done callback?

Any advice appreciated

Thanks

Upvotes: 1

Views: 73

Answers (1)

dchayka
dchayka

Reputation: 1302

Overall the code looks fine except you're not using ajaxStart and ajaxStop correctly.

Ref: https://api.jquery.com/ajaxStart/

$(document).ajaxStart(function() {
  $body.addClass("loading");
}).ajaxStop(function() {
  $body.removeClass("loading");
});

Keep in mind ajaxStart/Stop will fire globally on all ajax calls.

Upvotes: 1

Related Questions