Getting Data from database and showing it in alert - ajax

I'm new to laravel and I want to get data from database and show it on Alert using ajax
My Route:
Route::get('getforajax/{id}','Home#getforajax');
My Controller:
public function getforajax ($id)
{
$result=DB::select('select * from employees where empid =?',[$id]);
return $result;
}
my View:
$('#empid1').keyup(function() {
$.ajax({
url: 'getforajax/3',
type: 'GET',
data: data,
dataType: 'json',
success: function (data) {
alert(data.empid);
}
});
});

You can return json from the controller.
return response()->json($result, 200);
However, the result will be an array of al the resultant rows from the query. So even if you are expecting a single result from query, it is still going to give yo an array of single entry.
[
[
id => something,
name => something
]
]
Also, you can improve it as following :
In your javacript you need to do :
data[0].empId
However, you need to make sure the data is there. Use eloquent models for loading entry from Id :
$result = Employee::findOrFail($employeeid);
And then you do directly do :
alert(data.empid);

You should try this:
use App\Employee; //employee table's model
public function getforajax ($id)
{
$result=Employee::find($id);
return $result;
}

Related

Laravel Autocomplete using Jquery is not fetching data if the table column name isn't 'name'

I am using Jquery and Laravel 5.7 to make an autocomplete feature.
I have a table named 'pricings' there is no column in that table named 'name'. When I search through a keyword it returns nothing.
<script>
$(document).ready(function() {
$( "#search" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "{{url('autocomplete')}}",
data: {
term : request.term
},
dataType: "json",
success: function(data){
var resp = $.map(data,function(obj){
//console.log(obj.city_name);
return obj.name;
});
response(resp);
}
});
},
minLength: 1
});
});
</script>
Here is my Controller:
public function search(Request $request)
{
$search = $request->get('term');
$result = DB::table('pricings')->where('title', 'LIKE', '%'.$search.'%')->get();
return response()->json($result);
}
Table Data
Data in my table
output
output
But if I change my table Column name from TITLE to NAME
It returns data
If there is no column named 'name' how can I fetch data from any column?
In the success callback of your ajax, you are checking for name, you should instead be looking for title which is the column in your Database Table.
success: function(data){
var resp = $.map(data,function(obj){
//console.log(obj.city_name);
return obj.title; //This should be title instead of name.
});

Ajax data not getting into controller

I am using an ajax request to show some information, on my local development version it works perfectly, but on the production server (Ubuntu 16.04 LEMP) it fails in validation, because there is no data in the request.
Checks
The url is correctly showing (e.g. example.com/employeeInfo?employeeId=1)
Ajax itself is working: when I hard-code the controller's response everything is fine.
I cannot figure out why this happens in production, but not on the local version... Huge thanks for any clues!
View
<script>
(function ($) {
$(document).ready(function() {
$(".team-pic").off("click").on("click", function() {
var employeeId = $(this).data('id');
// Get data
$.ajax({
type: "GET",
url: "employeeInfo",
data: {employeeId:employeeId},
success: function(data){
var obj=$.parseJSON(data);
$('#team-info-title').html(obj.output_name);
$('#team-info-subtitle').html(obj.output_role);
$('#resume').html(obj.output_resume);
$('#linkedin').html(obj.output_linkedin);
$("#team-info-background").show();
$("#team-info").show();
}
});
});
});
}(jQuery));
</script>
Route
Route::get('/employeeInfo', 'EmployeeController#getInfo');
Controller
public function getInfo(Request $request) {
if($request->ajax()) {
$this->validate($request, [
'employeeId' => 'required|integer',
]);
$employee = Employee::find($request->employeeId);
$output_linkedin = '<i class="fab fa-linkedin"></i>';
$data = array("output_resume"=>$employee->resume,"output_linkedin"=>$output_linkedin, "output_name"=>$employee->name, "output_role"=>$employee->role);
echo json_encode($data);
}
}
If you want to pass a get data employeeId you have to pass a slug through your route either you should pass the data by POST method.
Route::get('/employeeInfo/{slug}', 'EmployeeController#getInfo');
And Get the slug on your function on controller .
public function getInfo($employeeId)

Laravel 5.6 ajax request, can't read the value

I can't read the values send with ajax request, i don't know what im missing.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#send").click(function(e){
e.preventDefault();
var id = 5;
$.ajax({
type:'POST',
url:'/device/',
data:{id:id},
success:function(data){
console.log('Yes' + data);
}
});
});
in the controller device i just dump the input from the ajax call
$data = $request->all();
dd($data);
I can't see the value send via ajax in the console, i only see Yes but not the data.
What im missing ?
use the following line in your controller;
return $data; instead of dd($data);
Just Replace the + with , like below
console.log('Yes' , data);
try this in controller
public function store(Request $request) {
return Response::json($request->all(), 200);
}
dont forget to include
"use Response;
use Illuminate\Http\Request;"
Use This:
$("#send").click(function(e){
e.preventDefault();
var id = 5:
$.ajax({
type:'POST',
url:'{{url('/device')}}',
data:{
'ajax': 1,'id':id,'_token': {{csrf_token}}
},
success:function(data){
console.log('Yes'+data.id);
}
});
});
In the controller use:
public function name()
{
if(Input::get('ajax') == 1)
{
print_r('Ajax is working');die;
}
}
Also make sure, in the route you have post or any and not get for this route.
try this one.
in controller:
return $data;
And simply replace + with, like this:
console.log('Yes' , data);

