Home > Software engineering >  How to pause further execution until the ajax call is finished in JavaScript
How to pause further execution until the ajax call is finished in JavaScript

Time:06-21

Actually I am editing some values in form while fetching from database via ajax on clicking an element i am opening a modalbox and fetch the details from server and put them in appropriate form elements.

there is pin code in that data I want to fetch all the areas of that pin code.

when that pin code have been put in the textbox via jQuery I am calling the keyup() function of jQuery and that will trigger the event which will call the ajax of Fetching Details Of pincode.

now I want to Fetch Those Details And Put The Appropriate Data in textbox(state) which is perfectly done.

I want to put areas in city dropdown but the problem is I also want to auto select the City which is in database after fetching all the cities of that pincode.

but the problem is modal opens before this process is done and it shows the cities later which is weird.

here is my code

Datatable where the edit button is

<div >
    <div >
        <button type="button" data-toggle="modal" data-target="#modal-add-customer"  style="overflow: hidden; position: relative;"><span  style="height: 129px; width: 129px; top: -43.5px; left: -20.9844px;"></span><i ></i> Add <?php echo $page; ?></button>
        <h2><?php echo $page; ?>s</h2>
    </div>
    <div >
        <table id="example-datatable" >
            <thead>
                <tr>
                    <th  style="width: 50px;">ID</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th style="width: 120px;">Status</th>
                    <th  style="width: 75px;"><i ></i></th>
                </tr>
            </thead>
            <tbody>
                <?php
                    $labels[0]['class'] = "label-success";
                    $labels[0]['text'] = "Active";
                    $labels[1]['class'] = "label-warning";
                    $labels[1]['text'] = "Pending..";
                    $labels[2]['class'] = "label-danger";
                    $labels[2]['text'] = "Blocked";
                ?>
                @if($customers->count()>0)
                    @foreach ($customers->get() as $customer)
                    <tr>
                        <td >{{$customer->id}}</td>
                        <td>{{$customer->name}}</td>
                        <td>{{$customer->email}}</td>
                        <td>{{$customer->phone}}</td>

                        <td><span  " . $labels[$customer->status]['class'] : ""}}">{{$labels[$customer->status]['text']}}</span></td>
                        <td >
                            <a href="javascript:void(0)" title="Information"  id="info" data-id="{{$customer->id}}"><i ></i></a>
                            <a href="javascript:void(0)" data-toggle="tooltip" title="Edit"  id="edit" data-id="{{$customer->id}}"><i ></i></a>
                            {{-- <a href="javascript:void(0)" data-toggle="tooltip" title="Delete" ><i ></i></a> --}}
                        </td>
                    </tr>
                    @endforeach
                @endif
            </tbody>
        </table>
    </div>
</div>

Fetching Details From Database

//script for edit customer
        $(".edit").click(function(){
            var custid=$(this).attr('data-id');
            $("#custid").val(custid);
            $.ajax({
                url:"/edit-customer",
                method:"post",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                data:{id:custid},
                error: function (error) {
                    console.log(error);
                    $.bootstrapGrowl('<h4><strong>Unsuccess!!!</strong></h4> <p>' error.statusText '</p>', {
                        type: "danger",
                        delay: 5000,
                        allow_dismiss: true,
                        offset: {from: 'top', amount: 20},
                        align: "center",
                        width: 400
                    });
                },
                success:function(resp){
                    json=$.parseJSON(resp)
                    // console.log(json);
                    $("#editname").val(json.name);
                    $("#editphone").val(json.phone);
                    $("#editemail").val(json.email);
                    $("#editdob").val(json.birthdate);
                    $("#editpincode").val(json.pincode).keyup();
                    $(document).ajaxStop(function () {
                        $("#editcity").val(json.city).change();
                    });
                    $("#editstate").val(json.state);
                    $("#editaddress").val(json.address);
                    $("#modal-edit-customer").modal("show");
                }
            });
        });

Fetching Details Of Pincode

