How are people handling AJAX posts to ActionMethods using [ValidateAntiForgeryToken] - asp.net-mvc-3

Seeing that the __RequestVerificationToken is not sent when using AJAX and ValidateAntiForgeryTokenAttribute is looking for the token in Request.Form, how are people dealing with this problem.
I ended up doing this.
$("#regmember-form").submit(function (e) {
e.preventDefault();
var token = $('[name="__RequestVerificationToken"]').val();
alert($(this).attr('action'));
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: { __RequestVerificationToken: token }
});
return false;
});
Very similar to the accepted answer.

I grab the input off the page and send it back with the form post. This assumes that you include it on the page in the first place.
$('#somebutton').click( function() {
var data = $('[name="__RequestVerificationToken"]').serialize();
$.post('/foo/bar', data, function(result) {
// ...
});
});

Related

Wordpress, doing AJAX request before admin submit a post

I need to do some server-side checking, before admin may submit a post form:
$('body').on('submit', '#post', function(e) {
if (e.originalEvent === undefined)
{
return true;
}
var thisForm = $(this);
$.ajax('/check.php', $(this).serialize(), function(answer) {
// if answer was ok...
thisForm.submit();
});
return false;
});
actualy it works good, but in case when my post is "draft", I cant put it "public". Nothing changes, I guess some other JavaScript is affraing in the background.
BUT if I do a synchronous verion:
$('body').on('submit', '#post', function(e) {
var error;
$.ajax({type: 'POST', url: '/action.php', data: $(this).serialize(), async: false, success: function(answer) {
// if answer was ok...
error = true OR false;
});
return !error;
});
it all works GOOD! But you all know, one doesnt made synchronous ajax calls...

Laravel 5.2 post route returns plain html text

whenever I send a post request to 'tasks/add' i want the user to return to a new page, but all I get is plain html text in a popup.
Route.php code
Route::post('tasks/add', function() {
return view('secrets');
});
this is my ajax request :
$("#frm").submit(function(e){
e.preventDefault();
var customer = $("input[name=customer]").val();
var details = $("input[name=details]").val();
var dataString = 'customer='+customer+'&details='+details;
$.ajax({
url: "tasks/add",
type:"POST",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data : dataString,
success:function(data){
console.log(dataString);
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
});
Anybody has had this issue before?
You are using Ajax to call your Route method. So when Route::post(...) returns the view 'secrets', it returns it to the Ajax method and becomes held by the data variable. Saying return in your Routes file doesn't magically mean redirect to a certain view, it is just like any other function that returns a value.
You currently have alert(data) which just says make an alert with whatever is held by data which in this case is the html text of your view.
Instead, take out the alert() and put
window.location.replace('<path/to/secrets>')
to redirect to the page you want upon success.
Assuming your Routes file has something like :
Route::get('/secrets', function() {
return view('secrets');
});
You could say
window.location.replace('/secrets')

Chained Select2 whith ajax json values

Have some problems to populate a Select2 with json data retrieved by ajax.
I check all samples from Select2-Github-AjaxData and other from StackOverFlow so always have same problem... the Json retrieved can't update next select2.
Some tries i use Jquery.Ajax to retrieve and assign:
function loadvariedad() {
var productIDVal= $("#frb_producto").val();
$.ajax ({
url: "http://www.fruitbull.info/api/json/es/v",
data: {idv: productIDVal, key:"123456"},
delay: 250,
dataType: 'json',
success: function(theResponse) {
$("#frb_variedad").select2({
data: theResponse.items
});
}
});
};
Other solution checked was the sample on Github form Ajax:
var productIDVal= $("#frb_producto").val();
$('#frb_variedad').select2({
ajax: {
url: 'http://www.fruitbull.info/api/json/es/v?key=123&idv='+productIDVal,
processResults: function (data) {
return {
results: data.items
};
}
}
});
Any idea or help to check?
My sample and tries on Fiddle
Solved by json origin data was formatted incorrectly

Ajax request type POST returning GET

I'm currently trying to make an ajax POST request to send a testimonial simple form to a Django view. The problem is this request is returning a GET instead of a POST.
This is my ajax:
<script>
$(document).ready(function(){
$("form.testimonial-form").submit(function(e){
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
Any idea what could I be doing wrong?
replace type by method
method: 'post',
also you may need send headers:
headers: {
'X-CSRFToken': getCSRFToken()
},
where getCSRFToken is:
function getCSRFToken() {
return $('input[name="csrfmiddlewaretoken"]').val();
}
I am not really sure why this is happening, but i would write the function in a bit different way. since ajax();'s default type is "GET", i suspect somewhere it is being set to default.
first set the type="button" of submit button (whose id is e.g. "submit_button_id"), so it doesnot submits if you click on it. or put the button outside of <form>
then try this code
<script>
$(function(){ // same as "$(document).ready(function()"..
$("#submit_button_id").on('click',function(){
var dataString = $('form.testimonial-form').serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>

Ajax calls and JQuery: stop previuos ajax calls

In a jsp page, when a user clicks a button, an ajax call is triggered.
If the user clicks again and again the button, I would that only the last ajax call be valid and only its response be considered.
I use:
var lastRequest=null;
$('#button').click(function() {
if (lastRequest) {
lastRequest.abort();
lastRequest = null;
}
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
response= $('<div/>').append(response);
}
});
});
With Firebug, I see that some request are aborted, but not all.
I think that if an ajax call is triggered, it's not possible to ignore the response, is it?
EDIT
If I set a var in MyAction.do and I read it in the success callback, is it possible to have a conflict in the success callback?
In case, how could I prevent that behaviour?
My experience with aborting ajax-calls is that it can be pretty random when it works.
A workaround that I've used once or twice is counters:
var lastRequest=null;
var started = 0, finished = 0;
$('#button').click(function() {
++started;
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
//Only do stuff on the last active request
if(++finished == started)
response= $('<div/>').append(response);
}
});
});
use object.abort() to discard data that have been called by service
i have add the code as to click on a button to abort service you can try it with respect to your case :)
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
response= $('<div/>').append(response);
}
});
});
$(document).click(function() {lastRequest.abort() });

Resources