ErrorException (E_ERROR) Undefined variable: empname - laravel-5

i am having issue undefined variable
this is my controller
'''
if (empty($input['emp_id'])) {
$empname = $input['emp_first_name'] . " " . $input['emp_last_name'];
return redirect()->action('EmployeeController#printQr', ['emp_code' => $input['emp_code'], 'empname' => $empname['empname']]);
} else {
return redirect()->route('employeeList');
}
'''
this is my print page
<!DOCTYPE html>
<html>
<body>
<br/><br/>
<img src="{{ Storage::url("emp_qr_codes/") }}{{ $emp_code }}.png" style="width: 250px;"/>
<br/>
Employee Code: {{ $emp_code }}
<br/>
Employee Name: {{ $empname }}
<script>
var emp_code = #json($emp_code);
var empname = #json($empname);
var ttt = '<br><br>' +
'<img src="{{ Storage::url("emp_qr_codes/") }}' + emp_code + '.png" style="width:250px;" />' +
'<br>Employee Code: ' + emp_code +
'<br>Employee Name: ' + empname;
var newWin = window.open('', 'Print-Window');
newWin.document.open();
newWin.document.write('<html><body>' + ttt + '</body></html>');
newWin.document.close();
newWin.focus();
setTimeout(function () {
newWin.print();
newWin.close();
}, 150);
setTimeout(function () {
window.location.href = '/employee/index';
}, 160);
</script>
</body>
</html>
This is the error I get:
' ErrorException (E_ERROR)
Undefined variable: empname (View: /var/www/html/attendance_system/resources/views/employee/print.blade.php)
Previous exceptions
Undefined variable: empname (0)
'

The controller code you show does not render any views.
Controller should have code like this:
return view('viewNamw', ['empname' => 'test' ]);
This renders a view with variable 'empname' that you can use in blade.

Related

Laravel 8 filter data with ajax

