AJAX failed to load server with a status of 500 - php

I have taken an example from the internet of working laravel with ajax. But it gives me the 500 internal server error:
jquery.min.js:4 GET 127.0.0.1:8000/search?search=p 500 (Internal Server Error) send # jquery.min.js:4 ajax # jquery.min.js:4 (anonymous) # (index):39 dispatch # jquery.min.js:3 r.handle # jquery.min.js:3
This is the code for controller called SearchController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function index()
{
return view('search.search');
}
public function search(Request $request)
{
if($request->ajax())
{
$output="";
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
if($products)
{
foreach ($products as $key => $product) {
$output.='<tr>'.
'<td>'.$product->id.'</td>'.
'<td>'.$product->title.'</td>'.
'<td>'.$product->description.'</td>'.
'<td>'.$product->price.'</td>'.
'</tr>';
}
return Response($output);
}
}
}
}
Code in web.php
Route::get('/','SearchController#index');
Route::get('/search','SearchController#search');
Code of blade file
<!DOCTYPE html>
<html>
<head>
<meta id="token" name="_token" content="{{ csrf_token() }}">
<title>Live Search</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Products info </h3>
</div>
<div class="panel-body">
<div class="form-group">
<input type="text" class="form-controller" id="search" name="search"></input>
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
});
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
</body>
</html>
It should display the record when the key is pressed but it gives error 500 internal server error
Screenshot with GET method
AJAX ERROR WITH GET
Screenshot with POST method
AJAX ERROR WITH POST

Try this
<script type="text/javascript">
$('#search').on('keyup',function(){
value=$(this).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url : '{{ url('search') }}',
method : 'POST',
data:{'search': value},
success:function(response){
console.log(response.data)
}
});
})
</script>
your route
Route::post('/search','SearchController#search');
and in your controller, verify
public function search(Request $request)
{
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
return response()->json(['data' => $products]);
}

The problem is, There is no DB imported.
So Just write
use DB;
in the controller

Related

Am not able to insert data into database using ajax laravel

I am trying to take amount from the html tags and store the amount into database but the about here
ajax code is not working and data is not stored in the database. And how to know if ajax code is redirected it's control to the laravel controller
#include('layouts.students.header')
<meta name="csrf-token" content="{{csrf_token()}}">
<body>
<div class="col">
<p class="text-right" style="font-size: 18px;">
<i class="fa fa-rupee"></i><strong
class="amount">299</strong>
</p>
</div>
<div class="form-group text-right">
<button class="btn btn-warning btn-block btn-lg
buy_now">Proceed</button>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('button').click(function(event){
e.preventDefault();
var amount = $('.amount').html();
$.ajax({
url : '{{route('razorpay')}}',
method : 'POST',
dataType : 'jason',
data : {amount :amount * 100},
success : function (Response) {
console.log(Response);
}
});
});
});
</script>
</body>
</html>
controller :
public function dopayment(Request $request)
{
$data = $request->all();
$result = Payment::insert($data);
echo "inserted";
}
In ajax method can you use dataType : 'json', instead of jason

Error: "Request aborted" axios laravel vuejs

i want to add a function using laravel and vuejs and axios but it gives me error Error: "Request aborted".if I delete form validation system and checkForm function it all works well,really i don't know what error sign what,what kind of error.
fonction.blade.php
<section id="main-content">
<section class="wrapper">
<div class="container" id="app">
<div id="login-page">
<div class="form-login">
<div class="login-wrap">
<form #submit="checkForm">
<div v-if="errors.length">
<div class="alert alert-danger" role="alert">
<ul>
<li v-for="error in errors">#{{ error }}</li>
</ul>
</div>
</div>
<input type="text" class="form-control" id="fonction" name="fonction" v-model="fonction.fonction" placeholder="fonction">
<br>
<button class="btn btn-theme" #click="addFonction">AJOUTER FONCTION</button>
</form>
</div>
</div>
</div>
</div>
</section>
</section>
<script src="{{asset('js/vue.js')}}"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
vuejs
<script>
window.Laravel = {!! json_encode([
'csrfToken' => csrf_token(),
'url' => url('/')
]) !!};
</script>
<script>
var app = new Vue({
el: '#app',
data: {
errors: [],
fonctions:[],
fonction:{
fonction :''
}
},
methods:{
checkForm: function (e) {
if (this.fonction.fonction) {
return true;
}
this.errors = [];
if (!this.fonction.fonction) {
this.errors.push('fonction required.');
}
e.preventDefault();
},
addFonction:function(){
axios.post(window.Laravel.url+'/addfonction/', this.fonction)
.then(response => {
//console.log(response.data);
this.fonctions.unshift(this.fonction);
this.fonction={
fonction:''
}
})
.catch(error=>{
console.log(error);
})
},
},
});
</script>
SalarieController.php
public function addFonction(request $request){
$fonction = new Fonction;
$fonction->fonction = $request->fonction;
$fonction->save();
Response()->json(['etat' => true]);
}
Same question, maybe it connect with <form> tag.
I am solve for myself by replace <form> this tag with <div> tag. Also I replace all submit events with click ones on button.

