• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Best practice for AJAX quieries

#1
Lightbulb 
Hello!

I have question, your best practice to service ajax request in CI4?
Other namespace in routes? Other Controller? Maybe other solution?
I have application with many modules and many connection by ajax, for dynamic content, for detail information about entity like user/news etc.
Reply

#2
As long as you check in your controllers for an Ajax request you should be ok.

PHP Code:
// Check for AJAX request.
if ($request->isAJAX())
{
 
       . . .

What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#3
Oh dude!JavaScript Cookie v2.2.0
js.cookie will save you a ton of headache with the csrf_protection! I discovered it 2-3 weeks ago, before I tried to avoid ajax or wrote exceptions in the csrf_exclude_uris
$.ajax({
url: base_url + 'community/edit_post',
type: 'POST',
data: {
id: post_id,
csrf_token: Cookies.get('csrf_cookie')
},
dataType: 'json'
}).fail(function (result) {
alert(result.responseText)
});
Wait, what?
Reply

#4
(09-03-2018, 09:11 AM)InsiteFX Wrote: As long as you check in your controllers for an Ajax request you should be ok.

PHP Code:
// Check for AJAX request.
if ($request->isAJAX())
{
 
       . . .


Yes it's good for minimal AJAX queries, but I have controllers with example 5-10 Ajax actions, and somethink like this:
PHP Code:
if($request->isAJAX()) {
    switch(
$task) {
        case 
'action1':
                
/**
                 * When action have many lines it's very hard to work fine with this
                 */
            
break;
        case 
'action1':
            break;
        case 
'action2':
            break;
        case 
'action3':
            break;
        case 
'action4':
            break;
        case 
'action5':
            break;
        ....
    }


So, I start thinking about declare Other Controller (namspace?) for AJAX. Ex.: method names as actions and resolve this to maybe better way.
Reply

#5
i use a separated controller for each ajax action, so ci only loads the required parts ( if your actions are gonna be more complex ). Mostly my ajax controller 1. collect data, 2. call a view for output formatting and 3. return it to the caller ( be sure to handle all possibilities, use the \CodeIgniter\API\ResponseTrait for returning with correct codes ).

to handle CSP correctly you need decide which request use user specific data to know which can be excluded from CSP check and which need to write session ( user specific ) data . so i exclude every trivial request ( check for news, updates ) and added a csp expiration check to the other - some request with write requirements also have the effect to extend the session validity.
to prevent this, you need call session_write_close() before sending the result back
Reply

#6
(09-03-2018, 02:29 PM)Leo Wrote: Oh dude!JavaScript Cookie v2.2.0
js.cookie will save you a ton of headache with the csrf_protection! I discovered it 2-3 weeks ago, before I tried to avoid ajax or wrote exceptions in the csrf_exclude_uris
$.ajax({
       url: base_url + 'community/edit_post',
       type: 'POST',
       data: {
           id: post_id,
           csrf_token: Cookies.get('csrf_cookie')
       },
       dataType: 'json'
   }).fail(function (result) {
       alert(result.responseText)
   });

Indeed that plugin is a lifesaver. But did you also know you can use it in combination with ajaxSetup?

Code:
$.ajaxSetup({
  data: {
    csrf_token_name: Cookies.get(csrf_cookie_name)
  }
})


This saves you having to add it to each of your AJAX functions as it is then added by default. Technically, jQuery docs say they don't recommend this because for some instances, the receiving endpoint may not want the csrf token. I feel like it's easier to override (or filter out) on those occasions rather than avoiding it completely as it's extremely useful.
Reply

#7
You get the JavaScript Cookie from here:

JavaScript Cookie
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#8
About CSRF cookie, propably it's secure with flag HTTP Only, and JS cannot display me this cookie?
Reply

#9
thats correct - you cant access these cookies from JS.
But php can do that, so just write something like
Code:
const CSRF = [ "<?= csrf_token() ?>", "<?= csrf_hash() ?>" ];
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.