I'm trying to load a calendar on my page using AJAX/Laravel-5. The URL the AJAX is posting to exists in my routes.php file. However for some reason I keep getting the following error:
Class App\Http\Controllers\AdminBookingsController does not exist
My jQuery call:
(function($){
$.fn.initCalendar = function(token,month,location) {
$('#calendar-overlay-wrap').html('');
$.ajax({
url: '/admin/reports/bookings/butchers',
type: 'post',
data: {
_token: token,
month: month,
location_id: location
},
dataType: 'json',
success: function(json) {
if(json['error']) {
$('#calendar-overlay-wrap').html(json['msg']);
}
$('#calendar').html(json['calendar']);
}
});
}
})(jQuery);
$(document).ready(function() {
$.fn.initCalendar(
$('input[name=_token]').val(),
$('#month').val(),
$('#location_id').val()
);
});
My routes.php file:
Route::post('admin/reports/bookings/butchers', 'AdminBookingsController#genButchersReport');
My controller file:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Booking;
use App\Location;
use App\ClassType;
use App\Classes;
use App\Http\Requests\BookingSearchRequest;
use App\Http\Requests\UpdateBookingRequest;
use App\Http\Requests\BookingReportAccountsRequest;
use Response;
use Excel;
use DB;
class AdminBookingsController extends Controller
{
/**
* Generate booking report for butchers.
*
* #return Response
*/
public function genButchersReport()
{
echo "Hi!...";exit;
}
}
I have tried running composer dump-autoload but this does not seem to have any effect on the error.
Please help.
I managed to resolve this as my controller was inside a sub folder. I changed my route and now it works.
Route::post('admin/reports/bookings/butchers', 'Admin\AdminBookingsController#genButchersReport');
This error popped up for me when I accidentally typed return = $variablename instead of return $variablename in one of my controller files. Maybe it will help somebody.
Related
I have a problem in which I cannot trace the error/problem when trying to export and download my Users table in excel using Maatwebsite I've followed step by step with this reference here link but it didn't export the data through excel,
Is there any wrong with my implementation? Is somebody have an idea what's the problem? I appreciate any comments
index.blade.ph
<li class="navi-item">
<a href="#" class="navi-link">
<span class="navi-icon">
<i class="la la-file-excel-o"></i>
</span>
<span class="navi-text" #click="exportData()">Excel</span>
</a>
</li>
Index.js
methods: {
init() {
var vm = this;
var t;
$(document).ready(function() {
vm.$toaster.init();
vm.setConfig();
});
},
exportData(){
let vm = this;
$.ajax({
url: vm.$route('staff.ajax.emvvalidationdetails.exportemv'),
type: 'GET',
success: function (response) {
if (response) {
// console.log("Test");
}
},
});
},
Staff ajax
Route::group(['prefix' => 'emvvalidationdetails', 'namespace' => 'Emvvalidationdetails'], function () {
Route::get('exportemv', 'EmvvalidationdetailsController#exportemv')->name('staff.ajax.emvvalidationdetails.exportemv');
});
EmvvalidationdetailsController
use Illuminate\Support\Facades\Input;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportUser;
use App\Exports\ExportUser;
use App\Models\User;
public function exportemv(Request $request){
return Excel::download(new ExportUser, 'users.xlsx');
}
ExportUser.php in app/Exports
<?php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class ExportUser implements FromCollection
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return User::select('username','email','password')->get();
}
}
you can download it this way
Download
My guess is that the response's Content-Type is not being set correctly. Maybe it gets messed up by some package or other part of your codes. See the doc here to manually set the Content-Type.
I am new in laravel I am simply wants to insert form input field data into database using jquery ajax but now problem is that when I click on submit button it show 404 error but when I write localhost/practice/public/save in url then (1/1) MethodNotAllowedHttpException. I don't know whay and where I am doing wrong? Please help me.
app/http/controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use DB;
class UserController extends Controller
{
public function save(Request $request)
{
$username = $request->input('username');
$password = $request->input('password');
$confirm_id = md5($username);
$data = array(
'username'=>$username,
'password'=>$password,
'confirm_id'=>$confirm_id
);
print_r($data);
}
}
resources/view/index.blade.php
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
username = $("#email").val();
password = $("#password").val();
$.ajax({
type:"POST",
data:{"username":username,"password":password,"_token":"{{csrf_token()}}"},
url:"{{URL::to('save')}}",
success:function(data){
$("#success").html(data);
}
});
});
});
</script>
route/web.php
<?php
Route::get('/',function(){
return view('index');
});
Route::post('save','UserController#save');
You can't open a post request directly in URL. It will always return MethodNotAllowedHttpException(The GET method is not supported for this route. Supported methods: POST)
So something wrong in ajax request.
url:"{{URL::to('save')}}",
Try to replace this url: {{ url('save') }}
I am trying to achieve simple Ajax call in my web application, unfortunately it is not working.
Html code
<li id="decorative_items">
Decorative Items
</li>
Ajax code:
$(document).ready(function() {
var id = 2; /* This has nothing to do with the code */
$("#decorative_items").bind("click", function() {
alert("click event fired"); /*This is working*/
$.ajax({
type:'POST',
url:'/getDecorativeItems',
data: {'id' : id},
success:function(response) {
alert("foo");
}
});
});
});
routes/web.php
Route::post('/getDecorativeItems', 'ajaxController#fetchDecorativeItems');
ajaxController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
class ajaxController extends Controller
{
function fetchDecorativeItems(Request $request) {
$msg = "Reached Controller";
return response()->json(array('msg'=> $msg), 200);
}
}
I have read all the answers to related questions and other online posts but I am unable to find the error.
Note: The code is working fine, there is no syntax error but I am unable to achieve the intended output. The intended output I am looking for is alerting "foo" using Ajax
Thanks in advance
Turn on your chrome devtool, check on network -> XHR in list of your XHR request, click on your ajax request (Case your ajax request fase, it has red color ) -> preview to see what really happen, if somethings wrong on your Laravel backend code, it also show here.
See the image bellow:
Hope this helfull, don't debug by print an alert()
I got the solution.
I was missing CSRF in my Ajax function call
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
I am new to Laravel and Lumen framework.
I am trying to create an API using Lumen framework.I wanted to enter the data to database. But the database is updated with id, date_created and date_updated. But the data I entered are not inserted there. Instead it shows blank for string inputs and 0 for integer inputs.
Here is my controller code:
<?php
namespace App\Http\Controllers;
use App\Place;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PlaceController extends Controller{
public function savePlace(Request $request){
$place = Place::create($request->all());
return response()->json($place);
}
}
And here is my migration code:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePlacesTable extends Migration
{
public function up()
{
Schema::create('places', function (Blueprint $table) {
$table->increments('id');
$table->string('place');
$table->integer('pincode');
$table->integer('bed');
$table->integer('square_feet');
$table->integer('price');
$table->timestamps();
});
}
public function down()
{
Schema::drop('places');
}
}
Am I doing it correct? Should I use any other codes along with this?
Please help.
Thanks in advance.
EDIT :
And here is my place model code :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Place extends Model{
protected $fillable = ['place', 'pincode', 'bed', 'square_feet', 'price'];
}
EDIT 2 :
I am sending the request from an angularjs app(ionic framework).
Here is my http.post code :
app.controller('NavCtrl', ['$scope', '$http', '$location', '$window', function($scope,$http,$location,$window){
$scope.data = {};
$scope.savedata = function(){
$http({
url : "http://localhost/lumen/public/add",
method : "POST",
headers: $headers,
data : {'place':$scope.data.place,'pincode':$scope.data.pincode,'bed':$scope.data.bed,'square_feet':$scope.data.square_feet,'price':$scope.data.price}
})
.success(function(data,status,headers,config){
console.log(data);
$scope.navigat('/success.html');
})
.error(function(){
alert("failed");
})
};
$scope.navigat = function(url){
$window.location.href=url;
};
}]);
And here is my routes.php code :
<?php
header("Access-Control-Allow-Origin: *");
$app->get('/', function () use ($app) {
return $app->version();
});
$app->post('lumen/public/add','PlaceController#savePlace');
According to this answer, the issue seems to be the way that angular is POSTing the data. Basically, it is attempting to POST data as JSON, but PHP does not do anything to turn JSON data into request query data.
To get this to work, you need to do two things.
First, you need to change the Content-Type header to application/x-www-form-urlencoded. Just changing the content type header won't resolve the issue, though, because angular is still POSTing the data as a JSON request.
Therefore, second, you need to change the data posted from the JSON format to the query string format (name=value&name=value).
So, update your code to something like this:
$http({
url : "http://localhost/lumen/public/add",
method : "POST",
headers: { "Content-Type" : "application/x-www-form-urlencoded" },
data : [
'place=' + encodeURIComponent($scope.data.place),
'pincode=' + encodeURIComponent($scope.data.pincode),
'bed=' + encodeURIComponent($scope.data.bed),
'square_feet=' + encodeURIComponent($scope.data.square_feet),
'price=' + encodeURIComponent($scope.data.price)
].join('&')
})
I'm making the following ajax request.
$.ajax({
url: '../app/Models/UserFiles.php',
data:'data',
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
$('#results').append("id: " +id+ "name: "+name);
}
});
After checking the response with FireBug I noticed this response:
Fatal error: Class 'Illuminate\Database\Eloquent\Model' not found in C:\xampp\htdocs\bluedrive
\drive\app\Models\UserFiles.php on line 6
I can't find anything wrong with UserFiles.php. This actually is the file:
<?php
namespace App\Models;
use \Illuminate\Database\Eloquent\Model;
use Auth;
use App\Models\Filecontent;
class UserFiles extends Model{
protected $table = 'files';
public function getUserFiles(){
$userid = Auth::id();
$getFiles = Filecontent::where('userid', $userid)->get();
foreach($getFiles as $getFile) {
$result = $getFile;
echo json_encode($result);
}
}
} ?>
What am I doing wrong?
The url in ajax call should be something like this:
...
url: <?php echo URL::route('route_to_handle_posted_data.post') ?>
...
Or, if the ajax call is in a js file you can define a
var route_to_post = <?php echo URL::route('route_to_handle_posted_data.post') ?>;
somewhere in templates.