I want to filter the data in my table. I have seen many tutorials online but do not understand. I found a tutorial that seemed very complicated to me. I just want to use a controller and view. Constants are used in that tutorial and the filter data is static but I don't want to use it and my filter data is dynamic. Help me out as a newbie.
The code of the tutorial is given here
app/Constants/GlobalConstants
<?php
namespace App\Constants;
class GlobalConstants {
const USER_TYPE_FRONTEND = "frontend";
const USER_TYPE_BACKEND = "backend";
const ALL = 'All';
const LIST_TYPE = [self::USER_TYPE_FRONTEND, self::USER_TYPE_BACKEND];
const LIST_COUNTRIES = ["Canada", "Uganda", "Malaysia", "Finland", "Spain", "Norway"];
const SALARY_RANGE = ['401762', '85295', '287072', '456969', '354165'];
}
App/User
public static function getUsers($search_keyword, $country, $sort_by, $range) {
$users = DB::table('users');
if($search_keyword && !empty($search_keyword)) {
$users->where(function($q) use ($search_keyword) {
$q->where('users.fname', 'like', "%{$search_keyword}%")
->orWhere('users.lname', 'like', "%{$search_keyword}%");
});
}
// Filter By Country
if($country && $country!= GlobalConstants::ALL) {
$users = $users->where('users.country', $country);
}
// Filter By Type
if($sort_by) {
$sort_by = lcfirst($sort_by);
if($sort_by == GlobalConstants::USER_TYPE_FRONTEND) {
$users = $users->where('users.type', $sort_by);
} else if($sort_by == GlobalConstants::USER_TYPE_BACKEND) {
$users = $users->where('users.type', $sort_by);
}
}
// Filter By Salaries
if ($range && $range != GlobalConstants::ALL) {
$users = $users->where('users.salary', $range);
}
return $users->paginate(PER_PAGE_LIMIT);
}
App/Http/Controllers/HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Constants\GlobalConstants;
class HomeController extends Controller
{
public function index() {
$users = User::getUsers('', GlobalConstants::ALL, GlobalConstants::ALL, GlobalConstants::ALL);
return view('home')->with('users', $users);
}
public function getMoreUsers(Request $request) {
$query = $request->search_query;
$country = $request->country;
$sort_by = $request->sort_by;
$range = $request->range;
if($request->ajax()) {
$users = User::getUsers($query, $country, $sort_by, $range);
return view('pages.user_data', compact('users'))->render();
}
}
}
view code
#foreach($users as $key)
<div class="card">
<div class="card-header">
<img src="{{ asset('assets/images/dev.png') }}" alt="" />
</div>
<div class="card-body">
<span class="tag tag-pink">{{ $key->type }}</span>
<hr>
<span class="tag tag-salary">Salary: {{ $key->salary }}</span>
<h4>{{ $key->email }}</h4>
<p>
{{ $key->address }}
</p>
<h4>Country: {{ $key->country }}</h4>
<div class="user">
#php
$user=App\User::find($key->id)
#endphp
<img src="{{ asset('assets/images/user-3.jpg') }}" alt="" />
<div class="key-info">
<h5>{{ $user['fullname'] }}</h5>
<small>{{ date('d.m.Y H:i:s', strtotime($key->created_at)) }}</small>
</div>
</div>
</div>
</div>
#endforeach
<script>
$(document).ready(function() {
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
getMoreUsers(page);
});
$('#search').on('keyup', function() {
$value = $(this).val();
getMoreUsers(1);
});
$('#country').on('change', function() {
getMoreUsers();
});
$('#sort_by').on('change', function (e) {
getMoreUsers();
});
$('#salary_range').on('change', function (e) {
getMoreUsers();
});
});
function getMoreUsers(page) {
var search = $('#search').val();
// Search on based of country
var selectedCountry = $("#country option:selected").val();
// Search on based of type
var selectedType = $("#sort_by option:selected").val();
// Search on based of salary
var selectedRange = $("#salary_range option:selected").val();
$.ajax({
type: "GET",
data: {
'search_query':search,
'country': selectedCountry,
'sort_by': selectedType,
'range': selectedRange
},
url: "{{ route('users.get-more-users') }}" + "?page=" + page,
success:function(data) {
$('#user_data').html(data);
}
});
}
</script>
public function create(Request $request)
{
$doctors = Doctors::all();
$query = doctors_slots::query();
'services.','consultation.')
// ->get();
if($request->ajax()){
$doctors_slots = $query->where(['doc_id'=>$request->doctors])->get();
return response()->json(compact('doctors_slot'));
}
$doctors_slots = $query->get();
return view('Admin.booking.add_booking',compact('doctors','doctors_slots'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#doctors").on('change', function() {
var doctors = $(this).val();
$.ajax({
url: "{{ route('booking') }}",
type: "GET",
data: {
'doctors': doctors
},
success: function(data) {
var doctors_slots = data.doctors_slots;
var html = '';
if (doctors_slots.length > 0) {
for (let i = 0; i < doctors_slots.length; i++) {
html += '<option value="' + doctors_slots[i][
'available_time_start'
] + '' + doctors_slots[i]['available_time_end'] + '">\
' + doctors_slots[i]['available_time_start'] + ' To\
' + doctors_slots[i]['available_time_end'] + '\
</option>';
}
} else {
html += '<option>No Data Found</option>';
}
$('#option').html(html);
}
});
});
});
</script>

Having problems to pass searched data from controller blade file using ajax in laravel

This is my controller method in Admin Controller , this method receive the search input but i am facing problems to pass output data to the view file
public function action(Request $request)
{
if($request->ajax())
{
$students=Student::where('name','LIKE','%'.$request->search."%")->paginate(5);
$data = $students->count();
if($data > 0)
{
$output=$students;
}
else{
$output=$students;
}
return view('search' compact('output'));
}
}
Here is the ajax in view file (search.blade.php)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
// $(document).on('keyup', '#search', function(){
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{route('search.action')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
})
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
Here is the ajax route
Route::get('/search/action', 'AdminController#action')->name('search.action');
Update the below source code.
AdminController.php
public function action(Request $request)
{
if ($request->ajax()) {
// Convert to lowercase after trim the searched text
$search_text = strtolower(trim($request->search));
$students = Student::where('name','LIKE','%'.$search_text."%")->paginate(5);
$data = $students->count();
$output = array();
if ($data > 0) {
$output = $students->toArray();
}
// Return JSON response
return response()->json($output);
}
}
search.blade.php
<input type="text" id="search">
<div id="studentlist">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{route('search.action')}}',
data:{'search':$value},
success:function(response){
var studentListHtml = "";
if (response) {
if (response.data && response.data.length > 0) {
$.each(response.data , function( index, value ) {
studentListHtml += "<tr><td>" + value.id + "</td>" + "<td>" + value.name + "</td></tr>";
});
$("#studentlist table tbody").empty().html(studentListHtml);
} else {
$("#studentlist table tbody").empty().html("<tr><td colspan='2'>No students found</td></tr>");
}
}
}
});
})
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>

