I'm using this code to submit data through ajax in laravel
$('#submit').submit(function (e) {
e.preventDefault();
let formData = new FormData(this);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
if (percentComplete === 100) {
}
}
}, false);
return xhr;
},
url: $(this).attr('action'),
type: "POST",
data: formData,
dataType:'JSON',
contentType:false,
cache: false,
processData: false,
but getting csrf token mismatch when i upload my code on live server.
Any solution is highly appreciated Thanks
I see you are fetching the token from the HTML page metatag, make sure your HTML page is not being cached by an intermediate/browser between accesses (try opening with two different browsers and checking the token, refreshing with f5 and force reloading too).
Another common issue is multiple HTML pages being loaded simultaneously (frames? maybe a 404 file that returns your default page, refreshing the token for your session). This is hard to find, check the network tab of your browser dev tools and inspect each response.
I don't think it's the case, but sometimes the case makes difference X-CSRF-Token if a proxy is "cleaning up non whitelisted headers".
Related
I am using ModelViewSet to fetch objects from my database and rendering them in a Django template. Since JWT Authentication is needed, I am sending the token in the header of AJAX request. I get the response back but if I redirect to the correct page I get a 401 Unauthorised.
$.ajaxSetup({
headers: {
'Authorization': "Bearer " + window.sessionStorage.getItem("token")
}
});
$(document).ready(function () {
$("#id").on('click', function (event) {
event.preventDefault()
var url = "myurl"
$.ajax({
url: url,
type: 'GET',
dataType: "html",
tokenFlag: true,
success: function(res) {
location.href = url
}
});
});
});
I want the page to redirect and the template rendered. It works fine in Insomnia.
I'm trying to figure out what is Adobe Coldfusion and how to work on this platform.
I'm stuck at simple issue.
On submit I send form with jQuery ajax to server.
But I got response: 500 (Element MY_VAR is undefined in FORM.)
What I'm doing wrong?
JS
$loginForm.on('submit', function(e) {
e.preventDefault();
var formData = new FormData(e.target);
$.ajax({
url: 'test.cfm',
method: 'POST',
cache: false,
processData: false,
data: formData,
error: function(err) {
console.log(err);
},
success: function(data, status) {
console.log(status);
console.log(data);
}
});
});
CF
<cfoutput>
<p>#form.myvar#</p>
</cfoutput>
500 indicates an internal server error.
Are you trying to display your form values after sending them?
Maybe try and use the cfdump tag. Very useful for debugging.
Try dumping the form scope and see what variables are actually in there.
I making an AJAX request to the food2fork api and can't get by the No 'Access-Control-Allow-Origin' header is present error. I've tried setting the header in beforeSend and setting crossDomain: true but it didn't work.
This is my AJAX call:
$.ajax({
type: "GET",
dataType: 'json',
url: url,
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
success: function(data){
console.log('in ajax json call');
console.log(data);
$('#info').html(JSON.stringify(data));
}
});
I tried setting the request header server side in node express.js with:
router.get('/test', cors(), function(req,res)
{
res.set("Access-Control-Allow-Origin", "*"); //set header here
res.render('exampleSearch', {title: 'FM | Test'});
});
Cors is an npm package that sets cross-reference permissions but didn't help me solve the problem.
Can you tell me what I'm doing wrong?
Client-side request doesn't work in this case. I had to do the request server side:
router.post('/test', function(req,res){
var callback = function(response){
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved
response.on('end', function () {
var recipes = JSON.parse(str);
//do something with recipes
});
}
var options = {
host: "food2fork.com",
path: "/api/search?key=[myKey]&q=" + ingredients
};
http.request(options,callback).end();
});
Used code from nodejitsu.com
Aim - to get the twitter followers of a particular user using javascript
I have tried the below code as a POC-
$(document).ready(function() {
// Handler for .ready() called.
$.ajax({
url: "https://api.twitter.com/1.1/followers/ids.json?callback=?",
type: "GET",
data: { cursor: "-1",
screen_name: "twitterapi" },
cache: false,
dataType: 'json',
success: function(data) { alert('hello!'); console.log(data);},
error: function(html) { alert(html); },
beforeSend: setHeader
});
function setHeader(xhr) {
if(xhr && xhr.overrideMimeType) {
xhr.overrideMimeType("application/j-son;charset=UTF-8");
}
//var nonce = freshNonce();
//var timestamp = freshTimestamp();
//var signature = sign(nonce,timestamp);
//alert(signature);
//alert(accessToken+"-"+consumerKey);
//alert(oauth_version+"-"+oauth_signature_method);
xhr.setRequestHeader('Authorization','OAuth');
xhr.setRequestHeader('oauth_consumer_key', 'HdFdA3C3pzTBzbHvPMPw');
xhr.setRequestHeader('oauth_nonce', '4148fa6e3dca3c3d22a8315dfb4ea5bb');
xhr.setRequestHeader('oauth_signature','uDZP2scUz6FUKwFie4FtCtJfdNE%3D');
xhr.setRequestHeader('oauth_signature_method', 'HMAC-SHA1');
xhr.setRequestHeader('oauth_timestamp', '1359955650');
xhr.setRequestHeader('oauth_token', '1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl');
xhr.setRequestHeader('oauth_version', '1.0');
}
});
I calculated the signature values from the Twitter OAuth tool ..
This gives me 400 Bad Request error ....
Please let me know what the problem is...
The problem is your request's header, it should be like this:
xhr.setRequestHeader('Authorization','OAuth oauth_consumer_key="HdFdA3C3pzTBzbHvPMPw", oauth_nonce="4148fa6e3dca3c3d22a8315dfb4ea5bb", oauth_signature="uDZP2scUz6FUKwFie4FtCtJfdNE%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp= "1359955650", oauth_token, "1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl", oauth_version="1.0"');
Btw, this javascript library might help you on OAuth's stuff: oauth-1.0a
It support both client side and node.js
Cheers
The oauth_* fields are all part of the Authorization header string, so they need to be concatenated as shown at the bottom of this page - https://dev.twitter.com/docs/auth/authorizing-request
They should not be presented as separate header fields.
This function is working on Chrome and Firefox but not on IE9, where errorHandler is logging this error message:
ERROR: getFriendsArray {"readyState":0,"status":0,"statusText":"No Transport"}
getUserAccessToken() is returning the right value. Any ideas what could it be, that only affects IE?
EDIT: seems that https://graph.facebook.com/me/friends directly on IE browser returns HTTP 400 error.
function getFriendsArray() {
var friendsArray = [];
$.ajax({
url: 'https://graph.facebook.com/me/friends',
data: {
access_token: getUserAccessToken(),
fields: 'name,picture,gender'
},
dataType: 'json',
cache: true,
async: false,
success: function(response) {
var data = '';
$.each(response.data, function(indice, item) {
friendsArray.push(item);
});
},
error: function(err) {
errorHandler('getFriendsArray', JSON.stringify(err));
}
});
return friendsArray.sort(sortByName);
}
$.ajax only supports using XMLHttpRequest or XDomainRequest (IE), the latter only supporting a few scenarios, and requiring that your page is SSL if the requested resource is SSL.
Instead, use FB.api, which handles this and much more, ensuring that the call makes it through, either by using JSONP, XHR, XDomainRequest, or Flash.