I am developing a Laravel 5-BackboneJs Application. I'm using RESTful Resource controllers to make my own api.
I've got a Backbone model then I am calling save model method. It makes an ajax request like this:
gerencia.app/es/customrole/1
That's why I am trying tu update the model with id 1.
Backbone creates a request with PUT method:
But it gives me 500 internal server error! I see the preview then:
This is a TokenMismatchException from Laravel, then I've found I've got to send a token so I did this in my blade view:
<meta name="token" content="{{ Session::token() }}">
Then I've create a function to set the token and add this function to ajax beforeSend method:
function sendAuth( request ){
console.log( request );
return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content'));
}
model.save({
beforeSend: sendAuth,
success: function(){
console.log( 'success!' );
},
error: function(){
console.log( 'error!' );
}
});
But it doesn't work in spite of I see the token in request headers :(
Any help?
I was able to get this working by following the instructions on the Laravel site. I added this to my global layout file:
<meta name="csrf-token" content="{{ csrf_token() }}" />
Then, I created a JS file called csrf-token.js, and placed this code in it:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
After doing that, the POST requests from Backbone worked correctly and I can see the extra header in the request. The key for me was to include the csrf-token.js file AFTER Backbone:
<script src="{{ asset('js/lib/backbone-min.js') }}"></script>
<script src="{{ asset('js/csrf-token.js') }}"></script>
I guess Backbone overwrites the ajax setup options when it loads, so you need to include your changes after that.
My solution is to add a new key/value called token in my model method:
model.save({
"_token" : $("meta[name='token']").attr('content'),
success: function(){
console.log( 'success!' );
},
error: function(){
console.log( 'error!' );
}
});
You can post another solution to this issue.
Related
I am working with laravel. I want to save a post as accepted on click using ajax.
I am sending post using a href tag.
I don't want to use form for this.
here how I am sending post id to ajax
Accept
Here is my js function
function acceptProject($id) {
var projectId;
$.ajax({
alert(projectId);
});
}
but it is showing unexpected token in the console. This is very first week that I am writing ajax code so any mistake please consider.
You need to add X-CSRF-TOKEN token to your ajax request. Add the following code to your main layout, and continue making your ajax calls normally.
In header
<meta name="csrf-token" content="{{ csrf_token() }}" />
In script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
I am using responsive File Manager in my project. i need to add CSRF token in its config file that is inside public folder. using csrf_token() in that config file doesn't work:
$token = csrf_token(); //this is inside filemanager confing.php
Fatal error: Call to undefined function csrf_token() in
E:\xampp\htdoc\site\public\plugin\filemanager\config\config.php on line 7
so how can i access this function in public folder?or totally access app instance out of Laravel typical pathes?
Maybe try to turn off csrf protection for that route, or add this code to header of page where that editor is enabled:
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
}
});
});
</script>
I am trying to do an ajax call in laravel. The ajax call logs my data how I want it, but keeps giving me the 500 error. I've read that you need to set the _token in the data field. But that doesn't work for me. So, I can log all the data, but ones I want to push it to the DB I keep getting this error.
Here's my code.
Script.js
$('.likeBtn').click(function(e){
e.preventDefault();
var userid=$(this).siblings('input[name=userID]');
console.log(userid[0].value);
var useridarticle=$(this).siblings('input[name=userIdFk]');
console.log(useridarticle[0].value);
var articleid=$(this).siblings('input[name=articleId]');
console.log(articleid[0].value);
var token=$(this).siblings('input[name=_token]');
console.log(token[0].value);
$.ajax({
url:"articles" ,
type: "post",
data: {'user_id':userid[0].value,
'article_id':articleid[0].value,
'user_id_fk':useridarticle[0].value,
'_token': token[0].value},
success: function(data){
console.log(data);
}
});
});
Controller.
if(Request::ajax()) {
$data = Input::all();
print_r($data);
}
My tokens are set in the header of my master.blade
<meta name="_token" content="{!! csrf_token() !!}"/>
And at the end of my master.blade
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
What am I not seeing? FYI, You might ask why I need does variables. I need them because I generate the same form in a foreach. This works fine for me, i get the data that I want so.
I am trying to get Relay and GraphQL set up with my Laravel server. I have successfully set Laravel up to serve GraphQL.
In the past, to make ajax calls with jQuery I added the following to my master.blade.php:
<meta name="csrf-token" content="{{ csrf_token() }}">
and the following to my main.js file:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
My GraphQL endpoint is currently returning token mismatch exception. It seems to me that Relay needs to pass the csrf-token to the server in a similar manner as jQuery.ajax. Where does it go?
Configure your network layer to append headers to each request:
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('/graphql', {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
})
);
The second argument to Relay.DefaultNetworkLayer gets passed through to the init argument of fetch(input, init). See the Relay Network Layer Guide for more information.
I am trying to delete instagram like . I have valid access token and have the media id of instagram image. I want to use whateverorigin.org so that i dont get cross domain error. when i run the code beleow i dont get any error and even when i press f12 i dont see any error in console!could any one tell me how to fix this getjson?
note:I am looking for non php solution !
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function delete() {
var url="https://api.instagram.com/v1/media/xxxxxxxxxxxxxxxxxx_xxxxxxxxxx/likes?access_token=xxxxxxxxxxxx"
$.ajaxSetup({
method: "post"
scriptCharset: "utf-8", //maybe "ISO-8859-1"
contentType: "application/json; charset=utf-8"
});
$.getJSON('http://whateverorigin.org/get?url=' +
encodeURIComponent(url) + '&callback=?',
function(data) {
});
}
</script>
<button onclick="delete()">delete</button>
According to the Instagram API Documentation you need to use the "delete" method. In your code you're using a "post" method, which is creating a like.
So, just change method: "post" to method: "delete"