AJAX POST Request in Laravel says url not found - ajax

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

Related

No query results for model [App\Facility] getAllData

i want to ask about this question, because this is make me crazy.
So i want to load datatables using ajax, i got this in view
$.ajax({
type: "GET",
url: "facility/getAllData",
success: function(data) {
console.log(data);
}
});
Then this is my routes
Route::get('/master_data/facility/getAllData', 'FacilityController#getAllData')->name('facility.getAllData');
The last Part is my controller
public function getAllData()
{
$facilities = Facility::all();
return response()->json($facilities);
}
Thats all my code, i already use App\Facility; what is wrong with my code? thanks
You are using a named route so you will need to add something like this to your view:
$.ajax({
type: "GET",
url: {{ route("facility/getAllData") }}, // named route
success: function(data) {
console.log(data);
}
});
or use the full route url url: "/master_data/facility/getAllData"

ajax post request to view

I am trying to make a simple ajax request to a view but keep having a not Found error for the given url:
Not Found: /myapp/start_session/1/scan_ports/
"POST /myapp/start_session/1/scan_ports/ HTTP/1.1" 404 5711
js
$(document).ready(function() {
$.ajax({
method: 'POST',
url: 'scan_ports/',
data: {'csrfmiddlewaretoken': '{{csrf_token}}'},
success: function (data) {
alert("OK!");
},
error: function (data) {
alert("NOT OK!");
}
});
});
url
url(r'^scan_ports/$',views.ScanPorts,name='scan_ports'),
view
#login_required
def ScanPorts(request):
user = request.user
if request.method == 'POST':
currentSetting = models.UserSetting.objects.filter(isCurrent=True)
if currentSetting.serialPort:
print("GOT IT!")
return HttpResponse('')
Is the ajax request not set properly?
Assuming you are in the "myapp" app, replace:
method: 'POST',
url: 'scan_ports/',
for this:
method: 'POST',
url: '/myapp/scan_ports/',
First check your urls, the url on which you posted is incorrect hence 404 not found error.
Try to define your url in your JS as: {% url 'scan_ports' %} which will search your urls with the name your provided in urls.py
In addition, this may not be a good approach to submit a form via ajax.
Your JS should be something like this:
$('.form-class-name').on('submit', function (e) {
e.preventDefault();
console.log("ajax is called");
$.ajax({
type: $(this).attr('method'),
url: "/url-name/",
data: $(this).serialize(),
dataType: 'json',
success: function(data) {
alert("success");
},
error: function(data) {
alert("Failure");
}
})
}
e.preventDefault() prevents the natural/default action, and prevents from submitting the form twice.
.serialize(), serializes the form data in a json format.
append a "/" before and after your action url.
Your view must return a dictionary as ajax deals with JSON format.
Edit your view like this:
if request.method == "POST":
currentSetting = models.UserSetting.objects.filter(isCurrent=True)
if currentSetting.serialPort:
print("GOT IT!")
a = {'data':'success'}
return HttpResponse(json.dumps(a))
This will return a dictionary required by the ajax.

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();
}

Laravel 5.4 not accepting post request in routes

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.

Ajax not reciving data. Symfony2

The idea is when i click on a button it calls sendeRequest() and the controller receives the petition. But I'm not receiving anything.
I wan't to send a request to the controller. (I have set a redirection in the controller, to check that I'm receiving the data). I've tried doing:
function sendRequest(){
$.ajax({
type: "POST",
url: "{{ path('login') }}" ,
cache: "false",
dataType: "html",
success: function(result){ $("div#box").append(result);}
});
}
And in the controller
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
return $this->render('mainBundle:Register:register.html.twig');
}
I'm using jquery 1.7.2
You can do this:
if($this->getRequest()->isXmlHttpRequest()){
return new Response(json_encode(array(
'form'=>$this->render('mainBundle:Register:register.html.twig')->getContent()))
);
}

Resources