R
R
Roman2015-07-25 23:49:43
CSRF
Roman, 2015-07-25 23:49:43

How to send ajax post with csrf?

Here is the code, please give me the cities:

if ($('select').is('#city')){
    $.post('/city/index', {_csrf: 'USER_CSRF_TOKEN'})
    .done(function(resp){
      $('#city').empty();

      _each(resp.cities, city)
      {
        $('#city').append($('<option value="' + city.id + '"> city.name</option>'));
      }	
    })
    .fail(function() {
      alert("error");
    });
  }

here is this line 1 to 1 from the documentation, except for the path:
$.post('/city/index', {_csrf: 'USER_CSRF_TOKEN'})
it doesn’t work, I get 403
, maybe instead of the USER_CSRF_TOKEN line I should use some specific value, but is it a descriptive term?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2015-07-26
@losaped

coped. in my case the solution is this:

var csrf;
  $.get('/csrfToken').done(function (resp) {
    csrf = resp._csrf;
  });

  setTimeout(function(){
    if ($('select').is('#city')){
      console.log(csrf);
      $.post('/city/index', {_csrf: csrf })
      .done(function(resp){
        $('#city').empty();
        console.log(resp.cities);

        $.each(resp.cities, function(i, city){
          $('#city').append('<option value="' + city.id + '"> ' +city.name + '</option>');
        });	
      })
      .fail(function() {
        alert("error");
      });
    }
    }, 0	
  );

It's just that it all looks crooked. If anyone is not too lazy, then write how to make it more beautiful

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question