Getting error in AJAX response in Laravel Blade Template - php

I am getting error in my AJAX response.
I am trying to view a specific patient details while clicking 'view' button from 'All Patient' table using AJAX request.
But getting error in response like below image
But I returned an 'id' from my controller.
AJAX
$(".view_prescription").click(function(){
var id = $(this).val();
var token = $('input[name=_token]').val();
$.ajax({
type:'GET',
url:'/view-prescription',
data:{
_token : "{{ csrf_token() }}",
id: id
},
success:function(data) {
alert(data);
}
});
});
Route
Route::get('/view-prescription','PrescriptionController#view_prescription');
Controller
public function view_prescription(Request $request)
{
$id = $request->id;
return $id;
}
I understand that it's a slight mistake. But I can't figure that. Anybody help please

I have solved the issue.
just change url from '/view-prescription' to "{{url('/view-prescription')}}" and comment our 'token'.
$(".view_prescription").click(function(){
var id = $(this).val();
//var token = $('input[name=_token]').val();
$.ajax({
type:'GET',
url:"{{url('/view-prescription')}}",
data:{
_token : "{{ csrf_token() }}",
id: id
},
success:function(data) {
alert(data);
}
});
});

Related

Getting 404 Not Found in Laravel AJAX Request

In my Laravel Projects, I want to pass data from blade to my controller using Ajax.
But I am getting error
404 | Not Found
ajax
var pi_id = $(this).attr('href');
$.ajax({
url: "{{ url('purchase-invoice-detail') }}",
type: "get",
data: {
'id': pi_id
},
success: function(response){ // What to do if we succeed
alert('ok');
},
error: function(response){
alert('Error'+response);
}
});
route
Route::get('purchase-invoice-detail/{id}', 'PurchaseController#purchase_invoice_detail')->middleware('auth');
controller
public function purchase_invoice_detail($id)
{
return 1;
}
Can't find the problem.
Anybody Help Please ?
Please try this code
"{{ url('purchase-invoice-detail') }}" + '/' + pi_id

ajax to delete a record from database does not fire redirect in laravel

I am deleting a record from my database using an ajax request. This works and deletes the record however then it does not redirect the user with the success message.
I am using a sweetalert modal to display the confirm delete button and when you click yes, the modal goes away and the record has been deleted but the page does not redirect and the record does not disappear until you refresh the page.
This seems to be ignored -
return redirect()->route('users.index')->with('success', 'User deleted!');
AJAX -
<script>
$(document).ready(function() {
$(".swal2-confirm").click(function(){
var id = '{{ request()->delete_id }}';
var route = '{{ request()->route }}';
$.ajax({
type:'post',
url:'/admin/' + route + '/' + id,
dataType: 'json',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {'_method':'delete', "_token": "{{ csrf_token() }}", id:id},
});
});
});
</script>
Controller -
public function destroy($id)
{
//Delete user from database
User::find($id)->delete();
return redirect()->route('users.index')->with('success', 'User deleted!');
}
I have figured it out by showing the alert and then reloading the page within my ajax -
<script>
$(document).ready(function () {
$(".swal2-confirm").click(function () {
var id = '{{ $delete_id }}';
$.ajax({
type: 'post',
url: '/admin/users' + '/' + id,
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: { '_method': 'delete', "_token": "{{ csrf_token() }}", id: id },
complete: function () {
swal.fire({
type: 'success',
title: 'User Deleted!',
showConfirmButton: false,
timer: 2500
});
setTimeout(function () { window.location.replace('/admin/users') }, 2500);
}
});
});
});
</script>

Minimum Working Example for ajax POST in Laravel 5.7

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.

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

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

Categories