Username Availablity check in laravel 5 using ajax - ajax

On my view page if I am entering username after loader.gif is loading but I am not getting the result for username available or not.. pls give me any ideas...
This is my controller:
public function index()
{
return view('test/username');
}
public function username()
{
$username = Input::get('username');
$users = DB::table('user')
->where('username',$username)
->first();
if ($users !== null)
{
return true;
}
return false;
}
These are my routes:
Route::get('test/username', 'PageController#index');
Route::post('test/username', 'PageController#username');
This is my Blade template:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#username").change(function () {
$("#message").html("<img src='../images/loader.gif' /> checking...");
var username=$("#username").val();
$.ajax({
type:"post",
url: "{{ URL::to('test/username') }}",
data: {username:username},
success: function (data) {
if (data == 0) {
$("#message").html("<img src='../images/yes.png' /> Username available");
} else {
$("#message").html("<img src='cross.png' /> Username already taken");
}
}
});
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Username</td>
<td>:</td>
<td>
<input type="text" name="username" id="username"/>
</td>
<td id="message"></td>
</tr>
</table>
</body>
</html>

In your routes you are not actually calling the username function declared in your controller but a name one, which doesn't exist. Try modifying your second route to:
Route::post('test/username', 'PageController#username');

There are a few issues with your code. First of all, you should only check for exact usernames instead of using LIKE, or this could match similar usernames. Start by updating your function to (comments in code):
public function username()
{
$username = Input::get('username');
$users = DB::table('user')
->where('username', $username) // exact matches only
->first(); // we only need one result
// instead of count, check that a valid result is returned
if ( $users !== null )
{
return true;
}
// else not required
return false;
}
You need to update your route to call the correct function:
Route::post('test/username', 'PageController#username');
Next, you need to update your JavaScript to correctly send the data to your PHP script. Update the data to:
data: { 'username': username },
If you still get errors, you may need to update the name() function to actually return JSON. You can do this using:
return \Response::json( true );

Related

How to use json response with relationship

I want to fetch data from the pivot table platform_user. I am able to get the ID of the user using ajax. PLease see my code below.
Controller
public function show($id) {
$users_id = User::find($id);
$users_id->with('platforms')->where('id', $id)->get();
return response()->json($users_id);
}
Blade - I am using bootstrap modal to get the USER ID and NAME in pop modal. However, I need to fetch data for that USER ID related to the pivot table.
<select name="platform" id="platform" class="form-control">
#if(isset($users_id))
#foreach($users_id as $user_platform)
#foreach($user_platform->platforms as $platform)
<option value="{{$platform->id}}">{{$platform->title}}</option>
#endforeach
#endforeach
#endif
</select>
<script type="text/javascript">
$(document).ready(function() {
$('body').on('click', '#show_user', function () {
var userURL = $(this).data('url');
$.get(userURL, function (data) {
$('#removePlatformModal').modal('show');
$('#user_id').text(data.id);
$('#user_name').text(data.name);
})
});
});
</script>
Try using [whereHas]:
public function show($id) {
$users_id = User::find($id);
$users_id->whereHas('platforms', function($query) use ($user_id){
$query->where('id', $user_id);
})->get();
return response()->json($users_id);
}

Vue.js: Conditional rendering based on computed property

I am trying to conditionally render element(s) based on a computed property but not having much luck even though my computed property is returning true or false correctly.
I am passing the user object in as a property (from Laravel) and all is working fine. I am able to see the user -- and their related role(s).
I've tested via Laravel to make sure I am sending the correct user and the relationship and everything looks good there as well.
Controller
$user = User::with('roles')->find(Auth::id());
blade
<my-component :user="{{ $user }}"></my-component>
VueComponent.vue
<template>
<div>
<div v-if="admin">
<p>You are an admin!</p>
</div>
<div v-else>
<p>You are not an admin.</p>
</div>
</div>
</template>
<script>
export default {
...
computed: {
admin: function () {
this.user.roles.forEach((role) => {
console.log('role: ', role); // role: admin (string)
if (role.name === 'admin') {
console.log('user is an admin!'); // I am getting here.
return true;
} else {
console.log('user is NOT an admin.');
}
});
return false;
},
},
methods: {
//
},
props: {
user: {
type: Object,
required: true,
},
},
}
</script>
I'm sure I am not implementing the computed property correctly; any help is greatly appreciated!
You problem is using foreach in wrong way! please use this instead:
computed: {
admin: function () {
for (var i = 0; i < this.user.roles.length; i++){
if ( this.user.roles[i].name === 'admin') {
return true;
}
}
return false;
}
}
you can read this article about forEach in js https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Your mistake was return true from forEach callback function and leave this true value useless and then return false value on admin function.