Ajax paginator with custom filters

I'm successfully adopted this guide: https://laraget.com/blog/how-to-create-an-ajax-pagination-using-laravel to my needs, it works, but pagination won't work if i apply my custom filters.
Let's start with routes/web.php:
// products routes
Route::get('products', 'ProductController#index')->name('CatalogIndex');
// sorting products with custom filters
Route::post('products', 'ProductController#Filters');
Then we're going to ProductController.php:
public function index(Request $request)
{
$products = Product::orderBy('created_at', 'desc')->paginate(12);
if ($request->ajax()) {
$products_view = view('includes.products', compact('products'))->render();
return response()->json(compact('products_view'));
}
return view('catalog.index', compact('products', 'power', 'area', 'source'));
}
// filtering products
public function Filters(Request $request, Product $product)
{
if ($request->ajax()) {
// using query builder here
$prods = $product->newQuery();
// sorting by price
if ($request->has('order')) {
if ($request->input('order') == 'default') {
$prods->orderBy('created_at', 'desc');
} else {
$prods->orderBy('price', $request->input('order'));
}
}
// more filters omitted for readability
$products = $prods->paginate(12);
$products_view = view('includes.products', compact('products'))->render();
return response()->json(compact('products_view'));
}
return abort(403, 'Unauthorized action.');
}
Some javascript, that makes these filters work:
$('body').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
getProducts(url);
window.history.pushState("", "", url);
});
function getProducts(url) {
$.ajax({
method: 'get',
url: url,
success: function(data) {
$('#products').html(data.products_view);
console.log(data);
},
error: function(jqxhr, status, exception) {
console.log('Error' + exception);
}
});
}
Now is the question, normal pagination with ajax works just fine, if i don't apply any filter, but if apply the filter (select all products where power source equal to something, etc), then when i click on a pagination link, it just leads to my index method of ProductController on 2nd page ignoring my filters, also url changes to "products?page=2", i expect the following behavior -> when you apply source filter == somevalue, then clicking on 2nd page, it would display 2nd page of all products with applied source filter, now it shows just index method with simple sorting by created_at column.
You need:
on the blade partial appends the adicional parameters on the paginator like this:
{!! $products->appends(['param1' => 'val1', 'param2'=>'val2'])->links() !!}
And on your method index() do that:
if ($request->ajax()) {
return $this->filters($request, $product);
}
Good luck.
Your http methods are mismatched. Try changing your route to a "get" instead of "post" and see if that fixes it
Ended using query strings and switched to GET method.

How to pass array of data to controller?

I'm new here :). I have a problem with my code. I'm working with laravel 5.1 and Blade. In my view I have:
function getNumber(){
values = [];
values[0] = $('#receipt_type_id').val();
values[1] = $('#provider_id').val();
$.ajax({
url: "{{{ url('receipts/showByNumber') }}}",
type: "get",
data: {ids: values},
dataType: "json",
success: function (data) {
//i do something
}
});
}
In my route:
Route::get('receipts/showByNumber', ['as' => 'receipt.showByNumber', 'uses' => 'ReceiptsController#showByNumber']);
And in my controller:
public function showByNumber($values){
$receipt_type_id = $values[0];
$provider_id = $values[1];
//Find the receipt to edit
...
...
}
The error is GET http://manchego.app/receipts/showByNumber?ids%5B%5D=1&ids%5B%5D=2 500 (Internal Server Error). I read another topics with the same problem that I have but I can't understand where is my problem.
Thanks in advance! :)
You could type-hint the Request class (recommended):
public function showByNumber(\Illuminate\Http\Request $request)
{
$allParams = $request->all(); // returns an array
$provider_id = $request->get('provider_id');
}
Or you could use the Request facade:
public function showByNumber()
{
$allParams = \Request::all(); // returns an array
$provider_id = \Request::get('provider_id');
}

Resources