0

I have currently a function where you can search using ajax request to this php file. The problem is that this file is heavy, leading to delay in search results and lag. For example if I search for John doe, in the search box it will say: Searching for John then delay 2 seconds then add Doe. The ajax request is called on key up and the php file is as following:

How can I optimize the function in order to make it faster when returning data?

Please see the demostration in this gif where I write hello there Please see the demostration in this gif where I write hello there

<?php
session_start();
include_once("../inc/main.class.php");
$main = new Main();

if(isset($_POST["token"])) {
    if($_SESSION["sess_id"] == $_POST["token"]) {
        $checkKlarnaApiOrder      = $main->checkKlarnaApiOrder($_POST["term"], $_SESSION["sess_id"]);
        $checkWooCommerceApiOrder = $main->checkWooCommerceApiOrder($_POST["term"], $_SESSION["sess_id"]);
        
        if ($checkKlarnaApiOrder["error"] == 1) {
            echo '
            <div class="alert alert-danger text-center">
                <i class="fa fa-info-circle"></i> '. $getKlarnaApiOrder["message"] .'
            </div>
            ';
        } else if(isset($checkKlarnaApiOrder["order_id"])) {
            $getKlarnaApiOrder        = $main->getKlarnaApiOrder($_POST["term"], $_SESSION["sess_id"]);
            $main->insertSearchTermToHistory("$_POST[term]", "Klarna Order", "$_SESSION[sess_id]", "found");
            echo '
            <div class="alert alert-success text-center mb-0 mt-2">
                <i class="fa fa-check-circle"></i> We found a order with ID '.strip_tags($_POST["term"]).'
            </div>
            <div class="alert bg-light mt-0">
                <div class="row">
                    <div class="col-md-4">
                        <b>Client</b> <br>
                        '.$getKlarnaApiOrder["billing_address"]->given_name. ' ' . $getKlarnaApiOrder["billing_address"]->family_name . ' <br>
                        Address 1: ' . $getKlarnaApiOrder["billing_address"]->street_address . ' <br>
                        Address 2: ' . $getKlarnaApiOrder["billing_address"]->street_address2 . ' <br>
                        ' . $getKlarnaApiOrder["billing_address"]->postal_code . ', ' . $getKlarnaApiOrder["billing_address"]->city . ', ' . $getKlarnaApiOrder["billing_address"]->country . ' <br>
                        ' . $getKlarnaApiOrder["billing_address"]->email . ' <br>
                        ' . $getKlarnaApiOrder["billing_address"]->phone . '
                    </div>
                    <div class="col-md-4">
                        <b>Delivery</b> <br>
                        ' . $getKlarnaApiOrder["shipping_address"]->given_name . ' ' . $getKlarnaApiOrder["billing_address"]->family_name . ' <br>
                        Address 1: ' . $getKlarnaApiOrder["shipping_address"]->street_address . ' <br>
                        Address 2: ' . $getKlarnaApiOrder["shipping_address"]->street_address2 . ' <br>
                        ' . $getKlarnaApiOrder["shipping_address"]->postal_code . ', ' . $getKlarnaApiOrder["billing_address"]->city . ', ' . $getKlarnaApiOrder["billing_address"]->country . ' <br>
                        ' . $getKlarnaApiOrder["shipping_address"]->email . ' <br>
                        ' . $getKlarnaApiOrder["shipping_address"]->phone . '
                    </div>
                    <div class="col-md-4">
                        <b>Method:</b> '. $getKlarnaApiOrder["initial_payment_method"]->type .' / '. $getKlarnaApiOrder["initial_payment_method"]->description . ' <br>
                        <b>Status:</b> ' . $getKlarnaApiOrder["status"] . ' <br>
                        <b>Total:</b> ' . number_format($getKlarnaApiOrder["order_amount"] / 100, 2) . ' <br>
                        <b>Paid:</b> ' . number_format($getKlarnaApiOrder["captured_amount"] / 100, 2) . ' <br>
                        <b>Refunded:</b> ' . number_format($getKlarnaApiOrder["refunded_amount"] / 100, 2) . ' <br>
                        <b>Currency:</b> ' . $getKlarnaApiOrder["purchase_currency"] . ' <br>
                        <b>Handle:</b> <a href="'.$main->baseUrl().'/klarna/cmd/view/order/'.$_POST["term"].'" class="">Show order</a>
                    </div>
                </div>
            </div>
            ';
        } else if($checkWooCommerceApiOrder == 1) {
            $getWooCommerceApiOrder = $main->getWooCommerceApiOrder($_POST["term"], $_SESSION["sess_id"]);
            $main->insertSearchTermToHistory("$_POST[term]", "WooCommerce Order", "$_SESSION[sess_id]", "found");
            if($getWooCommerceApiOrder["payment_method_title"]=="Klarna") {
                $getKlarnaApiOrder = $main->getKlarnaApiOrder($getWooCommerceApiOrder["transaction_id"], $_SESSION["sess_id"]);
                echo '
                <div class="alert alert-success text-center mb-0 mt-2">
                    <i class="fa fa-check-circle"></i> We found a WooCommerce order with id  ' . strip_tags($_POST["term"]) . ' (Klarna Id: '.$getWooCommerceApiOrder["transaction_id"].')
                </div>
                <div class="alert bg-light mt-0">
                    <div class="row">
                        <div class="col-md-4">
                            <b>Client</b> <br>
                            ' . $getKlarnaApiOrder["billing_address"]->given_name . ' ' . $getKlarnaApiOrder["billing_address"]->family_name . ' <br>
                            Address 1: ' . $getKlarnaApiOrder["billing_address"]->street_address . ' <br>
                            Address 2: ' . $getKlarnaApiOrder["billing_address"]->street_address2 . ' <br>
                            ' . $getKlarnaApiOrder["billing_address"]->postal_code . ', ' . $getKlarnaApiOrder["billing_address"]->city . ', ' . $getKlarnaApiOrder["billing_address"]->country . ' <br>
                            ' . $getKlarnaApiOrder["billing_address"]->email . ' <br>
                            ' . $getKlarnaApiOrder["billing_address"]->phone . '
                        </div>
                        <div class="col-md-4">
                            <b>Delivery</b> <br>
                            ' . $getKlarnaApiOrder["shipping_address"]->given_name . ' ' . $getKlarnaApiOrder["billing_address"]->family_name . ' <br>
                            Address 1: ' . $getKlarnaApiOrder["shipping_address"]->street_address . ' <br>
                            Address 2: ' . $getKlarnaApiOrder["shipping_address"]->street_address2 . ' <br>
                            ' . $getKlarnaApiOrder["shipping_address"]->postal_code . ', ' . $getKlarnaApiOrder["billing_address"]->city . ', ' . $getKlarnaApiOrder["billing_address"]->country . ' <br>
                            ' . $getKlarnaApiOrder["shipping_address"]->email . ' <br>
                            ' . $getKlarnaApiOrder["shipping_address"]->phone . '
                        </div>
                        <div class="col-md-4">
                            <b>Method:</b> ' . $getKlarnaApiOrder["initial_payment_method"]->type . ' / ' . $getKlarnaApiOrder["initial_payment_method"]->description . ' <br>
                            <b>Status:</b> ' . $getKlarnaApiOrder["status"] . ' <br>
                            <b>Total:</b> ' . number_format($getKlarnaApiOrder["order_amount"] / 100, 2) . ' <br>
                            <b>Paid:</b> ' . number_format($getKlarnaApiOrder["captured_amount"] / 100, 2) . ' <br>
                            <b>Refunded:</b> ' . number_format($getKlarnaApiOrder["refunded_amount"] / 100, 2) . ' <br>
                            <b>Currency:</b> ' . $getKlarnaApiOrder["purchase_currency"] . ' <br>
                            <b>Handle:</b> <a href="' . $main->baseUrl() . '/klarna/cmd/view/order/' . $getWooCommerceApiOrder["transaction_id"] . '" class="">Show order</a>
                        </div>
                    </div>
                </div>
                ';
            } else {
                echo '
                <div class="alert alert-warning text-center mb-0 mt-2">
                    <i class="fa fa-info-circle"></i> This seem to be a WooCommerce order without a Klarna Id.
                </div>';
                
            }

            
        } else {
            echo '
            <div class="alert alert-light bg-light text-center mt-3">
                <i class="fa fa-info-circle"></i> We could not find any data for <b>'.strip_tags($_POST["term"]).'</b>
            </div>
            ';
        }
    } else {
        echo '
        <div class="alert alert-danger text-center">
            <i class="fa fa-info-circle"></i> Du dont have any access.
        </div>
        ';
    }
} else {
    echo 'Error';
}