Ajax in Laravel Search function is not working

right now it is not showing any data;
console:finished loading: GET "http://todolist.local/teachers/search?text=a".
i am trying to show result in tbody, when user types something in search.
Ajax code:
<script>
$(document).ready(function(){
$('#searchname').on('keyup', function(){
var text = $('#searchname').val();
$.ajax({
type:"GET",
url: 'teachers/search',
data: {text: $('#searchname').val()},
success:function(data){
$('tbody').html(data);
}
});
});
});
</script>
web.php:
Route::get('/search', 'TeachersController#ajaxsearch');
Search Controller:
public function ajaxsearch(){
$searchname = Input::get ( 'searchname' );
if($searchname != ""){
$teacher = Teacher::where ( 'efirst', 'LIKE', '%' . $searchname . '%' )->paginate(10);
return response()->json($teacher);
}
}
view:
<div class="input-group stylish-input-group">
<input type="text" id="searchname" name="searchname" class="form-control" placeholder="Search..." >
<span class="input-group-addon">
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-search">Search</span>
</button>
</span>
</div>
This should do the trick.
HTML:
<div id="datasearch"></div>
JS:
$(function(){
$('#searchname').on('keyup', function(){
$.get('/teachers/search/'+$(this).val(), function(response){
$('#datasearch').html(response);
});
});
});
Controller:
public function ajaxsearch(string $value = null){
return $value ? Teacher::whereRaw("UPPER(efirst) LIKE '%".strtoupper($value)."%'")->paginate(10) : [];
}
Route:
Route::get('/teachers/search/{value?}', 'TeachersController#ajaxsearch');
VERSION AFTER CHAT
HTML:
<ul id="datasearch"></ul>
JS:
$(function(){
var $datasearch=$('#datasearch');
$('#searchname').on('keyup', function(){
$.get('/teachers/search/'+$(this).val(), function(teachers){
$datasearch.empty();
for (var i=0; i<teachers.length; i++){
$datasearch.append('<li>'+teachers[i].efirst+' edit</li>');
}
});
});
});
Controller:
public function ajaxsearch(string $value = null){
return $value ? Teacher::select('id','efirst')->whereRaw("UPPER(efirst) LIKE '".strtoupper($value)."%'")->offset(0)->limit(10)->get() : [];
}
Route:
Route::get('/teachers/search/{value?}', 'TeachersController#ajaxsearch');
do you know about error function in jquery ajax?
$(document).ready(function(){
$('#searchname').on('keyup', function(){
var text = $('#searchname').val();
$.ajax({
type:"GET",
url: 'teachers/search',
data: {text: $('#searchname').val()},
success:function(data){$('tbody').html(data);},
error:function(jqXHR){alert(jqXHR.status);}
});
});
});
You can try this,it will show error if there is some and text should be in inverted commas as it is a key value pair.
In your search controller you are accessing wrong input name. It should be like this
public function ajaxsearch(){
$searchname = Input::get ( 'text' );
if($searchname != ""){
$teacher = Teacher::where ( 'efirst', 'LIKE', '%' . $searchname . '%' )->paginate(10);
return response()->json($teacher);
}
}
First of all, just go to the URL manually and enter parameters.
http://todolist.local/teachers/search?text=a
If you get any response. It's mean your PHP working good.
If you get an error, you are using the GET method. Please pass the variable argument in Route
Route::get('/search/{searchName}', 'TeachersController#ajaxsearch');
and please correct your controller
public function ajaxsearch($searchname){
if($searchname != ""){
$teacher = Teacher::where ( 'efirst', 'LIKE', '%' . $searchname.'%' )->paginate(10);
return response()->json($teacher);
}
}
Second, Please $.get method in Jquery for GET Method AJAX
<script>
$(document).ready(function(){
$('#searchname').on('keyup', function(){
var text = $('#searchname').val();
$.get(urlHere, function(response){
console.log(response);
});
});
});
</script>
See your console tab, If you get response

