Welcome Guest, Not a member yet? Register   Sign In
Ajax best practices
#1

[eluser]Lockzi[/eluser]
Hello,

I'm a user of CI + jQuery which works just fine!

My question is regarding best practices for ajax.
Whenever I press a link which should do an Ajax effect or request, how should I set it up?

Option 1:
I have a standard .JS file that's imported in the header, which contains loads of functions like this one:

PSUEDO CODE:
Code:
vote = function()
{
   //Load external JS file that contains the effects, ajax requests for this
   load("js/vote.js");
   execute(imported_code);
}

This would make the site's index load fairly quick since all it does in regard to ajax functions is telling what file to import for the effects and calls, but it would take in another chain of actions as soon as something is to be used.

Option 2:
Just place all the crap in the same file, which for a big site could result in it being fairly huge.

This would make the index loading slow, but all the actions quick and tidy.

Option 3:
Something else?





I would also take this opportunity to ask you if you re-use ajax functions? Like requesting and displaying through passed variables?
#2

[eluser]Pascal Kriete[/eluser]
Put everything in one big file. It will only slow down the first load as all modern browsers cache the javascript. So it's quicker in the long run. Reusing ajax functions is difficult, but when the actions are similar it can be done. Just depends on the application.

Last but not least, everything should work with javascript turned off.

EDIT: If your file really is huge you might want to consider minifying and compressing it to make that initial load just a little snappier.
#3

[eluser]Lockzi[/eluser]
[quote author="inparo" date="1203740563"]
Last but not least, everything should work with javascript turned off.
[/quote]
Exactly, so how do you solve that if you have like a pagination system, which would require you to pass 'how_many_per_page' and 'page'? I currently on document read(onload) use jQuery to add events on link clickings to call a function which retrives the rel="" and ret="" values of that link and if I'm really in need, I would put it inside a <span class="thirdValue"> and retrive the class of that span as the third value. Don't know if this would pass W3C standards really... But it's the best solution I've found yet, to have the page working for users without javascript since I can still have a link in the <a href="whatever.ext"> which would be used if the event is not added.

This got quite messy, I could try to clarify further if needed.

[quote author="inparo" date="1203740563"]
EDIT: If your file really is huge you might want to consider minifying and compressing it to make that initial load just a little snappier.[/quote]
Yes, I've been thinking of that too... I wonder how Google and other AJAX sites do it...
#4

[eluser]ScottBruin[/eluser]
[quote author="Lockzi" date="1203741621"]
Exactly, so how do you solve that if you have like a pagination system, which would require you to pass 'how_many_per_page' and 'page'? [/quote]

If the same controller returns your a) AJAX data and b) non-AJAX file, then you could set your AJAX function in jQuery to send a POST variable that will notify the controller if you need (a) or (b). So, if you have a link like this:
Code:
<a href="/method/2/20" class="ajax">Link!</a>
where 2 is your page and 20 is the "how_many_per_page". Your jquery function would be something like
Code:
var href = $('.ajax').attr('href');

Then, use href to define the URL in your $.post function or whatever you use from jQuery. In that post function, make sure for data sent you use
Code:
{ ajax: 'true' }
and then you can check that POST variable from your controller. If it is true, then return the right kind of data for AJAX. If it isn't set, then assume the user has Javascript off and so you need to serve up a full page. This allows you to use the same controller method for the same things and just change how the data is presented based on whether it's for an ajax request or not.

Further, you can still use the variables that you would have normally passed in the URL (i.e. page and # per page) without having to set a bunch of attributes for the anchor element.
#5

[eluser]Lockzi[/eluser]
[quote author="ScottBruin" date="1203748619"][quote author="Lockzi" date="1203741621"]
Exactly, so how do you solve that if you have like a pagination system, which would require you to pass 'how_many_per_page' and 'page'? [/quote]

Further, you can still use the variables that you would have normally passed in the URL (i.e. page and # per page) without having to set a bunch of attributes for the anchor element.[/quote]

I feel so stupid... Sad

How would you handle a pagination system if your pagination bar (First < 1 2 3 4 e.t.c. > Last), is in a different div than your content? Would you make 2 Ajax requests or would you render it as an whole, bigger content content.

Lastly I would like to ask (it's an jQuery question really), how do you make your functions?

as a jQuery function:
Code:
(function($){
$.fn.whatEver= function() {

    return this.each(function() {

    });
};
})(jQuery);

or as a reglular function:

Code:
whatEver = function()
{

    return whichEver;
}
#6

[eluser]ScottBruin[/eluser]
Lockzi, it seems like there would be three big options if you want to change the content plus the navigation. 1) include them all as an html block, 2) split into multiple html blocks and return both of those, or 3) return JSON or XML data and parse that with jQuery.

I would lean toward option three if I were you, but if you're using the CI pagination I'm not quite sure how you would do this. I've been dealing with similar issues to this. If you pass a multidimensional array to json_encode() (http://us.php.net/json), you can pass this string to jQuery and it deals with it well. You can iterate through each item with jQuery's $.each() and do things. Just a thought, you'll have to see what fits you best.
#7

[eluser]Lockzi[/eluser]
[quote author="ScottBruin" date="1203757073"]split into multiple html blocks and return both of those[/quote]

I've been reading up on XML and JSON (http://www.quirksmode.org/blog/archives/...espon.html), and it seems much more simple to just send HTML blocks. How would I be able to send two different HTML blocks in one request? Actually, the sending is quite simple, but how would I be able to handle that with ajax?

Really appreciate all your help! I've been lurking on these questions for about a week now until I finally got tiered enough and just figured I should ask the masses Smile
#8

[eluser]Pascal Kriete[/eluser]
Normally, here's what I would do.

I would have a seperate view for the pagination results and links - i'll call it pag. My main controller accepts an ajax flag (parameter or something similar). If the flag isn't set it loads the main view:
Code:
//stuff for the main view
<div id="pagination">
$this->load->view("pag")
</div>
//more stuff
If the flag is set it only loads the pag view and I update the pagination div with the returned view.

Now all you have to do is hijack the pagination links and run an ajax call with their href. Easy as pie Big Grin.

The problem comes when trying to split it up. The only way I can think of is either make 2 requests or json encode the whole thing.
So in php you would have
Code:
$pagviews['content'] = $this->load->view('content', true);
$pagviews['links'] = $this->load->view('links', true);
echo json_encode($pagviews);

And then in your javascript you would have:
Code:
ajaxrequestusingwhateverframework {
    onComplete: function(req) {
        var resp = eval('(' + req.responseText + ')');
        $('linksdiv')[removed] = resp.links;
        $('contentdiv')[removed] = resp.content;
    }
}

The first path is admittedly easier. Not to mention that json_encode is php 5.
#9

[eluser]Lockzi[/eluser]
[quote author="inparo" date="1203797665"]
Code:
$pagviews['content'] = $this->load->view('content', true);
$pagviews['links'] = $this->load->view('links', true);
echo json_encode($pagviews);
[/quote]

Interesting take, I will definitely use that!

Thanks all, I'll be back if I get any further questions since I believe more people will benefit from this thread! We've covered some of the basic parts of Ajax best practice for bigger projects. Nice too see that there actually are a few people who know this and are willing to help, maybe I should start to blog about my journey Big Grin
#10

[eluser]Pascal Kriete[/eluser]
I couldn't let this go all day, so I wrote my own function that does it.

The explanation and code ended up to be a little more than expected so I've posted it here.




Theme © iAndrew 2016 - Forum software by © MyBB