0

Using jQuery to call an endpoint and populate the data on the frontend is a common task. After searching and using multiple solutions the below is my current blueprint for any ajax calls.

How can I improve the following to be faster and more efficient? I realize doing it in pure javascript will be faster but at this point I assume jQuery will be present.

Frontend - Javascript:

$(document).ready(function()
{
    function callEndpoint( call_url, payload ){
        return $.ajax({
            url: call_url,
            type: 'GET',
            data: payload
        });
    }
    $( '.get-endpoint' ).click( function() {
        sSelected = $( this ).text();
        console.log( sSelected );
        oRequest = callEndpoint( '/play/endpoint2.php', { 'type': sSelected } );
        oRequest.done(function( sJson ) {
            aData = JSON.parse( sJson );
            $( '.from-endpoint' ).text( aData.text );
        });
    });
});

Frontend - Html:

<body>
    <button class="get-endpoint">Games</button>
    <button class="get-endpoint">Books</button>
    <button class="get-endpoint">Comics</button>
    <div class="from-endpoint">Coming soon...</div>
</body>

Backend - PHP:

$aReturn[ 'text' ] = '';
if( !empty( $_GET ) )
{
    if( $_GET[ 'type' ] == 'Games' )
    {
        $aReturn[ 'text' ] = 'Text for games';
    }
    else if( $_GET[ 'type' ] == 'Books' )
    {
        $aReturn[ 'text' ] = 'Text for books';
    }
    else if( $_GET[ 'type' ] == 'Comics' )
    {
        $aReturn[ 'text' ] = 'Text for comics';
    }
}
$sJson = json_encode( $aReturn, 1 );
header( 'Content-Type: application/json' );
echo $sJson;
7
  • cache parameter in jQuery ajax is true by default - but you might wanna be sure that it is true if the content isn't changing often. Commented Mar 11, 2015 at 20:27
  • 1
    Have you measured it and found it to be slow? The bottleneck in your code would surely be the request itself, which you cannot do much about. Commented Mar 13, 2015 at 14:09
  • 1
    Please check the PHP documentation for the header function. You're not using it the right way. Commented Mar 13, 2015 at 15:21
  • Vladimir, could you please elaborate on why the need is there for a more efficient way? The above solution is kind of standard in jQuery. The below solution about using getJSON is kind of valid, since you don't have to do JSON.parse anymore. That is added by the overload function. Making your code cleaner. I am not sure at the moment what kind of answer you are looking for. A refactor of your code? Commented Mar 17, 2015 at 7:53
  • I'm looking for ideas/suggestions that are often overlooked when it comes to getting a better parse time/attaining the most efficient performance possible. The getJSON I did not like as it still uses ajax to route through adding another function call. Commented Mar 17, 2015 at 7:56

6 Answers 6

0
+50

I don't think that this code can be more efficient in jQuery. But you have some options left to give a more efficient feeling :

  • You can use pagination to get a portion of your data each time. The
    less data to load, the quicker it get. And your application will be
    more responsive to the user's actions. This solution is a trick for the user, because it will take in reality more time than before to load all the data.
  • You can keep previous loaded data so when you click back on a button, it won't load again the data. But, this can only be used if the data won't change much between each click. The first time you will click on a button, it will take the same time as before, but the next time, it will be immediat.

Be aware that the more HTML code you load, the more it will take time to initiate JavaScript behavior on it.

Sign up to request clarification or add additional context in comments.

Comments

0

Looks like your categories won't change often. You can save some bandwidth by using JavaScript localstorage or cookies to cache data. If you plan on connecting to a mysql database at somepoint you can use StoredProcedures which are variablized precompiled statements.

1 Comment

This is just a sandbox file not meant to go anywhere except limit the code for this example only. Obviously in production examples the listener will be attached to different events and the backend route will be different each time.
0

Since you are anyways going to use JSON and jQuery, I would suggest that you should check out the getJSON method of jQuery. I feel that it would reduce some lines of code, though I am not sure if it would help it become more efficient. Anyways getJSON is just a shorthand of AJAX and I thought I should suggest this.

2 Comments

