Ajax call with flask-seasurf - ajax

I am developing a small app on localhost and using flask-seasurf to prevent csrf attacks. All my non-ajax forms work correctly with flask-seasurf. I have one form that triggers an ajax call to '/checkajax' on form submit; this worked until I started to use flask-seasurf but now I get a console error and the ajax doesn't work:
Warning in flask_seasurf: Forbidden (CSRF token missing or incorrect): /checkajax
The form triggering the ajax call has the standard hidden field containing the 'csrf_token()' function call of flask-seasurf embedded in the jinja page template:
<input id="csrf-token" type="hidden" name="_csrf_token" value="{{ csrf_token() }}">
The ajax call structure is:
$("#submit").submit(function(event) {
event.preventDefault();
$.ajax({
url: "/checkajax",
data: {...},
type: "POST",
datatype: "text",
success: function(response){
...
},
error: function(response) {
...
}
});
});
I can see from the site cookie that there is an entry for '_csrf_token' generated by flask-seasurf. Can anyone give some insight as to why this ajax call is now not working?

The solution to my problem was to modify the header of the ajax call to include X-CSRFToken defined as the flask-seasurf token from my form:
var csrf_token = $("csrf-token").val()
$("#submit").submit(function(event) {
event.preventDefault();
$.ajax({
headers: {"X-CSRFToken", csrf_token},
url: "/checkajax",
data: {...},
type: "POST",
datatype: "text",
success: function(response){
...
},
error: function(response) {
...
}
});
});
Hope that helps someone else.

Related

Ajax link does not send POST request

I have the following ajax link:
#Html.AjaxActionLink(item.Name, "https://test.testspace.space/storage/Data/stream?tokenValue=e58367c8-ec11-4c19-995a-f37ad236e0d2&fileId=2693&position=0", new AjaxOptions { HttpMethod = "POST" })
However, although it is set to POST, it seems that it still sends GET request.
UPDATE:
As suggested below, I also tried with js functuion like this:
function DownloadAsset() {
alert("downloading");
$.ajax({
type: "POST",
url: 'https://test.testspace.space/storage/Data/stream?tokenValue=add899c5-7851-4416-9b06-4587528a72db&fileId=2693&position=0',
success: function () {
}
});
}
However, it still seems to be GET request. Parameters must be passed as query and not in the body of the request because they are expected like that by the target action. I don't know why (it would be more natural to have GET request) but back-end developer designed it like this due to some security reason.
If I use razor form like this, then it works:
<html>
<form action="https://test.testspace.space/storage/Data/stream?tokenValue=2ec3d6d8-bb77-4c16-bb81-eab324e0d29a&fileId=2693&position=0" method="POST">
<div>
<button>Send my greetings</button>
</div>
</form>
</html>
However, I can not use this because I already have bigger outer form on the page and I'll end up with nested forms which is not allowed by razor/asp.
The only way is to use javascript but for some reason it does not make POST request.
#Html.AjaxActionLink will generate to <a> tag,and tag will only have HttpGet request method.If you want to send HttpPost with <a> tag,you can use it call a function with ajax,here is a demo:
link
<script>
function myFunction() {
$.ajax({
type: "POST",
url: "https://test.testspace.space/storage/Data/stream",
data: { tokenValue: "e58367c8-ec11-4c19-995a-f37ad236e0d2", fileId: "2693", position:0 },
success: function (data) {
}
});
</script>
Since you want to make a POST request, but the values need to be as query string params in the URL, you need to use jquery.Param.
see https://api.jquery.com/jquery.param/.
You should set the params, like below :
$.ajax({
url: 'your url',
type: 'POST',
data: jQuery.param({ tokenValue: "your token", fileId : "2693", position: 0}) ,
...
Try this instead,
First remove the action url from the from
Second put the result in the success function to return response
and for parameters, I always use FormData() interface to post with Ajax
And last don't forget to include dataType, contentType, processData to not get an unexpected behavior
your code will look like this
var form_data = new FormData();
form_data.append('tokenValue' ,'add899c5-7851-4416-9b06-4587528a72db&fileId=2693');
form_data.append('position' ,'position');
$.ajax({
type: "POST",
dataType: 'json',
contentType:false,
processData:false,
data: form_data,
url: 'https://test.testspace.space/storage/Data/stream',
success: function (result) {
}
});

Laravel ajax post not working even though CSRF token included

I am having difficulty getting an ajax post to work with laravel v5.5.24. Here is what my ajax call looks like:
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/postCustomer?XDEBUG_SESSION_START=19683",
type: 'POST',
data: {_token: CSRF_TOKEN, message:myData, "_method": 'POST'},
dataType: 'JSON',
success: function (data) {
console.log('call to postCustomer successful');
}
});
Here is my route:
Route::post('/postCustomer','AdminUserController#store');
The interesting thing about this problem is that when all the post's are changed to get's (both in the ajax call and in the route) the request arrives and is handled correctly. The debug is triggered, and all is well. However, iof the route and the ajax call is set to POST, the debug is never triggered, and the request does not appear to make it. Naturally this smells like a CRSF issue, but I am including the CRSF token in the header.
if the javascript code inside .blade.php file try this
data: {_token:'{{ csrf_field() }}', message:myData, "_method": 'POST'},
hope its help
Try this,
<meta name="_token" content="{!! csrf_token() !!}"/>
$.ajaxSetup({
headers:
{'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}
});
$.ajax({
url: "/postCustomer?XDEBUG_SESSION_START=19683",
type: 'POST',
data: {message:myData, "_method": 'POST'},
dataType: 'JSON',
success: function (data) {
console.log('call to postCustomer successful');
}});
No need to pass token in ajax data again.
Heartfelt thanks to everyone who responded. A couple of things helpled in fuguring this thing out. First of all, I consolidated the CSRF token mentions,
and confined what I was sending as data to just that - no need to include the CSRF token in the data if you do it in the ajaxSetup. The second thing wasn't visible from my post, but I was encountering a race condition involving the button that triggered the ajax transaction. The button was causing a page reload before ajax could do its thing, and this is why occasionally the thing would appear to work, but mostly not. So the return false is necessary to prevent that - probably not in both places, but certainly after the ajax transaction has been invoked and we are waiting for the callback. The code which works can be found below. I hope it will prevent somebody else from spending a night going mad trying how to figure out what their POST's aren't working. Take away points: handle your CSRF in an ajaxSetup call, and return false from the whole business.
Thanks again to everybody.
-George Pipkin
Afton, Virginia
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
/* the route pointing to the post function */
url: "/postCustomer?XDEBUG_SESSION_START=19159",
type: 'POST',
/* send the csrf-token and the input to the controller */
data: {message:myData},
dataType: 'json',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
$("#success_msg").show();
return false;
}
});
return false;
You should have to pass the _token inside the data object.
data: {_token:'{{ csrf_token() }}',, message:myData, "_method": 'POST'},