The ajax code looks like this:

function searchAjaxTicket(str) {
        // Declare variables
        var input, filter, table, tr, td, i, txtValue, response;
        input = document.getElementById("ajaxTicket");
        filter = input.value;
        if (filter === '') {
            $('.ajaxTicketSocket').hide();
        } else {
            $('.ajaxTicketSocket').show();
        }

        if (!filter.trim()) {
            $(".ajaxTicketSocket").html('');
        } else {
            $(".ajaxTicketSocket").html('<div class="col-md-12 mt-2 searchAjaxTicketLabel">Söker efter <b>' + stripHTML(
                filter) + '</b> <i class="fas fa-spinner fa-spin" style="font-size: 0.7em;"></i></div>').fadeIn();
            // $(".ajaxTicketSocketResponse")
            var form = $(this);
            var url = '<?= $main->baseUrl(); ?>/cgi/search.php';
            var delay = 20000;
            $.ajax({
                type: "POST",
                url: url,
                data: {
                    term: filter,
                    token: "<?= $_SESSION['sess_id']; ?>"
                }, // serializes the form's elements.
                success: function(data) {
                    $(".ajaxTicketSocket").html(data);
                },
                error: function(data) {
                    $(".ajaxTicketSocket").html(data);
                }
            }, delay);

        }
    }

And the html form is as follows:

<input type="text" onkeyup="searchAjaxTicket(this.value)" class="form-control font-weight-light ajaxTicket" id="ajaxTicket" placeholder="Search ticket or order..." autocomplete="FALSE">
1
  • You should add a timeout of for example 600ms upon keypress, and reset the timeout every time a key has been pressed to "buffer" the request, then when the user stops typing for 600ms, the timeout executes and sends the request to search. Commented Oct 22, 2020 at 21:15

1 Answer 1

1

var delay = 20000;

You see - you make multiple calls, that are just delayed one by one. So you are getting multiple AJAX calls, each one after 20000, getting race condition. Check if value has changed after 20000, and if not, then call the API, otherwise just break the function.

EDIT: In pseudocode it would be:

var delay = 20000;
await new Promise(r => setTimeout(r, delay));
if (oldTextInput == currTextInput){
        $.ajax({
            type: "POST",
            url: url,
            data: {
                term: filter,
                token: "<?= $_SESSION['sess_id']; ?>"
            }, // serializes the form's elements.
            success: function(data) {
                $(".ajaxTicketSocket").html(data);
            },
            error: function(data) {
                $(".ajaxTicketSocket").html(data);
            }
        }, 100); 
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried with no delay as well, Im still getting the same delay and result as the gif above, when typing a long word :/
Check my edit. Just get the values from your input using document.GetElementById, save the old one before delay, and compare it to the one after.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.