I can't understand how the destroy function work here?

I am working on old laravel project and I have to modify existing one. So I am now trying to understand the code. The project is on laravel and yajra datatable. I can't understand how the destroy function work ? In the view there is a no call for destroy function but when I click the delete button still it is working.
Controller
public function loadSizes()
{
$sizes = Size::select(['id', 'name', 'code'])->get();
return DataTables::of($sizes)
->addColumn('action', function ($size) {
return '<i class="fa fa-wrench" aria-hidden="true"></i>
<button type="button" data-id="' . $size->id . '" class="btn btn-default remove-size remove-btn" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt" aria-hidden="true"></i></button>';
})
->rawColumns(['action'])
->make(true);
}
public function destory(Request $request)
{
$result = Size::where('id', $request->input('size_id'))->delete();
if ($result) {
return "SUCCESS";
} else {
return "FAIL";
}
}
view
#extends('layouts.sidebar')
#section('content')
<div class="row">
<div class="col-sm-12 pad-main">
<div class="row">
<div class="col-md-6">
<h4 class="cat-name"> Size List</h4>
</div>
</div>
<div class="row">
<div class="col-md-12 table-responsive pad-tbl">
<table class="table table-striped" id="size_table">
<thead>
<tr>
<th scope="col"> Name</th>
<th scope="col"> Code</th>
<th scope="col"> Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
#if (Session::has('action'))
#if (Session::get('action') == "create")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size creation successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size creation fail");</script >
#endif
#elseif(Session::get('action') == "update")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size update successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size update fail");</script >
#endif
#endif
#endif
<script>
$(document).ready(function () {
$('#size_table').DataTable({
language: {
searchPlaceholder: "Search records"
},
"columnDefs": [
{"className": "dt-center", "targets": "_all"}
],
processing: true,
serverSide: true,
ajax: '{!! url(' / load - sizes') !!}',
columns: [
{data: 'name', name: 'name'},
{data: 'code', name: 'code'},
{data: 'action', name: 'action'},
]
});
});
$(document.body).on("click", ".remove-size", function () {
var size_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Size ?", "deleteSize(" + size_id + ")");
});
function deleteSize(id) {
$.ajax({
type: 'get',
url: '{!! url('delete-size') !!}',
data: {size_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS", "Delete Size successful");
}
}, error: function (data) {
showAlert("FAIL", "Delete Size fail");
}
});
}
</script>
#endsection
At the bottom of the blade view there is an AJAX in function destory(id).
That AJAX is sending a GET request to a URL delete-size with size id.
Now, if you search your web.php file for that URL (location - routes/web.php), you'll find something like this:
Route::get('delete-size', 'SizeController#destory');
This route would be sending the size id to your destory function, which is in turn searching the Size in your DB and deleting it.
// Controller
public function destroy($id)
{
Tag::find($id)->delete();
Toastr::success('Tag Successfully Deleted',"Success");
return redirect()->back();
}
// Route
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
Route::resource('tag','TagController');
});
// HTML file
<form id="delete-form-{{ $tag->id }}" action="{{ route('admin.tag.destroy',$tag->id) }}" method="POST" style="display: none;">
#csrf
#method('DELETE')
</form>

Laravel 5.3 with Vuejs ajax call

