<script type="text/javascript">
$(document).ready(function(){
$('#mainmenu').change(function(){
var main_menu_id = $('#mainmenu').val();
$.ajax({
type: 'POST',
url: '/sub',
data: {"main_menu_id": main_menu_id,_token: '{{csrf_token()}}'
success: function (data) {
var submenus = data.submenus;
for(var i=0; i<submenus.length; i++){
$('#submenu').append('<option>'+submenus[i]+'</option>');
}
},
error: function () {
alert('what ever');
}
});
});
</script>
My route
Route::post('/sub','TicketController#sub');
And my controller
public function sub(Request $request)
{
dd($request->all());
return Response([
'submenus' => DB::connection("mysql2")->table('applicationsubmenu')
->join('applicationmenu', 'applicationmenu.Id', '=',
'applicationsubmenu.ApplicationMenuId')
->select('applicationsubmenu.*')
->where('applicationmenu.MainMenuId', '=', $request->main_menu_id)
->get()->toarray(),
]);
}
I am trying to populate an option submenu from depending from user option menu selection.To do that I tried building an ajax but it seems not to work at all.Neither the laravel function seems to be called at all!
Try to setup the ajax requests on the project properly:
In header
<meta name="csrf-token" content="{{ csrf_token() }}" />
In script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
Did you use ajax middleware
Route::post('/sub','TicketController#sub')->middleware('ajax');;
Why are you dumping the $request in your controller?
dd($request->all());
Laravel docs:
The dd function dumps the given variables and ends execution of the script https://laravel.com/docs/5.6/helpers#method-dd
Also when getting values from $request... you are doing this:
->where('applicationmenu.MainMenuId', '=', $request->main_menu_id)
but you should get the values like this:
->where('applicationmenu.MainMenuId', '=', $request->input('main_menu_id')
or if you want an array of request then you should set first:
$input = $request->all();
and then call the value like this:
$input->main_menu_id
you forget to send the token
$.ajax({
type: 'POST',
url: '/sub',
data: {'_token':'{{csrf_token()}}',"main_menu_id": main_menu_id},
success: function (data) {
alert(data);
},
error: function () {
alert('what ever');
}
});
Related
I want a correct ajax URL this one is not working. I am getting this in the console:
GET XHR localhost:8000/Controller/getUnitSellingPrice [HTTP/1.0 404
Not Found 203ms]
create.blade View
C:\Apache24\htdocs\printshopsales\resources\views\sales\create.blade.php
Controller
C:\Apache24\htdocs\printshopsales\app\Http\Controllers\SalesController.php
I have tried what is here:
Ajax call Into MVC Controller- Url Issue
<script>
$(document).ready(function() {
$("#stock_name").on('change', function () {
let element = $(this);
/*var MyAppUrlSettings = {
MyUsefulUrl : '/getUnitSellingPrice'
}*/
$.ajax({
//url: MyAppUrlSettings.MyUsefulUrl,
url: '/Controller/getUnitSellingPrice',
method: 'GET',
data: {
'stock_name' : element.val(),
},
success: function (response) {
$("#unit_selling_price").val(response.data).trigger('change');
console.log(response.data);
},
});
});
});
</script>
You should add a route to web.php file. Like in your SalesController.php
In SalesController file:
public function getUnitSellingPrice()
{
/* your code */
}
In Route file web.php
Route::any('sales-price/getunitsellingprice','SalesController#getUnitSellingPrice');
Update your jquery URL like:
url: '/sales-price/getunitsellingprice',
Thanks
In a Laravel app, I need to update some data in the database after a button is clicked, without reloading the page, thus requiring ajax. No data needs to parsed, only a function in one of the controllers should be invoked, so it's the simplest kind of ajax request.
Based on this example, I set up the following, but nothing happens. No error, no response from the check alert('success!'), nothing.
QUESTION: why does nothing happen? Could it be that the Javascript is not recognized at al?
Head
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Routes - web.php
Route::post('/notificationsSeen','NotificationController#seen');
Controller - NotificationController.php
public function seen() {
$userNotifications = Notification::where('user_id',Auth::id())
->where('status','new')
->update(array('status' => 'seen'));
return;
}
View
<button type="button" id="notifications"></button>
<script>
$("#notifications").on('click', function() {
$.ajax({
type:'POST',
url:'/notificationsSeen',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
alert('success!');
}
});
});
</script>
EDIT: WORKING SOLUTION
Change the contents of the box above labeled "View" to the following:
<button type="button" id="notifications"></button>
<script>
(function ($) {
$(document).ready(function() {
$('#notifications').on('click', function() {
$.ajax({
url: '/notificationsSeen',
type: 'POST',
data: { _token: '{{ csrf_token() }}' },
success:function(){alert('success!');},
error: function (){alert('error');},
});
});
});
}(jQuery));
</script>
In your AJAX request, data is not a string. It is a key value pair. So use
data: { _token: '{{ csrf_token() }}' }
You shouldn't pass the csrf token like this:
data:'_token = <?php echo csrf_token() ?>',
You have to store it in a HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then automatically add the token to all request headers:
$( document ).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#notifications").on('click', function() {
$.ajax({
type:'POST',
url:'/notificationsSeen',
data: {status: 'seen'},
success:function(data){
alert('success!');
}
});
});
});
Controller:
public function seen() {
$userNotifications = Notification::where('user_id',Auth::id())
->where('status','new')
->update(array('status' => request()->input('status')));
return ['success' => true];
}
I am new to Laravel and am using Laravel 5.3. I want to make a text field where it will automatically suggest some data and when I select a data it will add it to an array. I want to send that array to a controller for further use. For this the
view file is as follows:
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
var members = {!! json_encode($member) !!};
console.log(members);
var arr = [];
$("#tags").autocomplete({
source: members,
select: function (event, ui) {
arr.push(ui);
console.log(arr);
}
});
$("#submit").click(function(event){
$.ajax({
type: "POST",
url: '/storeresearch',
data: {selectedMembers: arr},
success: function( msg ) {
console.log(msg);
}
});
});
});
</script>
</head>
<body>
<form id="hu" action="/storeresearch" method="POST">
{!! csrf_field() !!}
<label>Research Author</label>
<input type="text" id="tags" name="researchsupervisor_1" value="">
<input type="submit" name="submit" id="submit" class="btn btn-primary" value="Add">
</form>
</body>
My Controller file is as follows:
public function store(Request $request){
if($request->ajax())
{
$mem = $request->all();
return response()->json($mem,200) ;
}
else{
return "not found";
}
And web.php is as followings:
Route::post('/storeresearch','ResearchController#store');
But it seems that there is no ajax call happening. In the controller it always enters the else section. What is the problem can anyone help?
Your code mostly looks good. But you are missing to send a csrf token with AJAX call as you are using POST request.
You can send csrf token with AJAX call in this way:
<meta name="csrf-token" content="{{ csrf_token() }}">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
More info: https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token
When you hit the button, does it really fires an AJAX call? Please check that on network tab of browser.
I solved this problem by doing following
$.ajax({
type:'POST',
url:'your url',
data:{_token: "{{ csrf_token() }}"
},
success: function( msg ) {
}
});
Try some thing like this:
$.ajax({
url : '/login',
method : 'post',
data : {
login_username : userName,
password : password
},
headers:
{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success : function(response){
}
});
Route:
Route::post('/login',[
'uses' => 'AdminServiceController#login'
]);
Controller method:
public function login()
{
$userName = INPUT::get('login_username');
$password = INPUT::get('password');
// your logic
}
What's your namespace declaration for Request ?
If it is use Illuminate\Http\Request; try use Request;
Before marking it as duplicated, i tried the other solutions found on the web, including SO, and none of them solved my issue.
I'm using x-editable plugin to store a new record using a store route.
When the form is submitted, i get a 500 with TokenMismatchException error.
I know about setting the csrf token thing, but i tried it in several ways, and nothing is working.
That's my javascript code:
$.fn.editable.defaults.params = function (params) {
params._token = window.Laravel.csrfToken;
return params;
};
$('.editable').each(function () {
$(this).editable();
});
The html
<head>
[...]
<meta name="csrf-token" content="{{ csrf_token() }}">
[...]
<script>
window.Laravel = <?php
echo json_encode([
'csrfToken' => csrf_token(),
]);
?>
</script>
[...]
</head>
<button id="note-asl-text"
data-type="textarea"
data-placeholder="Aggiungi Nota"
data-url="{{route('ricettanota.store')}}"
data-title="Inserisci una nuova nota"
data-highlight="false"
data-mode="inline"
data-send="always"
data-showbuttons="bottom"
class="editable"
>Aggiungi nota</button>
The Route
Route::resource('ricettanota', 'RicettaNotaController');
I already tried all possible combinations of the following:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': window.Laravel.csrfToken
}
});
$('.editable').each(function () {
$(this).editable({
ajaxOptions: {contentType: 'application/json', dataType: 'json'},
params: function (params) {
params._token = window.Laravel.csrfToken;
return JSON.stringify(params);
}
});
});
note
$('meta[name="csrf-token"]').attr('content') and window.Laravel.csrfToken are the same
update
I found out that placing Route::resource('ricettanota', 'RicettaNotaController'); into the api routes file(api.php) causes the issue, while placing the routes into the web routes file (web.php) and using the code above works.
Why using the API i get token mismatch, is still a mystery.
Not sure if this is what you are looking for, but maybe you should not struggling in sending custom header with x-editable plugin, but sending custom parameters.
The following code works for me.
$(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.node').editable(
{
params: function(params) {
var data = {};
data['_csrf_token'] = $(this).data("csrf");
return data;
},
}
);
});
Set csrf in your a-tag or somewhere else you like.
<a href="#" ... data-csrf="xxxxxxx" /a>
Hope this helps.
try this in your ajaxSetup
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
I also faced same issue in Laravel 5.8. Following code worked for me.
$.fn.editable.defaults.ajaxOptions = {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
};
this is use code
$.ajax({
type: 'POST',
url: url,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType:'html',
data:data,
success:function(data){
}});
this Follow link
https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token
I built an ajax post which sends each slider value (I am using jquery ui slider) to my controller.
The Ajax code:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'post',
contentType: "application/json",
url: "{{ Route('editProductPost', $product->id) }}",
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
data: JSON.stringify({
value: getSliderVal,
productId : getPrId
}),
datatype: 'json',
success: function(response) {
// get response
console.log(response.sliderValue)
}
});
And in my Controller I am doing this:
public function editProductPost(Request $request)
{
Log::info($request->get('value'));
return view('product.edit', [
'sliderValue' => $request->get('value')
]);
}
This returns me the correct slider value,
Log::info($request->get('value'));
But I get this error message in my browser console:
POST http://localhost/myApp/public/product/edit/98 500 (Internal
Server Error)
Later on I want to call this sliderValue inside of a php loop in my view.
Edit
I do have a csrf token:
<meta name="csrf-token" content="{{ csrf_token() }}">
Edit
I have done this:
$sliderValue = $request->get('value');
$route = 'updateProduct';
return view('product.edit', compact(['sliderValue', 'route']))->render();
The console print me undefined and if I do this {{ sliderValue }} I get an error that sliderValue is not defined
Little change of your code:
public function editProductPost(Request $request)
{
Log::info($request->get('value'));
$sliderValue = $request->get('value';
return view('product.edit', compact('sliderValue'))->render();
}
The problem here is that you're returning a view in your controller. If your view used {{ $sliderValue }} inside it, it should work. But there's no way for javascript to get the sliderValue variable.
If you wanted the sliderValue as is, you can return this array
return [
'view' => view('product.edit', compact(['sliderValue', 'route']))->render(),
'sliderValue' => $sliderValue
];
That way you're sending to javascript an object with 2 properties, one should contain the view and the second one will only contain the value.