Minimum Working Example for ajax POST in Laravel 5.7 - php

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.

Related

Laravel ajax not returning data

I am having trouble retrieving data from Controller using ajax
this is my code
the trigger
<select id="course_select" name="course_select" class="form-control" required autofocus value="{{old('course_select')}}" onchange="getCourse()">
The my ajax section
function getCourse(){
var id=document.getElementById('course_select').value;
alert(id);
$.ajax({
type:'get',
url:'getCourseLessons/'+id,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
and my controller
public function getCourseLessons($id){
$lessons = DB::table('lessons')->select('id','Lesson_name')->where('course_id','=',$id)->get();
return response()->json(array('lessons'=>$lessons));
}
Results console.log(data)
console.log(data)
ReferenceError: data is not defined[Learn More]
My Routes.
Route::get('/getcourselessons/{id}','AdminController#getCourseLessons');
I will appreciate all the help i can get.
First of all please check the route you used in Route/Web.php it should be like this
Route::get('getCourseLessons/{id}','YourController#getCourseLessons');
Check the controller.
public function getCourseLessons($id){
$lessons = \DB::table('lessons')->select('id','Lesson_name')->where('course_id',$id)->get();
return response()->json(array('lessons'=>$lessons));
}
As per your ajax code is ook but you can try this also.
function getCourse(){
var id=$('#course_select').val();
alert(id);
$.ajax({
type:'get',
url:'{{url('getCourseLessons')}}/'+id,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
<select id="course_select" name="course_select" class="form-control" onchange="getCourse()">
<option>hi</option>
<option>hello</option>
</select>
It seems that there is problem in your select as the above code will output
check the following
value="{{old('course_select')}}"
and one more thing I can't see CSRF
Add somewhere in your script
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
1- cheek your route
Route::get('/getCourseLessons/{id}','YourController#getCourseLessons');
2- change your Ajax attributes
function getCourse(){
var id=document.getElementById('course_select').value;
alert(id);
$.ajax({
url: '{{ url("getCourseLessons") }}',
type:'get',
datatype:'json',
data: {
"id": id,
"_token": "{{ csrf_token() }}"
},
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
try this bro change you url or route
function getCourse(){
var id=document.getElementById('course_select').value;
var url = '{{ url('getCourseLessons/')}}/'+id;
alert(id);
$.ajax({
type:'get',
url:url,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
change your route
Route::get('getcourselessons/{id}','AdminController#getCourseLessons');

Laravel 5.6 ajax post without form

I want to use ajax with selectize to load bdd results onchange.
I need to use post because I must send data to my url.
My function looks like this :
select_etages.load(function(callback) {
xhr && xhr.abort();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
data : { bat : value },
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
In my web.php I've got this :
Route::post('/lots/add/etages', ['as' => 'lots.add_post.select', 'uses' => 'Copro\LotController#select2']);
And my controller :
public function select(Request $request)
{
return "test";
}
But when I tried to use it, I've got an "419 unknown status". I can see that it's a post ajax and my data but I've got no error message :
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
If I change to get it's working but not post.
Anyone know why I can't use post ??
Thank for your help.
Maybe you just rewrite the "select2" name end of the route to "select"?
I think you need to remove $.ajaxSetup function in callback function. Code might look like this.
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
select_etages.load(function(callback) {
xhr && xhr.abort();
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
});

Laravel 5.5 delete item with ajax call on click

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
}
}
});

Pass data from ajax to laravel 5.1 Controller in order to save to mysql?

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;
}

getting 404 not found when submitting form using ajax in laravel

I am new with laravel, I am having an issue when posting my data to controller in laravel while using ajax. My view contains a select box which is populated from database when a user select a value from select box i am trying to call ajax which will return details of salary of the user.The issue is it gives me 404 not found error.
The Code for the controller file is shown below.
this function is defined inside a controller
public function getPostSalary()
{
echo "ajax called";
return 'true';
}
The Routes file is
Route::post('company/salary-user', 'CompanyController#getPostSalary');
this is my ajax code from where the controller is being calleD
<script>
$(document).ready(function() {
$('#employee').change(function () {
var values = $('#employee').val();
if (values == '') {
$.pnotify({
title: 'Message',
text: 'Please Select a User.',
type: 'error',
delay: 3000
});
return false;
}
var csrf = $('#csrf').val();
$.ajax({
url: '{!! URL::to("company/salary-user")!!}',
type: "POST",
data: { user_id: values, _token: csrf },
cache: false,
beforeSend: function () {
},
success: function (data) {
console.log(data);
$('#loader').hide();
}
});
});
});
</script>
Can someone help me to figure out what is the issue and what should be done to call my function.
Single quotes is for string so your url is not generating as you expecting. Use like this
url : "{!! URL::to('company/salary-user')!!}",
You can use direct url like
$.ajax({
url:'company/salary-user',
type: "POST",
data: { user_id: values, _token: csrf },
cache: false,
beforeSend: function () {
},
success: function (data) {
console.log(data);
$('#loader').hide();
}
});
replace this line:
{!! URL::to("company/salary-user")!!}
by :
{{ url('/company/salary-user') }}
or
{{ route('/company/salary-user') }}

Categories