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");
}
});
Related
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')
}
});
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;
}
Trying to get AJAX image upload working on Laravel 4 but having issues.
This is what I have:
The form:
{{ Form::open(array('class' => 'update-insertimage-form', "files" => true,)) }}
{{ Form::file('image', array('class' => 'update-insertimage-btn', 'name' => 'update-insertimage-btn')) }}
{{ Form::close() }}
And the PHP:
$createImage = Image::make(Input::file('update-insertimage-btn'))->orientate();
$createImage->resize(600, null, function ($constraint) {
$constraint->aspectRatio();
});
$createImage->save("user_uploads/cover_images/TEST.jpeg");
jQuery:
$('.update-insertimage-form').submit(function() {
$(".submit-newupdate-btn").addClass('disabled');
var rootAsset = $('.rootAsset').html();
$.ajax({
url: rootAsset+'saveUploadedImage',
type: 'post',
cache: false,
dataType: 'json',
data: $('.update-insertimage-form').serialize(),
beforeSend: function() {
},
success: function(data) {
if(data.errors) {
$('.modal-body').append('<div class="alert alert-danger centre-text modal-error-message" role="alert"><strong>Error!</strong> '+ data.errors +'</div>');
} else if (data.success) {
$(".form-control-addupdate").append(data.name);
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
I use this same exact code else where which works fine but not with AJAX.
The error is this:
{"error":{"type":"Intervention\\Image\\Exception\\NotReadableException","message":"Image source not readable","file":"\/Applications\/MAMP\/htdocs\/buildsanctuary\/vendor\/intervention\/image\/src\/Intervention\/Image\/AbstractDecoder.php","line":257}}
Any help?
Note, tried using formData and changed the jQuery to:
$('.update-insertimage-form').submit(function() {
$(".submit-newupdate-btn").addClass('disabled');
var rootAsset = $('.rootAsset').html();
var formData = new FormData();
formData.append('update-insertimage-btn[]', $('.update-insertimage-btn')[0].files[0], $('.update-insertimage-btn')[0].files[0].name);
$.ajax({
url: rootAsset+'saveUploadedImage',
type: 'post',
cache: false,
dataType: 'json',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data) {
if(data.errors) {
$('.modal-body').append('<div class="alert alert-danger centre-text modal-error-message" role="alert"><strong>Error!</strong> '+ data.errors +'</div>');
} else if (data.success) {
$(".form-control-addupdate").append(data.name);
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
But that is throwing the error:
{"error":{"type":"ErrorException","message":"preg_match() expects parameter 2 to be string, array given","file":"\/Applications\/MAMP\/htdocs\/buildsanctuary\/vendor\/intervention\/image\/src\/Intervention\/Image\/AbstractDecoder.php","line":208}}
Thanks for any help.
Try passing the form to the FromData contructor instead of trying to manually add the file to it.
var formData = new FormData($('.update-insertimage-form')[0]);