Trying to get some data from database using Vuejs. There are some dummy data in my users table. I want to show them in my view. Problem is though the page loads, It cannot fetch the data from the users table. It does not give any console error. I have checked database connection, restarted server and also checked api data with postman. It's working fine.
Views:
layout.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" media="screen" title="no title">
</head>
<body>
<div class="container">
#yield('content')
</div>
<!-- scripts -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js" charset="utf-8"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.2/vue-resource.min.js" charset="utf-8"></script>
#yield('scripts')
</body>
</html>
fetchUser.blade.php
#extends('layout')
#section('content')
<div id="UserController">
<table class="table table-hover table-striped">
<thead>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Address</th>
</thead>
<tbody>
<tr v-for="user in users">
<td>#{{ user.id }}</td>
<td>#{{ user.name }}</td>
<td>#{{ user.email }}</td>
<td>#{{ user.address }}</td>
<td>#{{ user.created_at }}</td>
<td>#{{ user.updated_at }}</td>
</tr>
</tbody>
</table>
</div>
#endsection
#section('scripts')
<script src="{{ asset('js/script.js') }}" charset="utf-8"></script>
#endsection
script.js
var vm = new Vue({
el: '#UserController',
methods: {
fetchUser: function(){
this.$http.get('api/users', function(data) {
this.$set('users', data )
})
}
},
ready: function(){
}
});
web.php
Route::get('/', function () {
return view('fetchUser');
});
api.php
<?php
use Illuminate\Http\Request;
use App\User;
Route::get('/users', function(){
return User::all();
});
You should use then , and call the fetchUser in the ready function as well
data:{
users: []
},
methods:{
fetchUser: function(){
this.$http.get('api/users').then(function(response){
this.$set('users', response.data);
}, function(response){
// error callback
});
},
ready: function(){
this.fetchUser();
}
vue-resource docs

PHP Laravel : Delete Data using Ajax

I want to delete some data from database using ajax.. I've done the following steps to run..But while I was trying to delete it's shows following Error:
Failed to load resource: the server responded with a status of 404
(Not Found)
Here is my route:
Route::post('/delete/{id}',[
'uses'=>'ItemController#delete',
'as' => 'delete'
]);
Here is the controller:
public function delete($id)
{
Item::find($id)->delete();
return Redirect::back();
}
And here is my view page:
<html>
<head>
<title> Item List</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h3> List Of Courses </h3></br>
<table class="table table-striped table-bordered dataTable" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>Title</td>
<td>Description</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i=1; ?>
#foreach($items as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->title }}</td>
<td>{{$row->description}}</td>
<td>
<button type="button" onclick="deleteItem({{ $row->id }})" id="Reco" class="btn btn-danger">Delete</button>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
</div>
<script>
function deleteItem(id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: '/delete/'+id,
success: function(result) {
console.log(result);
}
});
}
</script>
</body>
</html>
If anyone find the error I've done, hope you'll help me to find it out.
Generally passing parameter while deleting is not a good idea. since we can delete the data through url e.g /delete/4 while you may want to delete only after clicking the delete button.
$.ajax({
type: "POST",
url: "{{url('/delete)}}",
data:{id:id}
success: function(result) {
console.log(result);
}
});
route:
Route::post('/delete',[
'uses'=>'ItemController#delete',
'as' => 'delete'
]);
and, the controller
public function delete(Request $request)
{
$id=$request->id;
Item::where(['id'=>$id])->delete();
return Redirect::back();
}
Try this code:
function deleteItem(id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url:"{{url('delete')}}",
data:{id:id},
success: function(result) {
location.reload();
}
});
}
try this code
function deleteItem(id) {
var _token = $("input[name='_token']").val();
$.ajax({
type: "POST",
url: '/task/'+id,
data: '_method=DELETE&_token=' + _token,
success: function (result) {
console.log(result);
}
});
}
Try this:
$.ajax({
type: "POST",
url: url('/delete'), // The correct way to call ajax function in laravel
data:{
id: id
},
success: function(result) {
console.log(result);
}
});
You can set a method destroy in your controller which laravel automatically uses for deleting. It accepts id.
public function destroy($id){
Item::find($id)->delete();
echo 'Deleted Successfully.';
}
for ajax just send a method delete with your token.
jQuery.ajax({
url:'your-controller-route/id',
type: 'post',
data: {_method: 'delete', _token :token},
success:function(msg){
// do stuff
}
});

Categories