All request methods in laravel returned (error 419 unknown status) except get request.
How can I set token in header?
I tried to do this the following ways.
1)
window.onload = function() {
const ui = SwaggerUIBundle({
...
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
2)
window.onload = function() {
const ui = SwaggerUIBundle({
authorizations: {
csrf: function () {
var cookiearray = document.cookie.split(';');
for (var i = 0; i < cookiearray.length; ++i) {
if (cookiearray[i].trim().match('^XSRF-TOKEN=')) {
this.headers['RequestVerificationToken'] =
cookiearray[i].replace(`XSRF-TOKEN=`, '').trim();
}
}
return true;
},
}
}
}
3)
$.ajaxSetup({
data: {
"_token": "{{ csrf_token() }}"
},
});
4)
$.ajaxSetup({
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
but nothing has changed
Related
I installed a fresh Laravel App with authentication. I am using laragon. The login, registration, reset password pages are working fine. I created a profile controller for the user to edit profile. However, when submitting the form through Ajax, it gives me a Forbidden - You don't have permission to access / / /profile/edit_profile on this server..
class ProfileController extends Controller
{
//
function index()
{
return view('profile.index');
}
function edit_profile(Request $request)
{
$txt_midname = $request->input('txt_midname');
$txt_firstname = $request->input('txt_firstname');
$txt_lastname = $request->input('txt_lastname');
$extname = $request->input('extname');
$user = Auth::user();
$user->firstname = $txt_firstname;
$user->midname = $txt_midname;
$user->lastname = $txt_lastname;
if ($user->save()) {
return 'ok';
}
}
}
Here is also the route:
Route::post('/profile/edit_profile', 'ProfileController#edit_profile')->name('edit_profile');
and the view:
$('#btn_update').on('click', function() {
var btn_text = $('#btn_update').text();
var txt_firstname = $.trim($('#txt_firstname').val());
var txt_midname = $.trim($('#txt_midname').val());
var txt_lastname = $.trim($('#txt_lastname').val());
var extname = $.trim($('#extname').val());
$.post(baseUrl + '/profile/edit_profile', {
'_token': token,
'txt_midname': txt_midname,
'txt_firstname': txt_firstname,
'txt_lastname': txt_lastname,
'extname': extname
}, function(data) {
if (data == 'ok') {
window.location.reload();
}
})
})
You need to inject the csrf token to your request.
$.post({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
url: '/admin/gallery/create/ajax',
data: {},
method: 'POST',
success: function(response) {
},
error: function(error) {
}
})
or if you want every ajax request inject the csrf token you can do this as well.
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
It was my mistake. The problem is with my baseUrl in javascript. It should be var baseUrl = "{{url('')}}";instead of var baseUrl = '{{url('')}}';
I am using chrome popup extension but no data is sent to the php file named api.php.I have searched on stackoverflow and found ajax related content but nothing is working.here is my popover.js file which uses ajax.I used $_POST['data'] to grab the data in api.php file
var api_url = "https://localhost/psol/api.php";
window.onload = function () {
$("#checkout_btn").click(function () {
chrome.runtime.sendMessage({
'btnClicked': true
}, function () {});
});
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
console.log(request);
if (request.message === "show-loading") {
$(".psol-button").addClass('hide');
$(".psol-loader").removeClass("hide");
}
if (request.message === "hide-loading") {
$(".psol-button").removeClass('hide');
$(".psol-loader").addClass("hide");
}
if (request.message === "post-cart") {
console.log(request.data);
alert(JSON.stringify(request.data));
chrome.runtime.sendMessage({
'postCartDone': true,
'redirectTo': api_url
}, function () {});
$.ajax({
url: api_url,
type: "POST",
data: request.data,
// data:{name:'uzair'},
success: function (result) {
// alert("all done");
console.log(1, result);
}
}).done(function (result) {
console.log(2, result);
if (result.cartCount === 0) {
alert('There are no items in cart to checkout');
}else {
alert("this is also redirect");
}
});
}
});
};
There is a update view api made to update the content of employee. I can update from the django rest framework view.
I'm using jquery ajax to update but its not working.
$(document).ready(function(){
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$(".update-employee").submit(function(event){
event.preventDefault()
var this_ = $(this)
var form = this_.serializeArray()
$.each(form, function(key, value){
})
var formData = this_.serialize()
console.log(formData);
var temp =
{
"name": form[4].value,
"email": form[1].value,
"address": form[2].value,
"phone_number": form[3].value,
"username": {{ user_id }},
"school": {{ school_id}},
"language_id": {{ language_id }}
}
$.ajax({
url: "/api/student/{{ id }}",
data: JSON.stringify(temp),
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
method: "PUT",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function(data){
console.log(data)
},
error: function(data){
console.log("error")
console.log(data.statusText)
console.log(data.status)
}
})
});
});
The temp variable uses the values to update which is sent through context data from views.
what is the problem here, its showing error in console.
Looking at the Flux Documentation I can't figure out how the code to a ajax update, and a ajax fetch would fit into the dispatcher, store, component architecture.
Can anyone provide a simple, dummy example, of how an entity of data would be fetched from the server AFTER page load, and how this entity would be pushed to the server at a later date. How would the "complete" or "error" status of request be translated and treated by the views/components? How would a store wait for the ajax request to wait? :-?
Is this what you are looking for?
http://facebook.github.io/react/tips/initial-ajax.html
you can also implement a fetch in the store in order to manage the information.
Here is an example (it is a concept, not actually working code):
'use strict';
var React = require('react');
var Constants = require('constants');
var merge = require('react/lib/merge'); //This must be replaced for assign
var EventEmitter = require('events').EventEmitter;
var Dispatcher = require('dispatcher');
var CHANGE_EVENT = "change";
var data = {};
var message = "";
function _fetch () {
message = "Fetching data";
$.ajax({
type: 'GET',
url: 'Url',
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = error;
MyStore.emitChange();
}
});
};
function _post (myData) {
//Make post
$.ajax({
type: 'POST',
url: 'Url',
// post payload:
data: JSON.stringify(myData),
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = "update failed";
MyStore.emitChange();
}
});
};
var MyStore = merge(EventEmitter.prototype, {
emitChange: function () {
this.emit(CHANGE_EVENT);
},
addChangeListener: function (callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function (callback) {
this.removeListener(CHANGE_EVENT, callback);
},
getData: function (){
if(!data){
_fetch();
}
return data;
},
getMessage: function (){
return message;
},
dispatcherIndex: Dispatcher.register( function(payload) {
var action = payload.action; // this is our action from handleViewAction
switch(action.actionType){
case Constants.UPDATE:
message = "updating...";
_post(payload.action.data);
break;
}
MyStore.emitChange();
return true;
})
});
module.exports = MyStore;
Then you need to subscribe your component to the store change events
var React = require('react');
var MyStore = require('my-store');
function getComments (){
return {
message: null,
data: MyStore.getData()
}
};
var AlbumComments = module.exports = React.createClass({
getInitialState: function() {
return getData();
},
componentWillMount: function(){
MyStore.addChangeListener(this._onChange);
},
componentWillUnmount: function(){
MyStore.removeChangeListener(this._onChange);
},
_onChange: function(){
var msg = MyStore.getMessage();
if (!message){
this.setState(getData());
} else {
this.setState({
message: msg,
data: null
});
}
},
render: function() {
console.log('render');
return (
<div>
{ this.state.message }
{this.state.data.map(function(item){
return <div>{ item }</div>
})}
</div>
);
}
});
I hope it is clear enough.
I'm using Facebook JavaScript SDK to log in with Facebook,
the only problem is that the JavaScript code executed after the controller.
all i want is to check if the user logged in before going to the controller.
Any help?
This is the java script Code
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({ appId: '#Facebook.FacebookApplication.Current.AppId', channelURL: '#Request.Url.Scheme://#Request.Url.Authority#Url.Content("~/fbchannel.ashx")', cookie: true, xfbml: true, oauth: true });
FB.Event.subscribe('auth.login', function (response) { window.location.reload(); });
FB.Event.subscribe('auth.logout', function (response) { window.location.reload(); });
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
$.ajax({
url: '/Home/SaveAccess',
type: 'POST',
data: { A: accessToken },
success: function (data) {
},
error: function() {}
});
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} else if (response.status === 'not_authorized') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
$.ajax({
url: '/Home/SaveAccess',
type: 'POST',
data: { A: accessToken },
success: function () {
}
});
} else {
}
});
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
i save the Access Token in a session, the problem is that this code executed after the controller code.
Didn't understand exactly what you wanted. Here's a solution for what I did.
You can call FB.getLoginStatus anytime to check if the user is connected or not.
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
// user logged in and connected
}
});
You can also add this in the fbAsyncInit to check user status every time the page loads.