In my laravel project i have various checkboxes on my page.On checking of each checkbox i have to send coressponding Id's to laravel controller.But its triggering an error.
Following is the code of ajax.
$('.searchType').click(function() {
alert($(this).attr('id'));
if(this.checked){
$.ajax({
type: "POST",
url: '{{ route('mapService') }}',
data: $(this).attr('id'),
success: function(data) {
alert('it worked');
alert(data);
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
Following is the code of checkbox
<label class="control-label">Service</label> <br>
#foreach($services as $service)
<input type="checkbox" class="searchType" name="service[]" id="{!! $service->serviceID !!}" value="{!! $service->serviceID !!}">{!! $service->serviceName !!}<br>
#endforeach
As per ajax code i have created a controller named mapService and following is the code
public function mapService(Request $request)
{
$id = $request->input('id');
echo $id;
}
$id or corresponding is not getting in controller, It is generating following error
http://127.0.0.1/lifeloveandotherthings/public/api/mapService 405 (Method Not Allowed)
What is the problem here?Please help
Add Csrf token and write ajax data like closing breket
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.searchType').click(function() {
var id = $(this).attr('id');
$.ajax({
type: "post",
url: '{{ route('mapService') }}',
data: {
id: id,
},
success: function(data) {
alert('it worked');
alert(data);
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
},
});
});
Check is your route defined with POST and in your js part put something like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Related
I am struggling with this code. I am unable to send a response with ajax.
Ajax script is here.
$(document).ready(function () {
$('#selectSize').change(function () {
var idSize = $(this).val();
$.ajax({
type: "get",
dataType: 'json',
url: 'getproductprice',
data: {
idSize: idSize
},
success: function (response) {
console.log("working");
},
error: function () {
console.log("error");
}
});
});
});
Here is the Blade markup
<select name="size" id="selectSize" style="width:150px;">
<option value="">Select Size</option>
#foreach($productDetails->attributes as $size)
<option value="{{$productDetails->id}}-{{$size->size}}">{{$size->size}}</option>
#endforeach
</select>
And here is the controller code
public function getProductPrice(Request $request)
{
$data = $request->all();
$proArr = explode("-", $data['idsize']);
$proAttr = ProductsAttribute::where(['product_id' => $proArr[0], 'size' => $proArr[1]])->first();
$getCurrencyRates = Product::getCurrencyRates($proAttr->price);
echo $proAttr->price . "-" . $getCurrencyRates['USD_Rate'] . "-" . $getCurrencyRates['GBP_Rate'] . "-" . $getCurrencyRates['EUR_Rate'];
echo "#";
echo $proAttr->stock;
}
I do not know, What I am doing wrong .when I select option value.
error will come like.
"Trying to get property 'image' of non-object (View:
C:\xampp\htdocs\wrost\resources\views\shop\product-details.blade.php)"
Your ajax should be -
$.ajax({
url: 'getproductprice',
type: 'POST',
data: {idSize: idSize},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log(err);
alert("Something Went Wrong, Please check again");
}
});
First make sure you add meta tag for csrf in your head
<meta name="csrf-token" content="{{ csrf_token() }}">
At last you need to add header object in your ajax object
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
it will be like this
$.ajax({
type: "get",
dataType : 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url:'getproductprice',
data: {idSize: idSize},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
I am trying to concatenate a variable to my url link in ajax. The variable $news is the one that handles the notification id.
$(document).on("click", "#viewList", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var $news = $(this).prop("value");
$.ajax({
type: "get",
url : '{{url("admin/recipients/", $news)}}', //returning an error undefined variable news
data: {newsID : $news},
success: function(store) {
console.log(store);
$('#rec').text(store);
},
error: function() {
$('.alert').html('Error occured. Please try again.');
}
});
});
In my web.php, it's route is inside a route group.
Route::group(['middleware' => 'auth:admin'], function () {
Route::prefix('admin')->group(function() {
Route::get('/recipients/{news}', 'Admin\NewsController#recipients');
});
});
So how can I make this work? By the way, my ajax is inside a blade.php file.
$news doesnt exist to blade because it executes on the time server is rendering the page. So your javascript hasn't been executed yet. To make this work, change you js code to this:
$(document).on("click", "#viewList", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var news = $(this).prop("value");
$.ajax({
type: "get",
url : '{{url("admin/recipients")}}' + '/' + news,
data: {newsID : news},
success: function(store) {
console.log(store);
$('#rec').text(store);
},
error: function() {
$('.alert').html('Error occured. Please try again.');
}
});
});
Can someone please show a Laravel 5.7 post ajax example with a full-working minimum example in a blade template? I know there are some resources in the web, but I miss a concise, straight-forward minimum example.
You can do something like this,
web.php
Route::post('/admin/order/{id}', 'OrderController#edit')->name('admin.order.edit');
blade.php
$(document).on('click', '.delete-button', function (e) {
e.preventDefault();
var orderId = 1
$.ajax({
type: 'post',
url: '/admin/order/' + orderId,
data: {
'_token': $('input[name=_token]').val(),
'data_one': 'dataone',
},
success: function () {
toastr.success('Order Has Been Deleted Successfully.');
},
error: function(XMLHttpRequest) {
toastr.error('Something Went Wrong !');
}
});
});
$.ajax({
url: 'http://some.working/url',
type: "POST",
data: $('#formContainer').serialize(),
success: function (response) {
console.log('Success', response);
},
error: function (response) {
console.log('Error', response);
}
});
The data can be produced in many ways for example
1. Using serialize() method as shown in the above example.
2. Using FormData():
for example
var data = new FormData($('#formContainer'));
In both of the above example, one thing compulsory is that your form
must contain csrf field. which can be provided using any of the
following methods:
<input type="hidden" name="_token" value="{{ csrf_token() }}" >
or
{{ csrf_field() }}
or even more simply by just using
#csrf
in some where in your form.
In case you are not using any form, you can create the data object by
yourself like this
var data = {
_token: '{{ csrf_token() }}',
data1: 'Value1',
data2: 'Value2',
data3: 'Value2'
}
Define a Web Route
Route::get('currencies/fiat/changeStatus','FiatCurrencyController#changeStatus')->name("currencies.fiat.chanageStatus");
Call this function on click onclick="changeStatus(1,0)"
function changeStatus(id,status){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
/* the route pointing to the post function */
url: '/currencies/fiat/changeStatus',
type: 'GET',
/* send the csrf-token and the input to the controller */
data: {_token: CSRF_TOKEN,cid:id,status:status},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
console.log(data);
}
});
}
That's it all Done.
$(document).ready(function(){
/* In laravel you have to pass this CSRF in meta for ajax request */
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
/* change in website layout base on click */
$('#user_view').on('click',function (e){
e.preventDefault();
$('.loading_screen').show();
var val = $(this).data('id');
$.ajax({
url: base_path + 'user/changeview/'+val,
type: "POST",
success: function (data) {
var obj = jQuery.parseJSON(data);
if (obj.SUCC_FLAG == 0){
window.location.href = site_url;}
else{
/* for console error message. */
console.log(obj.MSG);}
$('.loading_screen').hide();
},
error: function () {
alert("server error");
}
});
});
});
Hey it's a working code and i hope this will works for you.
I am trying to delete a model item via an ajax call when you click on an icon.
Without an ajax call and just with a form everything works great.
This exception is thrown when I look in my network tab of my chrome dev tools
"Symfony\Component\HttpKernel\Exception\HttpException"
This is my icon:
<i class="fa fa-trash-o deletebtn" aria-hidden="true" data-pointid="<?php echo $damagePoint->id ?>"></i>
My ajax call:
$(".deletebtn").click(function(ev){
let pointid = $(this).attr("data-pointid");
$.ajax({
url: '/pointdelete/' + pointid,
type: 'delete',
success: function (response) {
}
});
})
My route:
Route::delete('pointdelete/{id}', 'DamagePointController#delete');
My controller method
public function delete($id)
{
$todo = DamagePoint::findOrFail($id);
$todo->delete();
return back();
}
if you are using delete route is like similar to post.Here is the sample code.you can change as per your need
$(".deletebtn").click(function(ev){
let pointid = $(this).attr("data-pointid");
$.ajax({
type: 'DELETE',
url: '/pointdelete',
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: {id:pointid,"_token": "{{ csrf_token() }}"},
success: function (data) {
alert('success');
},
error: function (data) {
alert(data);
}
});
});
Route
Route::delete('pointdelete','DamagePointController#delete');
controller
public function delete(Request $request){
if(isset($request->id)){
$todo = DamagePoint::findOrFail($request->id);
$todo->delete();
return 'success';
}
}
Please check below code:
Route::delete('pointdelete',['as' => 'point.delete','uses' => 'DamagePointController#delete']);
<button class="fa fa-trash-o deletebtn" aria-hidden="true" onclick="delete({{ $damagePoint->id }}"></button>
<script type="text/javascript">
function delete(id){
var _token = "{{ csrf_token() }}";
$.ajax({
url : "{{URL::route('your-delete-route')}}",
type : 'delete',
dataType : 'json',
data : {
'id': id,
'_token':_token
},
beforeSend : function() {
},
complete : function() {
},
success : function(resp)
{
console.log(resp);
}
});
}
</script>
public function delete(Request $request,$id)
{
DamagePoint::destroy($id);
return response()->json(['success' => true],200);
}
Try this kind of ajax call
$(".deletebtn").click(function(ev){
let pointid = $(this).attr("data-pointid");
$.ajax({
url: '/pointdelete/' + pointid,
data : {'_method':'delete','_token':'your csrf token'},
//type: 'delete',
type:'post',
success: function (response) {
}
});
})
Also, verify that what URL is called in request header information in your chrome developer tools.
you just don't need a form try to put your token as {{ csrf_token() }} in ajax.
Recently I got the same error and none of above solutions worked for me in laravel 5.7
I had code something like -
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type:'POST',
async: false,
url:validUrl,
data:{id:1},
success:function(response){
if(response && response.error) {
//show error
} else {
// success
}
}
});
Then I had to set csrf token first using setup method - changed code is something like -
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'POST',
async: false,
url:validUrl,
data:{id:1},
success:function(response){
if(response && response.error) {
//show error
} else {
// success
}
}
});
I need to pass data from jquery (version 1.9.1) to my Controller (Laravel 5.1) and then save it to mysql.
How to do that and pass the variable slot? It didn't work so far. For any further details, please asked me.
jquery:
$(".tic").click(function(){
var slot = $(this).attr('id');
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { _token: {{ csrf_token() }}, moves: slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
Controller:
public function addhistory(Request $request)
{
$history = new History();
$history->game_id = Game::orderBy('id', 'desc')->first()->id;
$history->moves = $request->moves;
$history->save();
return redirect()->back();
}
Routes:
Route::post('/addhistory', 'GameController#addhistory');
Errors in console:
(index):198 Uncaught ReferenceError: HAmcYRScL9puItnUGbd2kHx.... is not defined
at HTMLAnchorElement.<anonymous> ((index):198)
at HTMLAnchorElement.dispatch (191.js:3)
at HTMLAnchorElement.v.handle (191.js:3)
191.js file is the jquery version of 1.9.1
You can use this code, it may works
$(".tick").click(function (event) {
event.preventDefault();
$('.loading').show();
var form = $(this);
var data = new FormData($(this)[0]);
var url = form.attr("action");
$.ajax({
type: "POST",
url: url,
data: data,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert("Data has been saved successfully.");
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
});
Try this code-
$(".tic").click(function(){
var slot = $(this).attr('id');
var token= $("input[name='_token']").val();
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { '_token': token, 'moves': slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
And in your controller you don't need return redirect because the request is asynchronous. So I am returning true. Make sure you include History model at the top of your controller
public function addhistory(Request $request)
{
$game_id=Game::orderBy('id', 'desc')->first()->id;
History::create([
'game_id'=>$game_id,
'moves'=>$request->moves
]);
return true;
}