Laravel - DELETE Ajax request

I am using Laravel 5.0. I have created a RESTful Controller. Now i wanna use the destroy function via an ajax call.
This is my JS:
$.ajax({
type: 'POST',
url: '/pv/' + data.id,
data: {_method: 'delete' },
success: function(data){
console.log(data);
}
});
And this is my destroy function:
public function destroy($id)
{
$pv = PV::find($id);
$pv->delete();
return true;
}
All i got is a 500 error.
first check your route in laravel
Route::delete('/deleteprocess', 'Controller#destroy');
in javascript
$.ajax({
url: '/deleteprocess',
type: 'POST',
data:{
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
},
success: function(result) {
// Do something with the result
}});
set type : POST,
set token : _token,
set method : _method as DELETE,
That's probabily a "CSRF" Exception. If you are using Ajax Request with jQuery, add this (before your $.ajax):
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
And, in your "html" ..create a new "meta tag" with csrf-token..value:
{{ csrf_token() }}
Read more: http://laravel.com/docs/5.0/routing#csrf-protection

Linking AJAX with PHP code. Do i need to write it again?

I have a real problem. I have a php code and a form where when the form is submitted a POST request is sent and the page reloads again and ofcourse the post is viwed in the page.But i want to work with AJAX in order page not to be refreshed.I know the basics of AJAX but i don't want to build all the project from the beggining.Is there a way in success function of AJAX to link to my php code??
$.ajax({
type: "POST",
url: "index.php",
datatype: "html",
data: dataString,
success: function(data) {
//How can i link here to start running my php code which is located in the same page.
}
});
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
// try this
console.log(data);
// see what 'data' actually is
}
});
then check in the browser by hitting F12 to look at the console.
also are you sure you want datatype of html ? you probably want a data type of json or XML , what is the server returning to you after the ajax post?
You have to cancel the form's submission so that the ajax request will take place, otherwise it is canceled. Also use .serialize to get a name-value pair string of the form data to use in the ajax call.
Html
<form id="MyForm">
<button id="MyButtonId">Submit</button>
</form>
JS
$("#MyForm").submit(function(e){
//Prevents the form from being submitted
e.preventDefault();
$.ajax({
type: "POST",
data: $("#MyForm").serialize(),
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
alert(data);
}
});
});

using ajax in a page loaded by ajax

i have a page loaded via jquery tabs ajax, i have a form within this page that i want to show form response via ajax. response is loading from this code:
$('#whois').submit(function() {
$.ajax({
data: $('#whois').serialize(),
cache:false,
type: "POST",
url: $('#whois').attr('/lib/domainchecker.php'),
success: function(response) {
$('#reply').html(response);
}
});
return false;
);
but my form submit to parent page instead of /lib/domainchecker.php. so i see headers of my page instead of response!
any idea what makes this happen?
When you are loading content on the page via AJAX and you need to apply events to the loaded content you need to use the jquery live().
$('#whois').live('submit', function() {
$.ajax({
data: $('#whois').serialize(),
cache:false,
type: "POST",
url: $('#whois').attr('/lib/domainchecker.php'),
success: function(response) {
$('#reply').html(response);
}
});
This of course goes on the main host page rather than the loaded content page.
problem is solved, no thing related to loading page via ajax but there was an error with code, i shouldn't post to $('#whois').attr('/lib/domainchecker.php') but just '/lib/domainchecker.php'
corrected code:
$('#whois').live('submit', function() {
$.ajax({
data: $('#whois').serialize(),
cache:false,
type: "POST",
url: '/lib/domainchecker.php',
success: function(response) {
$('#reply').html(response);
}
});

Resources