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
Related
Is it possible to change a value of variable using script? I'm trying to set the data I retrieved in my database and set it in a for loop but I don't know how and all I find are setting or changing value of Input field. I'm using modal so I'm retrieving and displaying it differently.
My code
#php
// value of retrieved in database should be in the variable $count
$count = 3;
#endphp
counting....
#for($i=1;$i<=$count;$i++)
<br/>{{$i}}
#endfor
<br>The user have a total of {{$count}} children.
inside my script
<script>
$(document).ready(function (){
$(document).on('click','.showBtn', function(){
showModal();
$.ajax({
type: 'GET',
url: '/get_data/'+ id,
success: function(response){
console.log(response.count.number_of_children);
}
})
});
});
</script>
and in my Controller
public function get_data($id){
$data = user::find($id);
return response()->json([
'count' => $data
]);
}
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 a grid in which all users are shown. the grid is created and shown by ajax , it has 3 buttons: add, edit, remove. I can add and delete, but since in the update.blade.php I have the user image ( which is shown by a route and controller like : <img src="{{ route('userimage',['id' => $pass_the_id ])}}"/>, the problem now is how do I pass variable like $pass_the_id that I'm about to use in the view blade?
This is the code that brings up the modal ( when edit button which is right in front of user name and id is clicked. I can get user name, family and so on and show it in the modal, but how do I pass the $id to the image route that I mentioned above?
$('body').delegate('#student-info #edit','click',function (e) {
var id = $(this).data('id');
$.get("{{ URL::to('student/edit') }}",{id:id},function (data) {
$('#frm-update').find('#id').val(data.id);
$('#frm-update').find('#name').val(data.name);
$('#frm-update').find('#family').val(data.family);
$('#frm-update').find('#username').val(data.username);
$('#frm-update').find('#birth_date').val(data.birth_date);
$('#frm-update').find('#phone').val(data.cell_phone);
$('#frm-update').find('#email').val(data.email);
$('#frm-update').find('#gender').val(data.gender);
$('#student-update').modal('show');
})
})
here is the Laravel Controller function that is called on URL::to('student/edit') which I have mentioned in the above $.get code :
public function edit(Request $request) {
if($request->ajax()) {
$contact = User::find($request->id);
return response($contact);
}
}
the responsibility of above controller function which is called during $.get is to get the information based on the id that I have passed. ( my grid already shows each user id in the the grid table I've created. but I don't know how to pass it to the src="{{ route('userimage',['id' => $pass_the_id ])}}"
here is what userimage route is doing: below is the route:
Route::get('userimage/{id}','ImageController#showimage')->name('userimage');
and this is its code:
public function showimage($id) {
if(UserImages::selectuserimage($id) !== null) {
$imageData = UserImages::selectuserimage($id);
$info = $info = base64_decode($imageData);
$img = Imgs::make($info);
$img->encode('jpg',80);
return $img;
}
else return public_path('images/Atehran.jpg');
}
On Ajax Success call to pass data to view with return response() in laravel this is the simple way with an example -
js function
$(document).on('change', '[name="abc_field"]', getCitiesByState);
function yourAjaxCall() {
var data_to_pass = $(`[name='get_data_selector']`).val();
var $selector = $(`[name='selector']`);
$.ajax({
url: route('your_route'),
type: 'GET',
data: {
data: data_to_pass
},
dataType: "json",
success: function success(data) {
$selector.empty().append(data);
},
});
}
call to controller from ajax call
public function your_route_function()
{
$result = Abc::where('column',request('data'))->get();
return response()->json([
'result' => view('viewfilename.fields._option', ['options' => $result])->render(),
]);
}
view path "resources\viwes\viewfilename\fields_option.blade" to render
<option value="">{{ $defaultText or 'Select' }}</option>
#foreach($options as $value => $name)
<option value="{{ $value }}">{{ $name }}</option>
#endforeach
Hope this will help you to render view through ajax call.
I am trying to show data which is passed from controller to blade and manipulate something with it in my view page. But I can see the my data passed correctly in my console but i am not getting it in my view file. I am using Laravel 4
Controller:
public function addRow()
{
if(Request::ajax()){
$row = Input::all();
}
return View::make('add-stock')
->with('rows', $row);
}
View :
#if( !empty($rows) )
#foreach($rows as $row)
{{ $row[0] }}
#endforeach
#endif
route:
Route::post('add-stock/row','StockController#addRow');
jQuery :
<script>
$(document).ready(function(){
$('.rowForm').click(function(e){
e.preventDefault();
var rowVal = $('input[name=row]').val();
//ajax post
$.post('add-stock/row', {row:rowVal}, function(data){
console.log(data);
})
})
})
</script>
I would do like this.
Your ajax function........
public function addRow(){
$row = Input::all();
return Response::json($row);
}
And then your JQuery............
<script>
$(document).ready(function(){
$('.rowForm').click(function(e){
e.preventDefault();
var rowVal = $('input[name=row]').val();
//ajax post
$.get('/add-stock/row?rowVal =' +rowVal , function(data){
console.log(data);
$('#rowVal ').empty();
$.each(data,function(index,subcatObj)
{
$('#rowVal ').append('<option value="'+subcatObj.value+'">'+subcatObj.value+'</option>');
})
})
})
})
here #rowVal id of the div or select attribute
And atlast ...........the route file
Route::get('add-stock/row','StockController#addRow');
By the way you didn't specify from where JQuery will be called
You can return the response with JSON content type. Luckily, Laravel provides a tool for that. You could do something right this
if(Request::ajax()){
return Response::json(Input::all());
}
for more information: http://laravel.com/docs/4.2/responses#special-responses
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!!