Disagreed. .getjson() calls .ajax(), so it will add to the overhead.
Yeah, you are right. Even I was not aware in deep about this. But looking into it cleared it. Thanks
0

This could be a good approach for AJAX data transport browser->server->browser. Hope it suites your needs.

jQuery

$( function () {

    function fetch( data ) {

        var encoding = data.encoding,
            url = data.url,
            params = data.params,
            type = ( data.type ) ? : 'GET',
            cache = ( data.cache ) ? : 'false',
            async = ( data.async ) ? : 'true';

        return $.ajax({
            url: url,
            async: async,
            cache: cache,
            data: params,
            dataType: encoding,
            type: type
        });
    }

    var options = {
            url: 'controller.php',
            params: {
                param_one: value_one,
                param_two: value_two,
                param_n: value_n
            },
            encoding: 'json'
        };

    // Get the JSON feed from the server
    $.when( fetch( options ) ).then( function ( response ) {

        // Is there anything in the pool?
        if ( response ) {

            // Store the response and use it in your code
            var data = response.data;

            console.log( data.responseOne );
            console.log( data.responseTwo );
        }
    });
});

PHP Controller

// Set header to application/json
header( 'Content-type: application/json' );

// Create the DB connection object
$dbc = new mysqli( DB_HOST, DB_USER, DB_PASS, DB_NAME );

// Initialize parameters array
$params = array();

// Store the query variables in an array
$query_type = ( $_GET ) ? : $_POST;

// Run foreach and store the values in an array
foreach ( $query_type as $key => $value ) {
    $params[ $key ] = mysqli_real_escape_string( $dbc, $value );
}

// Now you can access passed parameters like $params['param_name']

// This would be the data obtained from DB or some server array processing, whatever
$response = array(
    'data' => array(
        'response_one' => 'some_value',
        'response_two' => 'another_value'
     )
);

// Encode the result
echo json_encode( $response );

1 Comment

Yes, it basically returns the conditional. For instance, if your conditional is isset([$_GET['value']]), $query_type value will be true or false, depending on $_GET['value'] being passed or not.
0

If you don't want use pure javascript, you can improve your jQuery code with better selectors

For example, you can add an id in <div class="from-endpoint">

You can add tag in selector like this:

$('button.get-endpoint')

Comments

0
  1. You can drop your getEndpoint method and just use the $.get method.

$(document).ready(function()
{
    $( '.get-endpoint' ).click( function() {
        sSelected = $( this ).text();
        console.log( sSelected );
        oRequest = $.get('/play/endpoint2.php', { 'type': sSelected });
        oRequest.done(function( sJson ) {
            aData = JSON.parse( sJson );
            $( '.from-endpoint' ).text( aData.text );
        });
    });
});

  1. You can make your code lint compliant.

$(document).ready(function()
{
    $( '.get-endpoint' ).click( function() {
        var sSelected = $( this ).text();
        console.log( sSelected );
        oRequest = $.get('/play/endpoint2.php', { type: sSelected });
        oRequest.done(function( sJson ) {
            var aData = JSON.parse( sJson );
            $( '.from-endpoint' ).text( aData.text );
        });
    });
});

  1. Use success instead of done & move the callback to it's own function

$(document).ready(function()
{
    $( '.get-endpoint' ).click( function() {
        var sSelected = $( this ).text();
        console.log( sSelected );
        $.get(
            '/play/endpoint2.php',
            { type: sSelected },
            insertData
        );
    });
});

function insertData( sJson ) {
    var aData = JSON.parse( sJson );
    $( '.from-endpoint' ).text( aData.text );
}

  1. Use $.getJSON instead of $.get or $.ajax

$(document).ready(function()
{
    $( '.get-endpoint' ).click( function() {
        var sSelected = $( this ).text();
        console.log( sSelected );
        $.getJSON(
            '/play/endpoint2.php',
            { type: sSelected },
            insertData
        );
    });
});

function insertData( data ) {
    $( '.from-endpoint' ).text( data.text );
}

1 Comment

Sure, but your method uses it as well, so you're just duplicating code already present in the jQuery library. On top of that. Nested functions won't add that much overhead. It's better to use cleaner, more battle tested methods present within a library than to reinvent the wheel and write your own methods, which are more error-prone.

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.