I'm new to Laravel and using Ajax for some functionalities.
//Route
Route::post('some/thing/','Controller#Method');
//jQuery
$('.some_class').click(function(){
var var1 = $('.some').val();
var val2 = $(".another").val();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
//this part
url: "some/thing/",
type:"POST",
data: { var1: var1,val2: val2,_token: CSRF_TOKEN},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
});
//controller
public function Method(Request $object){
if(isset($_POST['val1'])){//do something}
}
problem is in the URL parameter of AJAX. When I'm giving value to the url i.e some/thing/, it gives me 404 error showing www.siteurl/some/thing/some/thing/ not found and when I'm keeping url value blank then it's working. But then i don't think it's a good practice to do like this.
I have seperate .js file in public folder.
Controller in different and blade file in different directory. Laravel version 5.6.22
thank you.
I think you have to change the Url to the absolute path:
Incase you are working on Blade file:
Change the url from : url: "some/thing/",
To url: {{url('some/thing')}},
In case you are working on external Js File:
Change the url from : url: "some/thing/",
To url: url: "/some/thing/",
When you write the url to ajax its trying to achieve some/thing/some/thing/
To fix; give a name for your route and then use this name for your ajax url.
//Route
Route::post('some/thing/','Controller#Method')->name('yourRouteName');
//jQuery
$('.some_class').click(function(){
var var1 = $('.some').val();
var val2 = $(".another").val();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
//this part
url: "{{ route('yourRouteName') }}",
type:"POST",
data: { var1: var1,val2: val2,_token: CSRF_TOKEN},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
});
Use absolute path instead of relative. append / before the url like "/some/thing/"
$('.some_class').click(function(){
var var1 = $('.some').val();
var val2 = $(".another").val();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
//this part
url: "/some/thing/",
type:"POST",
data: { var1: var1,val2: val2,_token: CSRF_TOKEN},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
});
Hope this helps.
You can add route in $except array in VerifyCsrfToken middle ware to ignore csrf token verification on that route
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
"/some/thing/"
];
}
Related
I am new to Laravel.
Trying to Pass ID from View to Controller but getting Error
POST http://127.0.0.1:8000/getbuffaloidformonitor 404 (Not Found)
This is my View BuffaloMonitor :
$(document).on('click', '.viewmonitormodal', function() {
var modal_data = $(this).data('info').split(',');
$('#viewbuffaloID').val(modal_data[1]);
var buffaloid = document.getElementById('viewbuffaloID').value// get buffalo id from textbox to get data for that ID
alert(buffaloid);
//alert(data);
$(function() {
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor",
data: {
'_token': $('input[name=_token]').val(),
'id': buffaloid,
},
success : function(response) {
alert(response);
}
});
});
}
This is BuffalomonitorCOntroller :
public function getbuffaloidformonitor(Request $req) {
$data = buffalodata::find($req->id);
alert(data);
$id = $req('data');
return $id;
}
This Is Route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
Your post route has {id} but it's not necessary. This is what you need Route::post('/getbuffaloidformonitor','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
pass id to the link http://127.0.0.1:8000/getbuffaloidformonitor
as you write the route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
You are just pass id by routes Params, so the URL must like this
http://127.0.0.1:8000/getbuffaloidformonitor/yourbuffaloid
You need to change URL.
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor/" + buffaloid,
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If you use this script in you blade template just use
const url = '{{ route("getbuffaloidformonitor",":id") }}'
$.ajax({
method : "POST",
url: url.replace(':id',buffaloid),
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If your routes {id} is optional just
Route::post('/getbuffaloidformonitor/{id?}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
with question on your id route you can use both by pass id by route params or you can pass id by data post.
In controller
public function getbuffaloidformonitor(Request $req, $id = null)
{
// id is get from route params
$getId = $req->get('id') // this one get from data post.
}
I am coding a small Django project where an user can select an object and save it in a database. I am trying to implement an Ajax call on a button to delete this object if necessary.
I am doing it step by step, debugging with the console.
my urls:
app_name = 'register'
urlpatterns = [
path('<int:user_id>/', views.account, name='account'),
path('/delete/', views.delete, name='delete'),
]
my view.py:
def delete(request):
data = {'success': False}
if request.method=='POST':
product = request.POST.get('product')
print(product)
data['success'] = True
return JsonResponse(data)
my ajax.js:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var product = 'coca-cola'
console.log('ok till this point')
$.ajax({
url: '{% url "register/delete" %}',
type: "POST",
data:{
'product':product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
console.log('working fine')
}
});
});
My view isn't doing much for now but I haven't any knowledge about Ajax and I am doing it one step at a time.
This is the error I get in the console:
jquery.min.js:2 POST http://127.0.0.1:8000/register/6/%7B%%20url%20%22register/delete%22%20%%7D 404 (Not Found)
As far as I understand, Ajax can't find my url: '{% url "register/delete" %}'.
I have tried '{% url "register:delete" %}' with no luck either.
I found an answer after some tweaking, I defined my url before the Ajax call and then pass it in it:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var product = 'coca-cola'
var url = '/register/delete/'
console.log( url)
$.ajax({
url: url,
type: "POST",
data:{
'product':product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
console.log('working fine')
}
});
});
Also you can add just the string of url to "url" parameter without characters {% url %}. Maybe you copied the code from pattern Django and added it to JS-file. So it does not work.
I'm writing an ajax that works when url contains a constant but does not work when url contains a variable because this does not get replaced by the actual value.
$('body').on('click', '.deleteLayer', function () {
var layer_id = $(this).data('id');
confirm("Are You sure want to delete record with layer_id="+layer_id+"?");
$.ajax({
type: "POST",
url: "{{ route('layers.destroy',['layer' => "+layer_id+"])}}",
data: {_method: 'delete', layer:layer_id},
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
If I use a value, let's say 50 instead of layer_id then it works!!!:
url: "{{ route('layers.destroy',['layer' => 50])}}",
This is the route that I try to access:
DELETE | admin/layers/{layer} | layers.destroy
If I do not send layer parameter in the url I receive the following error
message : "Missing required parameters for [Route: layers.destroy]
[URI: admin/layers/{layer}]. (View:
/var/www/laravelapp/resources/views/layers.blade.php)"
Why is layer_id, here
url: "{{ route('layers.destroy',['layer' => "+layer_id+"])}}",
not replaced by the actual value?
When you are writing like ['layer' => "+layer_id+"] the js variable is not working. It goes like +layer_id+ as the parameter of the route. You can try like this
var layer_id = $(this).data('id');
var url = '{{ route("layers.destroy", ":id") }}';
url = url.replace(':id', layer_id );
$.ajax({
type: "POST",
url: url,
data: {},
success: function (data) {
},
error: function (data) {
}
});
{{URL::to('/destroy')}}+'/'+layer_id;
Route
Route::get('/destroy/{id}', 'controller#destroy')
Controller
public function destroy($id){
// use $id here
}
Hope you understand.
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"
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();
}