//pincode api code to get city and state.
$(".pincode").keyup(function () {
    let pincode = $(this).val();
    if (pincode.length == 6) {
        $(".city option").not(":first").remove();
        $.ajax({
            url: 'https://api.postalpincode.in/pincode/'   pincode,
            type: 'GET',
            error: function (error) {
                // console.log(error);
                $.bootstrapGrowl('<h4><strong>Unsuccess!!!</strong></h4> <p>'   error.statusText   '</p>', {
                    type: "danger",
                    delay: 5000,
                    allow_dismiss: true,
                    offset: {from: 'top', amount: 20},
                    align: "center",
                    width: 400
                });
            },
            success: function (resp) {
                console.log(resp);
                if (resp[0].Status == "Success") {
                    for (var i = 0; i < resp[0].PostOffice.length; i  ) {
                        $('.city').append($("<option></option>").attr("value", resp[0].PostOffice[i].Name).text(resp[0].PostOffice[i].Name));
                    }
                    $(".state").val(resp[0].PostOffice[0].State);
                } else if (resp[0].Status == "Error") {
                    $(".state").val("");
                    $.bootstrapGrowl('<h4><strong>Wrong!!!</strong></h4> <p>Pincode is Wrong</p>', {
                        type: "danger",
                        delay: 3000,
                        allow_dismiss: true,
                        offset: {from: 'top', amount: 20},
                        align: "center",
                        width: 300
                    });
                } else {
                    $(".state").val("");
                    $.bootstrapGrowl('<h4><strong>Wrong!!!</strong></h4> <p>Pincode is Wrong</p>', {
                        type: "danger",
                        delay: 3000,
                        allow_dismiss: true,
                        offset: {from: 'top', amount: 20},
                        align: "center",
                        width: 300
                    });
                }
            }
        });
    } else {
        $(".city option").not(':first').remove();
        $(".state").val("");
    }
});

Form Modal

<!-- Edit Modal Start-->
<div id="modal-edit-customer"  tabindex="-1" role="dialog" aria-hidden="true">
    <div >
        <div >
            <div >
            <button type="button"  data-dismiss="modal"><i ></i><i ></i></button>
                <h3 ><strong>Edit <?php echo $page; ?></</strong></h3>
            </div>
            <div >
            <form id="edit-customer" method="post" >
                <input type="hidden" name="custid" id="custid" >
                <div >
                    <label  for="editname">Name <span >*</span></label>
                    <div >
                        <input type="text" id="editname" name="editname"  placeholder="Enter Name..">
                    </div>
                </div>
                <div >
                    <label  for="editphone">Phone No.<span >*</span></label>
                    <div >
                        <input type="text" id="editphone" name="editphone"  placeholder="Enter the Phone No...">
                    </div>
                </div>
                <div >
                    <label  for="editemail">Email <span ></span></label>
                    <div >
                        <input type="text" id="editemail" name="editemail"  placeholder="Enter your valid email..">
                    </div>
                </div>
                <div >
                    <label  for="editdob">DOB <span ></span></label>
                    <div >
                        <input type="date" id="editdob" name="editdob"  placeholder="Enter birthdate..">
                    </div>
                </div>
                <div >
                    <label  for="editpincode">Pincode <span >*</span></label>
                    <div >
                        <input type="text" id="editpincode" name="editpincode"  placeholder="Enter Your Pincode...">
                    </div>
                </div>
                <div >
                    <label  for="editcity">City <span >*</span></label>
                    <div >
                        <select id="editcity" name="editcity" >
                            <option value="">--Please Select City--</option>
                        </select>
                    </div>
                </div>
                <div >
                    <label  for="editstate">State <span >*</span></label>
                    <div >
                        <input type="text" id="editstate" name="editstate"  placeholder="State..." readonly>
                    </div>
                </div>
                <div >
                    <label  for="editaddress">Address <span >*</span></label>
                    <div >
                        <textarea id="editaddress" name="editaddress" rows="7"  placeholder="Enter Your Address.."></textarea>
                    </div>
                </div>
                <div >
                    <div >
                        <button type="submit" >Submit</button>
                        <button type="reset" >Reset</button>
                    </div>
                </div>
            </form>
        </div>
            <div >

            </div>
        </div>
    </div>
</div>
<!-- Edit Modal End-->

function to get data from database in laravel/php

public function edit(Request $request)
    {
        $customer=Customer::find($request->id);
        return json_encode($customer);
    }

CodePudding user response:

Could you move the $("#modal-edit-customer").modal("show"); inside the ajaxStop function after the $("#editcity").val(json.city).change(); even look to use jquery chaining so that the model call can only come after the city data has loaded ? I hope this helps

CodePudding user response:

I was thinking something like:

$(document).ajaxStop(function () {
    $("#editcity").val(json.city).change();
    $("#modal-edit-customer").modal("show");
});
                    

Or

$(document).ajaxStop(function () {
    $("#editcity").val(json.city).change(function() {
        $("#modal-edit-customer").modal("show");
    });
});

Fetching Details From Database - script for edit customer

because that's where your calling the model show but ajaxStop is probably running after that to load the city data hence there weird model before data your seeing. Based on what you posted in your follow up question i would say you should be able to do this

$("#editpincode").val(json.pincode).keyup(function() {
  $("#editstate").val(json.state);
  $("#editaddress").val(json.address);
  $('#editaddress').on("custom", function() {
    $("#modal-edit-customer").modal("show");
  });
  $("#editcity").val(json.city).trigger("custom");
});

Dose this help ?

  • Related