My blade
<i class="bi bi-trash-fill"></i>
my ajax
jQuery('#delete').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
jQuery.ajax({
url: $(this).attr('href'),
type: 'GET',
success: function(result){
console.log("Sucess");
}});
});
});
My route
Route::get('genre_delete/{id}', 'GenreController#genre_delete')->name('artist_genre_delete');
1-Here i am using Ajax to delete only working first row data how to solve this problem
2-and anther one is i am change to route get to delete 405 method not allowed error show.why delete mehod not working.but Get method working fine
You can use Delete method.
Try this
web.php
Route::delete('genre_delete/{id}', GenreController#genre_delete)->name('artist_genre_delete');
Related
I have an ajax function in jquery caling a cakephp4 function. The function doesnt work as it is giving a 403 forbidden error. The error is about headers but i cant find what I need to fix this exactly.
This code runs and it does get the var (alert verifies this). Nothing works ?
jquery
///
var freeassessmentid = "<?=$testid?>";
$.ajax({
url: "/freeassessments/freeasssesmenFinaltResult", //path is correct and it can be tested on its own
method: "POST",
dataType: "html",
data: { freeassessmentid:freeassessmentid },
success: function(response) {
//console.log(response);
$('#display-area').append(response); //no output
}
});
public function freeasssesmenFinaltResult($freeassessmentid=0)
{
//debug('test');
$html .= '<li class="listyle" style="height: auto;">hi<br/></li>';
$html .= '</ul>';
//no output
//https://stackoverflow.com/questions/36666256/jquery-ajax-call-results-in-error-status-403
The Ajax url should be:
url: "/freeassessments/freeasssesmen-finalt-result",
Use the kebab case for actions/methods in urls and the camel case for them in the controllers
You have to pass CSRF token in header during ajax call.
You can get CSRF token in many ways.
One of the simplest way is:
You can add bellow code to your head tag of parent layout or inside any of your template file.
<?php echo $this->Html->meta("csrfToken", $this->request->getAttribute("csrfToken")); ?>
At the time of ajax call you will have to get this csrf token and pass it to the ajax header.
Here is the example:
var token = $("meta[name='csrfToken']").attr("content");
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
url: "path/to/controller/method",
method: "POST",
data: { pram1:val },
success: function(response) {
//console.log(response);
}
});
I hope it may help :)
I'm working on a simple web application in the laravel framework. I have blade, controller and model files and I want to insert the data into the database with the help of ajax. But, I'm not able to insert the data. Below is the code:
Thanks.
<script>
$(document).ready(function(){
$("#button").on("click", function(){
var name=$("#name").val();
var email=$("#email").val();
$.ajax({
url:'insert.php',
method:'POST',
data:{
name:name,
email:email,
},
success:function(data){
alert(data);
}
});
});
});
</script>
There are so many issue with your code:
url:'insert.php', // here you are not working in core php so url is not passed in this way
it will be like:
url:'{{ url("/insert") }}', // This 'insert' will be a route and that will be mapped to a controller function.
And if you are using:
method:'POST',
then you have to set the csrf token like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
or
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
Resolve the above issues and try again.
at least, you have to call in your script.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
Because it is POST request, your csrf_token is required.
I am having difficulty getting an ajax post to work with laravel v5.5.24. Here is what my ajax call looks like:
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/postCustomer?XDEBUG_SESSION_START=19683",
type: 'POST',
data: {_token: CSRF_TOKEN, message:myData, "_method": 'POST'},
dataType: 'JSON',
success: function (data) {
console.log('call to postCustomer successful');
}
});
Here is my route:
Route::post('/postCustomer','AdminUserController#store');
The interesting thing about this problem is that when all the post's are changed to get's (both in the ajax call and in the route) the request arrives and is handled correctly. The debug is triggered, and all is well. However, iof the route and the ajax call is set to POST, the debug is never triggered, and the request does not appear to make it. Naturally this smells like a CRSF issue, but I am including the CRSF token in the header.
if the javascript code inside .blade.php file try this
data: {_token:'{{ csrf_field() }}', message:myData, "_method": 'POST'},
hope its help
Try this,
<meta name="_token" content="{!! csrf_token() !!}"/>
$.ajaxSetup({
headers:
{'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}
});
$.ajax({
url: "/postCustomer?XDEBUG_SESSION_START=19683",
type: 'POST',
data: {message:myData, "_method": 'POST'},
dataType: 'JSON',
success: function (data) {
console.log('call to postCustomer successful');
}});
No need to pass token in ajax data again.
Heartfelt thanks to everyone who responded. A couple of things helpled in fuguring this thing out. First of all, I consolidated the CSRF token mentions,
and confined what I was sending as data to just that - no need to include the CSRF token in the data if you do it in the ajaxSetup. The second thing wasn't visible from my post, but I was encountering a race condition involving the button that triggered the ajax transaction. The button was causing a page reload before ajax could do its thing, and this is why occasionally the thing would appear to work, but mostly not. So the return false is necessary to prevent that - probably not in both places, but certainly after the ajax transaction has been invoked and we are waiting for the callback. The code which works can be found below. I hope it will prevent somebody else from spending a night going mad trying how to figure out what their POST's aren't working. Take away points: handle your CSRF in an ajaxSetup call, and return false from the whole business.
Thanks again to everybody.
-George Pipkin
Afton, Virginia
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
/* the route pointing to the post function */
url: "/postCustomer?XDEBUG_SESSION_START=19159",
type: 'POST',
/* send the csrf-token and the input to the controller */
data: {message:myData},
dataType: 'json',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
$("#success_msg").show();
return false;
}
});
return false;
You should have to pass the _token inside the data object.
data: {_token:'{{ csrf_token() }}',, message:myData, "_method": 'POST'},
I am using Laravel 5.0. I have created a RESTful Controller. Now i wanna use the destroy function via an ajax call.
This is my JS:
$.ajax({
type: 'POST',
url: '/pv/' + data.id,
data: {_method: 'delete' },
success: function(data){
console.log(data);
}
});
And this is my destroy function:
public function destroy($id)
{
$pv = PV::find($id);
$pv->delete();
return true;
}
All i got is a 500 error.
first check your route in laravel
Route::delete('/deleteprocess', 'Controller#destroy');
in javascript
$.ajax({
url: '/deleteprocess',
type: 'POST',
data:{
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
},
success: function(result) {
// Do something with the result
}});
set type : POST,
set token : _token,
set method : _method as DELETE,
That's probabily a "CSRF" Exception. If you are using Ajax Request with jQuery, add this (before your $.ajax):
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
And, in your "html" ..create a new "meta tag" with csrf-token..value:
{{ csrf_token() }}
Read more: http://laravel.com/docs/5.0/routing#csrf-protection
Is it possible to make AJAX PATCH requests to laravel, or am I restricted to POST? Laravel uses PATCH in input hidden fields, however, I am not using form elements—just buttons that should partially update a record when clicked (via an AJAX request).
How would the route look like for this?
Routes file
Route::patch('questions/{id}', 'QuestionController#update')->before('admin');
I am not sure if laravel routes support PATCH.
Controller
public function update($id) {
if (Request::ajax() && Request::isMethod('patch')) {
//partially update record here
}
}
JS
$('div#question_preview <some button selector>').click(function (event) {
$.ajax({
url: 'questions/'+question_id,
type: 'PATCH',
data: {status: 'some status'}
});
});
I am just looking for clarity, thanks!
Yeah, it's possible try
In Your JavaScript
$('#div#question_preview <some button selector>').click(function() {
$.ajax({
url: 'questions/'+question_id,
type: 'PATCH',
data: {status: <SOME VALUE I WANT>, _method: "PATCH"},
success: function(res) {
}
});
});
In Your Route
Route::patch('questions/{id}', 'QuestionController#update')->before('admin');
In your QuestionController Controller's update method
dd(Request::method());
You will see the respond like
string(5) "PATCH"
Read more about Request Information on Laravel doc.
It's possible!
You should need to provide an extra parameter in the form request called as _method with a value PATCH.
JS
$('div#question_preview <some button selector>').click(function (event) {
$.ajax({
url: 'questions/'+question_id,
type: 'PATCH',
data: {status: 'some status',_method: 'PATCH'}
});
});
You can provide a hidden input in the view file with the value PATCH for better readability
HTML
<input type="hidden" name="_method" value="PATCH">
If you are using FormData, you need to send the request as POST. The Laravel application will automatically get it as a PATCH request because you included #method('PATCH'). So your route and method for that will get triggered.
JS with FormData
$('div#question_preview <some button selector>').click(function (event) {
let form_data= new FormData();
form_data.append('status','some status');
form_data.append('_method','PATCH');
$.ajax({
url: 'questions/'+question_id,
type: 'POST',
data: form_data
});
});