How can I use JSONP to bypass an error with XMLHttpRequest?

Can someone help me to use JSONP so I can bypass this error:
XMLHttpRequest cannot load https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/24332988/ranked?season=SEASON4&?api_key=***********. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.
I am having trouble understanding on how to use it.
Here is the code I have right now which gives me the error above. How can I fix this?
//ap.js
var summonerLookUp = function () {
// DECLARE URIs
var nameUri = 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/';
var statUri = 'https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/';
var statEnd = '/ranked?season=SEASON4&';
// Expose API Key for demo purposes
var apiKey = '?api_key=******************************';
// Grab summoner names;
var summOne = $('#summOne').val();
var summTwo = $('#summTwo').val();
// declare divIds that need to be modified later;
var divIds = {
summoner : '',
sLevel : 'Summoner Level : ',
sId : 'Summoner ID: ',
champKills : 'Champion Kills: ',
death : 'Death Total: ',
assist : 'Assist Total: ',
kda : 'Avg KDA: ',
win : 'Wins: ',
loss : 'Losses: ',
minions : 'Minion Kills: ',
turrets : 'Turret Kills: '
};
// Declare general errorhandler
var errorHandler = function () {
alert('Sorry, please try again.');
};
// Must fetch summoner info first to get basic summoner data
var fetchSummonerStats = function (summoner) {
$.ajax({
url: nameUri + summoner + apiKey,
type: 'GET',
dataType: 'json',
data: {},
success: function (summData) {
summData = summData[summoner];
// attach .summoner property to summData for divIds later
summData.summoner = summoner;
console.log('SUMM DATA >>', summData);
fetchDetail(summData);
},
error: errorHandler
});
};
// Declare secondary ajax call to fetch stats
// provide summonername an data to attach
var fetchDetail = function (summoner) {
$.ajax({
url: statUri + summoner.id + statEnd + apiKey,
type: 'GET',
dataType: 'json',
data: {},
success: function (summStats) {
// include previous data to attach for divIds
summStats.id = summoner.id;
summStats.summoner = summoner.summoner;
summStats.level = summoner.summonerLevel;
attachStats(summStats);
},
error: errorHandler
});
};
var attachStats = function(summStats) {
var summNumber;
/*
attach a 1 or 2 based on summonername;
if summStats.summoner === xkouki,
summNumber = 1 else it must be summTwo
*/
if (summStats.summoner === summOne) {
summNumber = 1;
} else if (summStats.summoner === summTwo) {
summNumber = 2;
} else {
return errorHandler();
}
// change summoner to summoner as saved in riot api
summStats.summoner = summStats.name;
for (var divId in divIds) {
/*
if divId === summoner
val = 'xkouki';
*/
var val = summStats[divId];
/*
add summonerNumber to the current key in divIds
if divId === summoner
and summNumber === 1
id = summoner1;
etc ...
*/
var id = divId + summNumber;
/*
attach prefix to actual value
if divid === summoner
divIds.summoner = ''
innerHtml = '' + xkouki
*/
document.getElementById(id).innerHtml = divIds[divId] + val;
}
};
// make sure both values exist
if (!summOne || !summTwo) {
alert('Please make sure you have an entry for summoner one & two');
} else {
// loop through this array using forEach and fetchSummoner
[summOne, summTwo].forEach(function (summoner) {
fetchSummonerStats(summoner);
});
}
};
$(document).ready(function() {
$('#list').click(function() {
$('.list').fadeToggle("fast");
});
});
<!DOCTYPE html>
<html>
<head>
<title>League Stats</title>
<link rel="stylesheet" type="css/text" href="styles.css"/>
<link rel="stylesheet" type="css/text" href="font.css"/>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<link href='http://fonts.googleapis.com/css?family=Trade+Winds' rel='stylesheet' type='text/css'>
<script src="app.js"></script>
</head>
<body>
<div class="container">
<header class="title">
<h1>League of Legends Face Off</h1>
<input id="summOne" placeholder="summoner name"/>
<input id="vs" type="button" value="VS" onclick="summonerLookUp();" />
<input id="summTwo" placeholder="summoner name"/>
</header>
<div class="one">
<div id="summoner1"></div>
<div id="sLevel1"></div>
<div id="sID1"></div>
<div id="champKills1"></div>
<div id="death1"></div>
<div id="assist1"></div>
<div id="kda1"></div>
<div id="win1"></div>
<div id="loss1"></div>
<div id="minions1"></div>
<div id="turrets1"></div>
</div>
<div class="logo"><img class="vs" src="vs.png"></div>
<div class="two">
<div id="summoner2"></div>
<div id="sLevel2"></div>
<div id="sID2"></div>
<div id="champKills2"></div>
<div id="death2"></div>
<div id="assist2"></div>
<div id="kda2"></div>
<div id="win2"></div>
<div id="loss2"></div>
<div id="minions2"></div>
<div id="turrets2"></div>
</div>
<button id="list">summoner names</button>
<div class="list" style="display: none;">
xkouki | theoddone | le groot | renesisbuddy | azoh | gripex | bestriven na
<br/>
dyrus | kingtrick | voyboy | robertxlee | iamgosu | balls | fabbbyyy | azingy | megazero
</div>
</div>
</body>
</html>

