user756659
user756659

Reputation: 3512

load results from ajax into div upon success

Just started using ajax a few days ago and came across a new situation I need. The part I am concerned about is the loading. In the past I have loaded the content of an actual file upon ajax success.... now I want to load results from the page I am posting to.

Again, in the past I have just returned an array ['success']='success' and maybe some other variables for use on the return call and to know it was a success. Is it best practice to do the same thing with a large chunk of html stored into a single variable?

Say 'data'] is equal to the html I want to load into the div. Is this the best practice of doing so? I still need to check for success and fail of the processing and only load data from it upon a success.

$('#show-user').on('click', function () {
    var $form = $(this).closest('form');
    $.ajax({
        type: 'POST',
        url: '/spc_admin/process/p_delete_user_show.php',
        data: $form.serialize(),
        dataType : 'json'
    }).done(function (response) {
        if (response.success == 'success') {

            $('#delete_user_info').fadeOut('slow', function(){
                $('#delete_user_info').html('+response.data+', function() {
                    $('#delete_user_info').fadeIn('slow');
                })
            });

        } 
        else
        {
            // error stuff
        }
    });
});

an example return from php:

$ajax_result['success'] = 'success'; // add success info
$ajax_result['data'] = 'this would be a large chunk of html'; // html to show

echo json_encode($ajax_result);

Upvotes: 0

Views: 1677

Answers (1)

m59
m59

Reputation: 43745

There's nothing wrong with sending/receiving a lot of data with ajax, within reason. If you're talking about getting markup for one page, that should be fine. The best way to tell is to look at the "Network" tab in your dev tools and see how long the request takes. If the time isn't to your satisfaction, one option is to have javascript create the markup from a data set. Then you only need to ask the server for that data (faster request) and have javascript create the markup, which can be very fast. This shouldn't be necessary, though. An example of having too much data in a transfer would be a product page where you're fetching information for hundreds of products at once. Pagination or loading on scroll are good ways to go in that case.

As for being sure that the request succeeded, it would be helpful for you to study about request headers. When making a request to the server, if the server is not able to give the information requested, the status code of that request should indicate what happened. A status code of 200 should mean that the server has given you the html you asked for, in this case. If something went wrong, the status code should be set to something else, probably in the 400's or 500's. Check this out for more information on status codes.

When I was new to ajax, I would write requests that basically always "succeeded" which would be status code 200:

success: function(response) {
  if (response.status === 'success') {
    //response is good, use response.data
  }
  else {
    //handle failure
  }
}

Do you see the issue here? I requested something and the success function is running, yet I'm checking to see if I got what I wanted. If the request was successful, then I should have what I want! So, the status code from the server (if set correctly) is great, because it tells us whether or not something was successful and if it was, then we definitely have the data we want. Consider this:

$.ajax({
  url: 'This-file-does-not-exist',
  //status code is 404, so "error" is called
  error: function() {
    console.log('Failed!');
  }
});

$.ajax({
  url: 'this-file-exists.html',
  //response code is 200 - success
  success: function(data) {
    console.log('Success');
  }
});

So, in summary - setting/checking the request status code is the standard approach to determining if you have the data you want (success/fail) and it's probably ok to load a page worth of html on an ajax call (but determine that by monitoring the request time).

By the way, you can cache references to elements so that you aren't searching the dom each time you need to use them. This is better for performance. Also, .html() is not an asynchronous operation, so it doesn't need a callback (and doesn't accept one).

$myElem = $('#delete_user_info');
$myElem.fadeOut('slow', function() {
  $myElem.html(response);
  $myElem.fadeIn('slow');
}

Upvotes: 1

Related Questions