Dynamic dependent select option using AJAX and Laravel 5.8

I am actually trying to obtain a dynamic dependent select option for city based on region and in my controller i am returning a string(using echo) but unfortunately the string is not rendering in the select option(of cities) on the browser. but i can see it by inspection or by printing on the console.
my jquery:
<script >
$(document).ready(function(){
$('.dynamic').change(function(){
if($(this).val() != '')
{
var select = $(this).attr("id");
var value = $(this).val();
var dependent = $(this).data('dependent');
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('dynamicdependent.fetch') }}",
method:"POST",
data:{select:select, value:value, _token:_token, dependent:dependent},
success:function(result)
{
$('#cityName').html(result);
console.log(result);
console.log(result);
}
})
}
});
$('#RegionName').change(function(){
$('#cityName').val('');
});
});
</script>
: my controller
class DynamicDependent extends Controller
{
public function fetch(Request $request)
{
$select = $request->get('select');
$value = $request->get('value');
$dependent = $request->get('dependent');
$data = city::where($select,$value)->get();
$output = '<option value="">Select '.ucfirst($dependent).'</option>';
foreach($data as $row)
{
$output .= '<option value="'.$row->$dependent.'">'.$row->$dependent.'</option>';
}
echo $output;
}
}
:no eroor message
Here is the picture of the actual outpout :
I suspect that the response might not be that well formed.
Try to return a proper response instead of echoing yourself.
// other code in the controller ...
return response()->json($output);
If it doesn't help, please include the actual response you get in the browser/console.
thanks. actually i was using bootstrap select library and there is a class called selectpicker when i removed this class from the select tag of city it worked fine

Auto Completion Ajax laravel

Hello I need to do autocompletion to some cities i already have in my db
so my code is like this :
View
<input type="text" name="ville" id="ville" class="small" placeholder="Entrer la ville souhaité">
<script type="text/javascript">
$(function() {
$( "#ville" ).autocomplete({
source:'{!!URL::route('autocomplete')!!}',
minlength:1,
autoFocus:true,
select:function(e,ui)
{
$('#ville').val(ui.item.value);
}
});
});
</script>
Controller
class VilleController extends Controller
{
public function autocomplete(Request $request)
{
$term = $request->term;
$queries = DB::table('ville')
->where('libelle_ville', 'like', '%'.$term.'%')
->take(6)->get();
foreach ($queries as $query)
{
$results[] = ['id' => $query->id, 'value' => $query->libelle_ville]; //you can take custom values as you want
}
return response()->json($results);
}
}
Routes
Route::get('/autocomplete', array('as' => 'autocomplete', 'uses'=>'VilleController#autocomplete'));
It doesn't tells me that I have an error and it doesn't show me any completion either.
Debug json request with laravel is a bit difficult, I recommend you to download this package
https://github.com/ARCANEDEV/LogViewer
or manually open the laravel log in storage/logs/laravel.log and see whats happened
Thanks to Stack and EddyTheDove I found out that the error is that aucomplete is not a function so I have to remove the barkets and $function so it would be something like this in the script tag
<script type="text/javascript">
$( "#ville" ).autocomplete({
source:'{!!URL::route('autocomplete')!!}',
minlength:1,
autoFocus:true,
select:function(e,ui)
{
$('#ville').val(ui.item.value);
}
});
</script>

Resources