How to set both xPath query in one query?

Here is my totally code:-
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var xml;
$.get(
"xml_converted.xml",
null,
function (data) {
xml = data;
},
"xml"
);
function get_node(ls)
{
var elName = $('#select').val();
var value = $('#value').val();
var xPath = '//*[translate(translate(translate("' + elName + '","-","")," ",""),":","") '+ ls +' translate(translate(translate(#value,"-","")," ",""),":","")]/../../#value';
var iterator = xml.evaluate(xPath, xml.documentElement, null,
XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);
var thisNode = iterator.iterateNext();
var str = '';
while (thisNode) {
if (str) {
str += ', ';
}
str += thisNode.textContent;
thisNode = iterator.iterateNext();
}
$("#result").text(str);
if (str == null || str == "")
return false;
else
return true;
}
</script>
</head>
<body>
<input type="text" id="select">
<input type="text" id="value">
<input type="button" value="Less than" onclick="get_node('>')">
<input type="button" value="Grater than" onclick="get_node('<')">
<input type="button" value="Equal" onclick="get_node('=')">
<div id="result">
</div>
</body>
</html>
This is my xml fiel sample :-
<products>
<product_id value="1">
<tab_id value="351">
<tab_name value="test1"/>
<dist_region value="5,5068,5069"/>
<reg_str_dt value="2013-01-14 20:35:00"/>
<individual_strdt value="2013-01-14 20:35:00"/>
</tab_id>
</product_id>
<product_id value="2">
<tab_id value="352">
<tab_name value="test2"/>
<dist_region value="5,5069,5070"/>
<reg_str_dt value="2013-01-14 20:35:00"/>
<individual_strdt value="2013-01-14 20:35:00"/>
</tab_id>
</product_id>
</productS>
In my xml file I have one tab dist_region_value="5,5069,5070" this type of value for check this I have one xpath:-
var xPath = '//*[contains(concat(#value, ","),"' + elName+ ',")]/../../#value';
and another xpath query is :-
var xPath = '//*[translate(translate(translate("' + elName + '","-","")," ",""),":","") '+ ls +' translate(translate(translate(#value,"-","")," ",""),":","")]/../../#value';
How to set both in one query?
thanks...
How about this:
var xPath = '//*[contains(concat(#value, ","), "' + elNname+ ',") and ' +
' translate("' + elName + '"," -:","") '+ ls +
' translate(#value," -:","")]/../../#value';
as shown here, you don't need to nest multiple translates together, either.

ICanHaz template not rendering

I'm just started using backbone.js and ICanHaz.js for templating. But template is not getting rendered.
var MovieView = Backbone.View.extend({
render : function() {
this.model.movies.each(function(mov) {
console.log("In view " + mov.get('title') + " " + mov.get('format') + " " + mov.get('rating'));
});
var da = JSON.parse(JSON.stringify(this.model.toJSON()));
console.log("Moviedata " + da);
var movList = ich.movies_tmpl(da);
$('#movieList').append(movList);
return this;
}
});
console log prints the movie data. But not in browser. \n
And in my html,
<script id="movies_tmpl" type="text/html">
<li id="movie_{{ cid }}">
<p>Title : {{ title }}</p>
<p>Format : {{ format }}</p>
<p>Rating : {{ rating }}</p>
</li>
</script>
<h1>MovieApp</h1>
Add New Movie
<ul id="movieList"></ul>
TIA,
Arun
Try the following:
{{#movies}}
Title : {{ title }}
Format : {{ format }}
Rating : {{ rating }}
{{/movies}}
and maybe
var da = JSON.parse(this.model.toJSON());

Resources