hey I want to run a function in my controller using the $.get to pass what is the cod that I want to execute my querys then create my excel file
my route, that's working if I type in adreess bar of my browser my file downloads.
Route::get('relatorios/exportar', array('as' => 'relatorios.exportar', 'uses' => 'ReportsController#exportar'));
my controller: note that works if i change Input::get('cod') to any number
public function exportar()
{
$cod = Input::get('cod');
set_time_limit(0);
$datainicio = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_inicio');
$datafinal = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_fim');
$mes = DB::table('tb_periodo')->where('cod', $cod)->pluck('mes_referencia');
$horarioQuery = $this->horario->with(array('funcionario', 'item_contabil'))
->whereBetween('data', array($datainicio, $datafinal))
->whereNull('deleted_at')
->orderBy('cod_funcionario')
->orderBy('data', 'ASC')
->get();
$horarios = reset($horarioQuery);
$nome = 'Marcações'.$mes.'-'.Carbon::now()->year;
$this->horario->allToExcel($nome, $horarios);
}
my JS: the console log shows the right number but nothing happens
$('#exportar').on('click', function(){
var cod = $("#cod").val();
$.get('exportar', {cod: cod}, function(data) {
console.log(cod);
});
});
my view:
(edited) Hi! sorry I just could see right now. how my form would be ? i did like this:
{{Form::open(array("exportar","id"=>"ajaxForm"))}}
{{ Form::submit('Exportar', array('id' => 'exportar', 'class' => 'exportar')) }}
{{ Form::hidden('cod', $cod, array('id' => 'cod', 'class' => 'cod')) }}
{{ Form::close() }}
I want to pass the COD in the hidden field to the generate the file, my funcition works I just need to pass this number and dont know what's happening.
thanks!
Hello there fellow Laraveller!
At first please use POST, not GET! This means you have to change your route to Route::post...
After that use AJAX, not get like this:
$(".ajaxForm").submit(function(e) {
e.preventDefault();
var postData = $(this).serialize();
var url = $(this).attr('action');
$.ajax({
type: "POST",
data: postData,
dataType: 'JSON',
url: url,
beforeSend: function() {
$(".preloaderContainer").fadeIn(); // example
}
}).done(function(response) {
console.log(response);
}).fail(function() {
console.log(response);
});
So the trick in here is the following:
On submitting your form we need to catch the event 'e' and prevent the page from going to that controller by e.preventDefault();
After that the serialize method gets all iputs fields information and their names and creates query string that is posted to the certain url (method)
and the 'url' variable gets information from the forms attribute 'action'!
In your Method you should do this to check if everything is okay:
$inputs = Input::except('_token');
return Response::json($inputs);
Regards and tell me if you need any other help and explanation!
that worked
I gave up from using ajax and just tried with routes
Route::get('relatorios/exportar/{cod}', array('as' => 'relatorios.exportar', 'uses' => 'ReportsController#exportar'));
my controller
public function exportar($cod)
{
set_time_limit(0);
$datainicio = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_inicio');
$datafinal = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_fim');
$mes = DB::table('tb_periodo')->where('cod', $cod)->pluck('mes_referencia');
$horarioQuery = $this->horario->with(array('funcionario', 'item_contabil'))
->whereBetween('data', array($datainicio, $datafinal))
->whereNull('deleted_at')
->orderBy('cod_funcionario')
->orderBy('data', 'ASC')
->get();
$horarios = reset($horarioQuery);
$nome = 'Marcações'.$mes.'-'.Carbon::now()->year;
$this->horario->allToExcel($nome, $horarios);
}
view:
{{ link_to_route('relatorios.exportar', 'Exportar para excel', array($cod), array('class' => 'btn btn-success')) }}
that's solved for me, because dont load another page and download the correct file.
thx for the help!!
Related
I am trying to send variable with data from a function to laravel front page view and i get Undefined variable: data (View: C:\xampp\htdocs\laravelproject\resources\views\process-url.blade.php).
This is my code and web.php routes.
web.php
Route::get('/', [welcomechecker::class, 'getfrontpage']);
Route::post('process-url', [welcomechecker::class, 'saveformdata']);
welcomechecker.php controller
class welcomechecker extends Controller
{
function getfrontpage(){
return view('welcome');
}
function saveformdata(Request $request){
$client = new Client();
$data = [];
$url = $request->url; //getting value from ajax $url = $request->url;
$wp = $url.'/'.'wp-admin';
$website = $client->request('GET', $url);
$html = $website->html();
//Check if cms is wordpress
$cms = '';
if($this->isWordPress($wp, $html) == 'WordPress'){
$cms = 'WordPress';
$data['cms'] = 'WordPress';
}
return view('process-url', compact('data'));
}
view blade: process-url.blade.php
#foreach($data as $student)
{{$student->cms}}
#endforeach
front page view blade: welcome.blade.php
<div class="display-content alert-success" >
#include('process-url')
</div>
application.js having ajax code
jQuery(document).ready(function(){
$(document).ajaxStart(function(){
$("#wait").css("display", "block");
});
$(document).ajaxComplete(function(){
$("#wait").css("display", "none");
});
jQuery('#ajaxsubmit').click(function(e){
e.preventDefault();
jQuery('.alert').show();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: 'process-url',
type: 'POST',
data: {
url: jQuery('#enter_url').val()
},
success: function(result){
console.log(result);
jQuery('.display-content').html(result.success).fadeIn(700);
// jQuery('.display- content').html(result.success).fadeIn(700).fadeOut(5000);
}});
});
});
Someone please help me to identify what i am doing wrong. I am trying to submit the variable data to the process-url blade view which is routed to the saveformdata() on the web.php. The error occurs in process-url.blade.php at the data variable. The saveformdata function has a whole lot of code than what i actually put here the whole idea is that it returns an array of data from a scraping tool which i want to display on a table on process-url blade
Of course you will get Undefined Variable error when you are trying to include a blade file that is waiting for an array $data which is only passed to the view when you hit the route process-url. Also it is really, really bad practice to return a view after a POST request. Anyways, to solve your error (because that's what you actually want) you can do the following:
Pass the $data to the welcome page view and remove it from the process-url view
function getfrontpage(){
return view('welcome', [
'data' => ['Balloon Fight', 'Donkey Kong', 'Excitebike']
]);
}
function saveformdata(){
return view('process-url');
}
Pass the $data array from the welcome view to the process-url view through #include
<div class="display-content alert-success" >
#include('process-url', ['data' => $data])
</div>
Your error now disappeared. Your code still makes no sense, but this is what you wanted.
In the first URL you show a welcome blade file and it includes process-url blade without data variable
you should pass data variable in getfrontpage function like saveformdata
and the include directive pass variable to child blade
function getfrontpage(){
$data = ['Balloon Fight', 'Donkey Kong', 'Excitebike'];
return view('welcome', compact('data'));
}
and data variable array type that student will show every element in the array
#foreach($data as $student)
{{$student}}
#endforeach
I've Signup form in my website. It was properly submitting before. Now I wanted to submit my form using ajax and wanted to return a variable from controller into JSON that I will use into blade file.
The form is submitting and values are showing into database but after redirection, it returns error.
Undefined variable: seller in report blade
I tried to decode my variable to make it work but still the same error.
How would I make it work?
Report-Blade
#foreach(json_decode($seller, true) as $row)
<a href="{{route('Report', $row->id) }}" >
{{ __('Show Report of ')}} {{$row->car_title}}
</a>
#endforeach
Controller
$seller = Sellers::take(1)->latest()->get();
return response(view('report',array('seller'=>$seller)),200, ['Content-Type' =>
'application/json']);
JavaScript
$("#submit-all").click(function(e){
e.preventDefault();
var _token = $('input[name="_token"]').val();
$.ajax({
type: "post",
url: "{{ route('form_for_private_sellers') }}",
data : $('#msform').serialize() + "&_token=" + _token,
dataType: 'JSON',
beforeSend: function(){
// Show loading image
$("#se-pre-con").show();
},
success: function(data) {
window.location = "http://127.0.0.1:8000/report/";
},
complete:function(data){
// Hide loading image
$("#se-pre-con").hide();
}
});
});
As understood from your comments,
window.location = "http://127.0.0.1:8000/report/";
will hit the route
Route::get('/report', function () {
return view('report');
})->name('private_seller_report');
Report blade expects a variable named $seller, and it is not being sent from the route. You would need to change the route to something similar to this:
Route::get('/report', function () {
$sellers = Seller::get(); //your logic
return view('report', ['seller' => $sellers]);
})->name('private_seller_report');
Alternatively you can point the route to a method in a controller if you want to avoid bulking up your routes.
you need two route for this
first for rendering blade
return view('report');
and the second for fetch seller
$seller = Sellers::latest()->take(1)->get();
return $seller
I have some problems with my ajax call, I have a collection group and when I click on show link it should show me the collection's tasks.The problem is when I try to create new tasks for the current collection.I made 50% of the problem, because it creates the records in database, but something strange happen.
Form is already submitted even If I do not click the create button
After ajax call, it creates the records in database, but it does not append the newly created element, it shows me this:
Ajax call response
Here is my ajax script:
$(document).ready(function() {
// store task
$('#create-task').click(function (event) {
event.preventDefault();
$.ajax({
type: 'post',
dataType: 'json',
data: $('#create-task-form').serialize(),
success: function (data) {
$('#create-task-form').trigger('reset');
$('#createTaskModal').modal('hide');
$('.collections').append('<li>' + data.name + '</li>');
}
});
});
});
I did not set the url, because when I do that it shows me something like this, and I do not know why.
Duplicate collection/collection/id
Set the url
Routes:
// Collection routes
Route::prefix('collections')->middleware('auth')->group(function() {
Route::get('/', 'CollectionController#index')->name('collections.index');
Route::post('/', 'CollectionController#store')->name('collections.store');
Route::get('/{collection}', 'CollectionController#show')->name('collections.show');
Route::get('/{collection?}/edit', 'CollectionController#edit')->name('collections.edit');
Route::patch('/{collection?}', 'CollectionController#update')->name('collections.update');
Route::delete('/{collection?}', 'CollectionController#destroy')->name('collections.destroy');
Route::post('/{collection?}', 'CollectionController#storeTask')->name('tasks.store');
});
Controller
public function storeTask(Request $request)
{
$attributes = $request->validate([
'name' => 'required|min:3',
'description' => 'nullable|min:3',
'status' => 'required',
'due' => 'nullable|date'
]);
$attributes['collection_id'] = $request->collection;
$task = Task::create($attributes);
return Response::json($task);
}
PS: I can still create records, even the validation from back-end fails!
Based on your image your routing is wrong.
You get a 404 for trying to access collections/collections twice leading to a non existing URL of course.
A solution to this would be:
url: {{ url('/collections/25') }},
In my laravel 5.4 app, i have a crud module. for the edit bit, the data is rendered in a bootstrap modal. the data is pulled successfully but on hitting the update button, the error shown is returned.
here's my blade form that's rendered in the modal:
<form id="formEdit" class="form-horizontal" role="form" method="put">
//form elements
</form>
here's the ajax that handles it:
//edit_id is defined globally
$('#updateClass').click(function(){
var name = $("#formEdit #name").val();
var status = ($('#formEdit #status').prop("checked") == true) ? 1 : 0;
var token = $('meta[name="csrf-token"]').attr('content');
var id = edit_id;
var url = "classes/update/"+id;
var formdata = {
'name' : name,
'status' : status,
'_token' : token
};
$.ajax({
method: "PUT",
url: url,
data: formdata,
dataType: "json"
})
.done(function(data) {
//
})
.fail(function(data) {
//
});
});
});
updateClass is the button that displays the edit form on the modal..
here's my routes in web.php:
Route::resource('classes', 'ClassesController');
Route::group(['prefix' => 'admin'], function () {
Route::get('classes', 'ClassesController#index');
Route::get('classes/edit/{id}', 'ClassesController#edit');
Route::put('classes/update/{id}', 'ClassesController#update');
});
and finally, my update function in the classes controller:
public function update(Request $request, $id)
{
$validator = $this->validator($request->all());
$errors = $validator->errors();
$errors = json_decode($errors);
if ($validator->passes())
{
Dl_class::find($id)->update($request->all());
return response()->json();
}
else
{
return response()->json($errors, 422);
}
}
what i'm i missing?
To send PUT request from form you need to send a hiddne input element named as method. Something like this:
<input type='hidden' name='_method' value='PUT'>
there is a helper method to do the same like:
{{ method_field('PUT') }}
Only then Laravel can recognize your PUT request.
Or alternatively, you can enclose this value to your ajax call also Something like:
var formdata = {
'name' : name,
'status' : status,
'_token' : token,
'_method' : 'PUT'
};
Complete Edit
I've edited my original question as I've refined my code which has put me in a much better position to define a better error
Hi I'm creating a chained select box that will once a client is selected find the clients projects.
The ajax is doing its job it knows which client has been selected and my console tells me the following:
Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://itempus.dev/task/clientsprojects?option=5
The above option value refers to the client id which I want to pass into the projects db and find the clients projects. I'm not sure what I am doing wrong and would appreciate some help in a somewhat complex task for a newbie.
TaskController
public function create()
{
$tasks = Auth::user()->tasks;
$client_options = DB::table('clients')->orderBy('client_name', 'asc')->lists('client_name','id');
$team_options = DB::table('teams')->orderBy('team_member_name', 'asc')->lists('team_member_name','id', 'team_member_category');
return View::make('tasks.create', array('project_options' => $project_options, 'team_options' => $team_options, 'client_options' => $client_options));
}
public function clientsprojects() {
$input = Input::get('option');
$client_id = Project::find($input);
$projects = DB::table('projects')->where('client_id', $client_id->id)
->orderBy('project_name')
->lists('id','project_name');
$models = $project->projects();
return Response::eloquent($models->get(array('id','project_name')));
}
views/tasks/create.blade.php
{{ Form::open(array('action' => 'TaskController#store', 'id' => 'createuser')) }}
<div class="form-group">
#if(count($client_options)>0)
{{ Form::label('select_client', 'Assign to Client', array('class' => 'awesome client_option')); }}
{{ Form::select('client', $client_options , Input::old('client'), array('class' => 'tempus_select client_option', 'id' => 'select_client')) }}
#endif
</div>
<div class="form-group deletegates">
{{ Form::label('select_client', 'Assign to Project', array('class' => 'awesome')); }}
{{ Form::select('project', array_merge(array('default' => 'Please Select')), 'default', array('class' => 'tempus_select', 'id' => 'project_select')) }}
</div>
{{ Form::submit('Create the task!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
<script>
$(document).ready(function($){
$('#select_client').change(function(){
$.get("{{ url('task/clientsprojects')}}",
{ option: $(this).val() },
function(data) {
var model = $('#project_select');
model.empty();
$.each(data, function(index, element) {
model.append("<option value='"+ element.id +"'>" + element.name + "</option>");
});
});
});
});
</script>
Route.php
I've also defined my route as so:
Route::get('task/clientsprojects', function(){
$input = Input::get('option');
$client_id = Project::find($input);
$projects = DB::table('projects')->where('client_id', $client_id->id)
->orderBy('project_name')
->lists('id','project_name');
$models = $project->projects();
return Response::eloquent($models->get(array('id','project_name')));
});
I assume that the create function in the TaskController works correctly and creates the first drop down menu for the clients.
When this drop down changes value, an ajax get request is sent to the server but you receive a 500 (Internal Server Error) because something is wrong with your queries.
So lets try to fix that.
Route::get('task/clientsprojects', function(){
// Get the option value which is the client_id
$client_id = Input::get('option');
// Get all projects that have client_id = $client_id
$projects = DB::table('projects')
->where('client_id', $client_id)
->orderBy('project_name')
->lists('id','project_name');
//Return the response to the client
return Response::json($projects);
});
Now the response is back to the client. Replace your JavaScript with the following.
$(document).ready(function($){
$('#select_client').change(function(){
$.get("{{ url('task/clientsprojects')}}", { option: $(this).val() },
function(data) {
var projects = $('#project_select');
projects.empty();
$.each(data, function(key, value) {
projects
.append($("<option></option>")
.attr("value",key)
.text(value));
});
});
});
});
And you're good to go.
You need some JavaScript (AJAX) to accomplish this, basically, a select element has a change event which fires upon changing any value, I mean, if user selects an item then the change event fires and you have to declare a change event handler in JavaScript for you client combo/select element. There are so many ways to use an event handler, for example (Your select should contain an id as id='select_client'):
window.onload = function(){
document.getElementById('select_client').onchange = function(){
// ...
};
};
Or you may use addEventListener and if you use a library like jQuery then you may do it using something like this:
$(function(){
$( "#select_client" ).change(function(e) { // i.e. '/get_progects/{clientId}'
e.preventDefault();
var clients = $(this);
$.getJson('yuordomain/get_projects/' + clients.val(), function(response){
// id = 'projects' for projects combo.select
var projects = $('#projects');
projects.empty();
$.each('response.projects', function(k, v){
var option = $('<option/>', {'id':v.id, 'text':v.projectName});
projects.append(option);
});
});
});
});
This will simply, fetch the data (projects depending on the selected client) from server when ever a user selects the client dropdown box and to make this work you need to declare a route for fetching the projects dasta, for example:
Route::get('/get_progects', function($client_id){
// I'm using a closure here but you should use a class method
$projects = Project::where('client_id', $client_id)
->orderBy('project_name')
->lists('id','project_name');
return Response::json(compact('projects'));
});
This is the very basic idea and hope you can implement it in your project now.