Laravel 5.4 not accepting post request in routes - ajax

I have made a ajax call in laravel 5.4 following is the script
<script>
$(document).ready(function()
{
$("#btnLogin").click(function()
{
// var username = $('#username').val();
// var password = $('#password').val();
// var form = new FormData($('.login-form')[0]);
var form = $('.login-form').serializeArray();
$.ajax({
url: '/login',
type: 'POST',
dataType: 'JSON',
data: {form},
})
.done(function(resp){
console.log(resp);
})
.fail(function(resp){
console.log(resp);
})
.always(function(resp){
console.log(resp);
});
});
});
</script>
This is my web.php in routes folder
<?php
Route::match(['get', 'post'], '/login', function () {
return "hello";
});
It is showing the error in console log, i dont know why it is showing this. Firstly it was showing 404 not found then i realized that i had not defined in rotes then i defined in routes then it is showing this error.
POST http://www.example.com/login 500 (Internal Server Error)
If access this url through browser direct it is showing hello but if i am making through ajax it is not loading.

When you hitting through browser, you are requesting page with get request, however, through ajax, it goes through post.

Related

AJAX POST Request in Laravel says url not found

I am trying to post data to a controller through ajax request. But it can't find the route and says the following in console.
POST http://127.0.0.1:8000/addNotification_action 404 (Not Found)
This is my ajax call below.
function editNotification(obj) {
// alert(obj.id);
var obj_id = obj.id;
var id = obj_id.split("_");
$.ajax({
url: "{{ url('addNotification_action') }}",
type: 'POST',
dataType: 'json',
data: {edit_notification_id: id[1]},
})
.done(function(result) {
console.log(result);
$('#title').val(result['title']);
$('#description_notification').val(result['details']);
$('#edit_flag_notification').val(result['notification_id']);
})
.fail(function() {
alert("error");
});
}
And I am just trying to dd() the request I get in the controller. Please help. Thanks
First of all, you should create a route and give this route a name. You have to generate the ajax url as "route('route_name')".
// Route (for Laravel 8)
Route::post('addNotification_action', [NotificationController::class, 'notify_method'])->name('notify');
// Ajax Settings
....
url: "{{ route('notify') }}",
....
Jus Give admin/addNotification_action in Ajax URL

ajax query without passing page data laravel 5.6

I have a button and when it's clicked, I basically want to load the Auth::user()->name and a date into the database. I can't figure out how to do an ajax call without passing in some sort of data. This is my ajax query.
var url2 = "/application-background-sent/{{$application->id}}";
$(document).ready(function(){
$('#bgSubmit').click(function(e){
$.ajax({
url: url2,
success: function(data) {
alert(data);
},
type: 'GET'
});
});
});
My route:
Route::get('/application-background-sent/{id}', 'ApplicationsController#backgroundSent');
My controller:
public function backgroundSent($id)
{
$application = Application::findOrFail($id);
$application->bg_check_submitted_by = Auth::user()->name;
$application->save();
return response()->json(['success'=>'Data is successfully added']);
}

How to post data controller in Laravel 5.4?

I cannot post my data to my controller, is there something wrong with my ajax call? my setup for the web.php, or is the controller not setup, the error i get is. reminder this is laravel 5.4 running locally
POST http://127.0.0.1:8000/change-rank 500 (Internal Server Error)
JS
$('.rank-select').change(function(){
var id = $(this).val();
var memberId = $(this).closest('.irmember').attr('id');
console.log(id);
console.log(memberId);
$.ajax({
type: "POST",
url: 'change-rank',
data: {id: id, memberId, memberId},
success: function( msg ) {
console.log(msg);
}
});
})
web.php
Route::post('change-rank', 'RankController#changeRank');
RankController.php
namespace App\Http\Controllers;
use App\Rank;
use Illuminate\Http\Request;
class RankController extends Controller
{
public function changeRank()
{
info("hi");
}
}
The JS code you show does not include the CSRF token, which will certainly throw a 500 server error. There are different ways to include your CSRF token in AJAX calls, here's one example.
In your form:
<form>
{{ csrf_token() }}
....
In your JS:
var token = $('input[name="_token"]');
....
$.ajax({
data: {_token: token, id: id, memberId: memberId},
...
There are other approaches here on SO, and the Laravel docs suggest another method.
BTW, 500 server error is just a generic error telling you that, well, there was a server error. You really need to know what the error was if you want to solve it - and you should be able to see that in both the laravel and webserver (Apache/nginx/etc) logs. Your logs probably say something like "CSRF TokenMismatchException" which might have led you straight to the answer! :-)
EDIT
I've just noticed a typo in your Javascript which I initially copied into my answer. It may just be a typo here and not in your real code as it would likely throw JS errors rather than run and generate server error.
data: {_token: token, id: id, memberId, memberId},
should be:
data: {_token: token, id: id, memberId: memberId},
(colon after memberId).
Change your JS code like:
$('.rank-select').change(function(){
var id = $(this).val();
var memberId = $(this).closest('.irmember').attr('id');
console.log(id);
console.log(memberId);
$.ajax({
type: "POST",
url: 'change-rank',
data: {id:id, memberId:memberId},
success: function( msg ) {
console.log(msg);
}
});
});
Its simple change to ajax params its should work fine.
$('.rank-select').change(function(){
var id = $(this).val();
var memberId = $(this).closest('.irmember').attr('id');
console.log(id);
console.log(memberId);
$.ajax({
type: "POST",
url: 'change-rank',
data: {id:id, memberId:memberId},
success: function( data) {
console.log(data);
}
});
});
And controller file is,
public function changeRank(Request $request)
{
return $request->all();
}

Ajax request returning 404 in Laravel 5.4

This is my script I am using in Laravel 5.4:
<script>
$(document).ready(function()
{
$("#btnLogin").click(function()
{
// var username = $('#username').val();
// var password = $('#password').val();
// var form = new FormData($('.login-form')[0]);
var form = $('.login-form').serializeArray();
$.ajax({
url: '/login',
type: 'POST',
dataType: 'JSON',
data: {form},
})
.done(function(resp){
console.log(resp);
})
.fail(function(resp){
console.log(resp);
})
.always(function(resp){
console.log(resp);
});
});
});
</script>
I have made a Login Controller In app\http\Controllers\LoginController.php.
Whenever an ajax request in console it is showing in POST http://www.example.com/login 404 (Not Found)
where example.com is virtual host created on wamp.
I am new to Laravel 5.4.

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

Resources