Welcome Guest, Not a member yet? Register   Sign In
Best practice for AJAX quieries
#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


Messages In This Thread
Best practice for AJAX quieries - by Przem4S - 09-03-2018, 06:01 AM
RE: Best practice for AJAX quieries - by InsiteFX - 09-03-2018, 09:11 AM
RE: Best practice for AJAX quieries - by Leo - 09-03-2018, 02:29 PM
RE: Best practice for AJAX quieries - by twistedpixel - 09-04-2018, 03:01 AM
RE: Best practice for AJAX quieries - by Przem4S - 09-04-2018, 12:57 AM
RE: Best practice for AJAX quieries - by puschie - 09-04-2018, 02:19 AM
RE: Best practice for AJAX quieries - by InsiteFX - 09-04-2018, 04:01 AM
RE: Best practice for AJAX quieries - by Przem4S - 09-04-2018, 04:14 AM
RE: Best practice for AJAX quieries - by puschie - 09-05-2018, 02:39 AM



Theme © iAndrew 2016 - Forum software by © MyBB