Error 405 when trying to make an Ajax request - ajax

Good afternoon. I am having a problem sending a route using Ajax The problem is as follows. I have an HTML form that contains a selection of employees. What I intended was that when I selected an employee, Ajax would return me the positions concerning him. I had done something similar before, but this error had never occurred.
JS
$('#funcionario').change(function(){
$.ajax({
url:'teste',
type:"POST",
data:{
'_token': $('input[name=_token]').val(),
'id' : $('#funcionario').val();
},
}).done(function(e){
alert("success->"+ e)
}).fail(function(){
alert('Deu ruim')
})
})
Route
Route::POST('teste', function() {
return 1;
});

Related

Post a form on click of table row

I wanted post a form on click of row of table and pass that row data with it. I am passing data to controller using ajax.
$("#return_table tr").click(function(e){
$(this).addClass('selected').siblings().removeClass('selected');
var name = $("#cityName").val();
var initial = $("#cityInitial").val();
$.ajax({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type:'post',
data: $('#return_flight').serialize(),
success: function () {
alert('form was submitted');
}
});
});
This is my ajax.
My route is Route::post('/dashboard/return','Users\BookTicketController#retrunTime');
When I click on any row then I am getting error that POST http://127.0.0.1/dashboard/return 500 (Internal Server Error)
What is a issue with this code?
The issue is not in this code It probably occurring at your backend code, check your retrunTime function implementation.
check out this link understand more about why and when 500 error occurs.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500

ajax request is not returning back to view in laravel 5

I wanted to submit a for using ajax call in laravel 5.
In view i wrote something like
$("#updateSubmit").on('submit',function(e){
e.preventDefault();
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
method:'POST',
url: '/account/updateForm',
//dataType: 'json',
data: {accountId:'1111', _token: '{{csrf_token()}}'},
success: function( data )
{
alert(data)
return false;
}
},
error: function(error ){
alert("There is some error");
}
});
and on controller side
public function update(Request $data )
{
return Response()->json(['success' => true],200);
}
while in route for post method
Route::post('account/updateForm', 'AccountController#update')->name('account/updateForm');
its working till ajax. on Submission of ajax it goes to controller action.
but it does not retrun back as ajax comes back in normal form submisson.
it just go to controller and stops there with {"success":true} line.
I want ajax to come back to view form so that I can perform different dependent actions.
Do you mean that when you submit your form, you just have a white page with {"success": true} ?
If that's the case, maybe the error is on your javascript.
Maybe your jQuery selector is wrong, or maybe your js isn't compiled ?

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')

Request facebook permissions/login after ajax form validation (in ajax response)

It is working right now , but I have some feedback of user saying that the facebook popup is blocked by the browser
So what I am doing right now: I have a form that is being validated via ajax (making a call to a php page) , then if the response is successful, it ask for the user login/permissions. I assume that the popup is sometime blocked because the browser consider the ajax response not as an user action.
So my code looks like this :
$("#submit").click(function (event) {
event.preventDefault();
$.ajax({
url: url,
type: type,
data: form_data,
success: function(result){
if(result==""){
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me/permissions', function (response) { ... });
} else if (response.status === 'not_authorized') {
FB.login(function (response) { ... });
}
}
}
}
});
Any idea other than putting the facebook calls before the form validation?
You can make ajax request as synchronous call. I don't like it though
btw, what kind of validation you are doing?

How are people handling AJAX posts to ActionMethods using [ValidateAntiForgeryToken]

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) {
// ...
});
});

Resources