Unable to create Delete action in Laravel.
I am getting Not Found or Token mismatch errors all the time.
My controller:
class TranslationController extends Controller
{
public function destroy($id)
{
//$id = 1;
/*$translation = Translation::find($id);
$translation->delete();*/
}
....
}
Ajax call:
/* Delete given translation */
var url = "translation";
var id = 1;
$.ajax({
method: 'DELETE',
url: url + '/' + id,
// data: {'id': id, '_token': token},
success: function() {
}
});
This would give: TokenMismatchException in VerifyCsrfToken.php line 53:
If I try:
url: url + '/' + id,
data: {'_token': token}, // token is equal to csrf_token
I have: NotFoundHttpException in Controller.php line 269:
Routes:
Route::controller('translation', 'TranslationController');
Otherwise I am using Laravel 5 default Middleware, I have not changed anything related to csrf.
NotFoundHttpException means that either the route for the particular request with the particular HTTP verb has not been specified, or the action (i.e. the controller method) that is mapped to the verb for the route is wrongly implemented.
Since you've mentioned in the post that the TranslationController is defined as an implicit controller,
Route::controller('translation', 'TranslationController');
and from the controller code you've posted, it's quite obvious that you have not defined the verb for the destroy method in your controller TranslationController.
If you do a php artisan route:list in your projects root directory with a terminal/command line interface, you'll see the listing of the registered HTTP verbs, mapping to the corresponding URIs, and the actions.
To define a particular method in an implicit controller, the verb (GET, PUT, POST, DELETE) should precede the actual function name.
Make sure that the destroy method looks like the following in your controller:
public function deleteDestroy($id){
//delete logic for the resource
}
Note:
Laravel by default requires that the csrf token is passed along with a particular RESTful request, so do not remove data: {'_token': token} from your AJAX call.
Update
Forgot to mention that the url in your AJAX call should also be changed to the following in order to work, because this is how Laravel's implicit controllers define the route for a DELETE request:
var url = "translation/destroy";
Here is documentation about method spoofing. You need to send a POST ajax request with _method field set to DELETE
$.ajax({
method: 'POST',
url: url + '/' + id,
data: {
'id': id,
'_token': token,
'_method' : 'DELETE'
},
success: function() {
}
});
You could try defining your route that way
Route::delete('translation/{id}',array('uses' => 'TranslationController#destroy'));
In this case your AJAX won't change. But if you want keep this Route
Route::controller('translation', 'TranslationController');
You must change your Ajax request to:
/* Delete given translation */
var url = "translation/destroy"; // You must specify the action
var id = 1;
$.ajax({
method: 'DELETE',
url: url + '/' + id,
data: {'_token': token},
success: function() {
}
});
You should to send token via header. ( especially in 5.2 version )
$.ajax({
type: "post",
url: "/routeurl",
headers: { 'X-CSRF-Token': "{!! csrf_field() !!}" },
success: function(msg){
// msg
}
});
Related
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
I tried to access an id from a URL "myfolder/mycontroller/mymethode/123" which I call into an AJAXcall.
I cannot access them, in "mycontroller" under the "mymethode". I tried to output $_GET, $_POST, $this->input->get(), $this->input->post(), but all array are empty.
In the Controller/mycontroller I have this
public function mymethode($listid=false)
{
echo "listid: $listid";
print_r($_GET);
print_r($_POST);
print_r($this->input->get());
print_r($this->input->post());
}
The Ajax call is this and is ok with Status 200.
$.ajax({
url: http://mydomein.com/myfolder/mycontroller/mymethode/123,
type: "POST",
method: 'post',
data: form + "&" + additional_data + csrfName + "=" + csrfHash,
dataType: 'json',
cache: false,
success: function(res){...
If I tried to open the URL directly, I have the same problem.
What can the reason for it be?
Use this (if this is not HMVC)
in route.php
# You may need first route since you're accepting null on method
$route['mymethode] = 'mycontroller/mymethode';
$route['mymethode/(:num)'] = 'mycontroller/mymethode/$1';
In AJAX
url: http://mydomein.com/mymethode/123,
Make sure your sites run without index.php
In controller
public function mymethode($listid=null)
I have strange problem because previously in my app this code was working but now isn't.
I take data from Laravel api via url address:
/api/customer/{id}/products
to select2 script
$('.js-data-example-ajax').select2({
ajax: {
url: '/api/customer/{id}/products',
dataType: 'json',
data: function (params) {
var query = {
q: params.term,
}
return query;
}
but Laravel make url address i that way:
api/customer/%7Bid%7D/products
so, I have %7Bid%7D instead of {id} and I'm looking for solution in google without success.
The character "7B" is { converter to asci, before the ajax request create a var call "url"
i call the route with his name, for give it the name just attach
->name('your_name') in the route file
and after in url variable i use the route name instead the full url
url = '{{ route("your_route_name", ":id") }}';
then replace the id placeholder with the id of select
url = url.replace(':id', id);
finally in ajax request
ajax: {
url: url,
//the rest of ajax request
}
I am working on a Post Ajax request Function. Where the function takes some data and send it through an enabled CSRF_token post Request to a controller and then after evaluations on controller a message sent back to the view. but it seems i miss a small thing in my code.
My controller
public function PostMessage(Request $request){
$message=$request->someData; //getting data from request variable
return response()->json($message);
}
My jquery Ajax request function
$('.SendAjaxPostRequest').on('click', function() {
var value=$('.MessageHolder').val();
$.ajax({
method: 'POST',
url:'{{route('SVCate')}}', //SVCate is my route to the controller
dataType: 'JSON',
data: {_token:token,'someData':value,}
// #token gets it's value from a local view javaScrip Variable
})
.done(function (data) {
console.log(data);
})
});
My route function
Route::post('SendMessage','NessageController#PostMessage')->name('SVCate');
Check your apostrophes in the url. You are ending the string and beginning the string around SVCate change it to url:"{{route('SVCate')}}" to make sure that SVCate stays a string and does not break your string.
I'm trying to set up a token on ajax post but is not getting recognized by the controllers method. The javascrip looks as it follows
jQuery(document).ready(function() {
jQuery('#source').change(function() {
jQuery('#fileupload').addClass('fileupload-processing');
var data = jQuery('#source option:selected').val();
jQuery.post('index.php', {
'option': 'com_tieraerzte',
'task': 'parser.importColumns',
'tmpl': 'component',
'token':'<?php echo JUtility::getToken()?>',
'app': data,
'dataType': 'html',
}, function(result) {
jQuery('td.add_column').html(result);
jQuery('button#parse.btn').show();
//edit the result here
return;
});
});
the token is getting generated and posted
in the controller I check the existance of toke but throws me Invalid Token
controller check toke
JRequest::checkToken('request') or jexit( 'Invalid Token' );
You're almost there, it's just a little mixed up. The Joomla! Form Token is generated and submitted as a input name with a value of 1. So, the token looks like this in your form:
<input type="hidden" name="1LKJFO39UKSDJF1LO8UFANL34R" value="1" />
With that in mind, when submitting via AJAX, you need to set the parameter name to your token name, with a value of 1. I accomplish something similar by just using the jQuery('selector').serialize() method:
Joomla.autoSave = function () {
jQuery.ajax({
url: "index.php?option=com_gazebos&task=product.apply&tmpl=component",
type: "POST",
data: jQuery("#product-form").serialize(),
success: function (data) {
console.log("autosaved");
}
});
};
Doing this pulls in all the form data (including the form token from the hidden input) and formats it as a query string, then sends it with the request. However, it seems to me that you might not want to do that and you are really only wanting to submit a single bit of data, not the whole form. So, let's rework your code a little bit to get the desired effect:
/**
* First, let's alias $ to jQuery inside this block,
* then setup a var to hold our select list dom object.
*/
jQuery(document).ready(function ($) {
var sourceSelect = $('#source');
sourceSelect.change(function () {
$('#fileupload').addClass('fileupload-processing');
/**
* Use the token as a parameter name and 1 as the value,
* and move the dataType param to after the success method.
*/
$.post('index.php',
{
'option': 'com_tieraerzte',
'task': 'parser.importColumns',
'tmpl': 'component',
'app': sourceSelect.val(),
'<?php echo JSession::getFormToken()?>': 1
},
function(result) {
$('td.add_column').html(result);
$('button#parse.btn').show();
//edit the result here
return;
},
'html'
);
});
});
Finally, this code is assuming you have this js code either in your view.html.php or in your views/parser/tmpl/default.php. If you have it in a separate .js file, then your php code won't execute and give you the token.
In your ajax call method use url as :
$.ajax({
url: '/index.php?option=com_itemreview&task=item.userReviewVote&<?php echo JSession::getFormToken(); ?>=1',
type: 'post',
data: {'data': submitvalue},
dataType: 'json',
success: function(response) {
}
});
for more information see here:
http://joomlabuzz.com/blog/27-preventing-cross-site-request-forgery-in-joomla
https://docs.joomla.org/How_to_add_CSRF_anti-spoofing_to_forms