Laravel autocomplete 404 (Not Found) - php

So i am noob working with laravel, i have try find a solution but i can not find out.
I am making a autocomplete in laravel.
My route:
Route::get('autocomplete',array('as'=>'autocomplete','uses'=>'SearchController#autocomplete'));
My SearchController:
public function autocomplete(Request $request)
{
$data = Country::select("name")->where("name","LIKE","%{$request->input('query')}%")->get();
return response()->json($data);
}
My script:
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
And finaly my input:
input class="typeahead form-control" id="front-item-field" placeholder="{{trans('messages.home.where_want_to_go')}}" name="item" type="text" required>
The error:
GET http://xxxxx.com/autocomplete?query=p 404 (Not Found)

Well i have made a mistake the route was inside of a route group for auth user, so i have change the line of the route to evry one can see and works like a charm.

Related

I'm making an dependent drop-down of countries states and cities in Laravel 9 using jQuery and Ajax but getting an 500 internal server

I'm making an dependent drop-downn of countries states and cities in laravel using jQuery and Ajax. I'm doing it on localhost Xampp. First i use jQuery for country. when country change jQuery get value and send to Controller. But when i send value from RegistrationFormComponent to CountryStateCity Controller and try to show what value i get. I got an error ( POST http://127.0.0.1:8000/getstate 500 (Internal Server Error) ). i don't know why im getting this error.
Route:
Route::get('/register', [CountryStateCityController::class, 'getcountry']);
Route::POST('/getstate ', [CountryStateCityController::class, 'getstate']);
JQuery and Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$('#country').change(function () {
var cid = this.value; //$(this).val(); we cal also write this.
$.ajax({
url: "getstate",
type: "POST",
datatype: "json",
data: {
country_id: cid,
},
success: function(result) {
// if(cid == "success")
// alert(response);
console.log(result);
},
errror: function(xhr) {
console.log(xhr.responseText);
}
});
});
});
Controller
class CountryStateCityController extends Controller
{
public function getcountry() {
$country = DB::table('countries')->get();
$data = compact('country');
return view('RegistrationForm')->with($data);
}
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
public function getcity() {
}
}
I think i tryed every possible thing. But didn't work. Please tell me how can i get rid of this problem. And please also tell me how can i send data from component to controller using jquery and ajax and get value form controller and take data from database and send back to component.
This is written incorrectly.
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
It should look like this.
public function getstate(Request $request) {
$state = State::where('countryid', '=', $request->country_id)->get();
return response()->json($state);
}
please check controller function
public function getstate(Request $request) {
$state = State::where('countryid' `=` ,request->$countryid)->get();
return response()->json($state);
}

How to send dropdown selected value through ajax call to controller in laravel

I'm new with laravel and I want to send the selected dropdown option value of product name through ajax data to the controller
For Example: If I'm select 1st plastic product option value from a drop-down then in the controller from request object I want that selected product name
as per my below code I'm getting null in the request object of the product name
Here is my route:
Route::get('product', 'ProductController#index')->name('product');
Here is my controller:
public function index(Request $request)
{
if (isset($request->productName)) {
$productName = $request->productName;
dump($productName); // getting null
} else {
$productName = null;
}
return view('Product.product');
}
Here is my an ajax call:
function display(productName){
productName = $('#product_filter').val(); // Here, I'm getting selected value of dropdown
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('product')}}",
type: "GET",
data:{
'productName' : productName // in header request I'm getting value [productName: plastic product] *
},
success:function(data){
console.log(data);
},
error:function(e){
console.log(e,'error');
}
});
}
header request result
I don't know if I'm doing something wrong,
ends with wanting to get help from helping hands please help me to get the selected value to the controller object
I believe you got null because you are returning a full HTML to the Ajax request. In order to get the payload sent from the Ajax, you have to return a JSON response like this:
public function index(Request $request)
{
$productName = null;
if (isset($request->productName)) {
$productName = $request->productName;
}
return response()->json($productName);
}
That being said, I'm unable to reproduce the issue without seeing how do you call the method and where would you show the data to. And I assume you want to simply just do a console.log(data) like you did on the given snippet. In this case, the snippet above will work.
And if you want to keep the view to prevent error when you refresh the page, just add a new method for that specific call in your controller and send the request to that endpoint, like this:
web.php
<?php
Route::get('/', [ProductController::class, 'index']);
Route::get('/productFilter', [ProductController::class, 'productFilter'])->name('dashboard-product-data');
ProductController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index(Request $request)
{
return view('welcome');
}
public function productFilter(Request $request)
{
$productName = null;
if (isset($request->productName)) {
$productName = $request->productName;
}
return response()->json($productName);
}
}
welcome.blade.php
<div>Product Name: <span id="product-name"></span></div>
<select id="product_filter" name="product_filter">
<option value="plastic product">plastic product</option>
</select>
<button id="submit-button" type="button">Send data</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
function display(productName){
productName = $('#product_filter').val(); // Here, I'm getting selected value of dropdown
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('dashboard-product-data')}}",
type: "GET",
data:{
'productName' : productName // in header request I'm getting value [productName: plastic product] *
},
success:function(data){
console.log(data);
document.querySelector('#product-name').innerHTML = data
},
error:function(e){
console.log(e,'error');
}
});
}
const submitButton = document.querySelector('#submit-button')
submitButton.addEventListener('click', () => display())
</script>

Laravel autocomplete search questions

I am working on online shop that has categories page and in accordance of the category that is chosen products page is displayed .
I want to create an autocomplete search field that will be available in those 2 pages that will show products only , once that match the search.
Where should I create my search field?How my route should look?What view should I return? I would appreciate very much even farther instructions of creating autocomplete search field. Thank you
if you create the search field in both pages you code should look like this:
the search field:
<input type="text" name="search" value="" id="search">
your route:
Route::post('/search', 'SomeController#searchFunction')->name('search');
and your search function in the controller
class SomeController extends Controller
{
public function searchFunction(Request $request){
return CategoryClass::where('name', 'like', '%'.$request->search.'%')->get();
}
}
then you can create a main.js file por example with you ajax call and include it in both blade pages
the ajax call can be something like this:
$("#search").keyup(function() {
$.ajax({
url: "{{ route('search') }}",
type: "post",
data: $("search").serialize(),
success: function (data) {
//do something
},
error: function (data) {
console.log(data)
}
});
});
Hope this helps

Submit form using VueJs and AJAX in Laravel 5.1

I am trying to submit a form using AJAX and VueJs. But somehow I am failing to achieve that. I always end up getting an empty Illuminate\Http\Request object.
The blade file:
<body>
<div class="container">
<generate-admin></generate-admin>
</div>
<script src="https:http://code.jquery.com/jquery.js"></script>
<script src="{{ url('/js/main.js') }}"></script>
</body>
The component:
<template>
<form id="createAdministrator" #submit.prevent="createAdministrator">
<div class="form-group">
<input type="text"
name="username"
id="txtUserName"
placeholder="Username"
autocomplete="off"
v-model="username"
/>
</div>
<input type="submit" value="Submit">
</form>
</template>
<script>
export default {
data: function() {
return {
username: ''
}
},
methods: {
createAdministrator: function() {
formContents = jQuery("#createAdministrator").serialize();
this.$http.post('/admin', formContents).then(function(response, status, request) {
console.log(response);
}, function() {
console.log('failed');
});
}
}
}
</script>
main.js
import Vue from 'vue';
import GenerateAdmin from './components/GenerateAdmin.vue';
var VueResource = require('vue-resource')
Vue.use(VueResource);
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');
Vue.http.options.emulateJSON = true;
new Vue({
el: 'body',
components: { GenerateAdmin }
});
gulpfile.js
var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');
elixir(function(mix) {
mix.browserify('main.js');
});
routes.php
Route::get('/admin/create', function () {
return view('admin.create');
});
Route::post('/admin', function(Request $request) {
// returns an empty object.
return response(['results' => $request]);
});
Route::get('/', function () {
return view('welcome');
});
What I get in return is:
"{"results":{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}}"
When I check the Request Payload section of Network Tab in Chrome. I do see that the form is getting submitted successfully with whatever data I write in the text box above.
Why is this happening ? Kindly guide me where I have made the mistake ?
UPDATE 1:
I was playing trial and error with the code above. And I removed the namespace Illuminate\Http\Request and also removed the argument Request $request from the post Route. And changed the passing parameter to object from string.
Doing so, did the job for me that I was looking for. Why I don't know. I am still looking for someone who can explain this to me.
Why adding the namespace Iluminate\Http\Request in routes.php file didn't work as I was expecting and removing it did the task ?
Can anybody tell me why it didn't worked out earlier ? Any kind of help is highly appreciated.
P.S.: I have started learning VueJs Components recently.
As a general practice I follow, any form data which needs to be passed to the laravel controller is passed as json object from vue frontend. Then in laravel controller (route with a closure function in your case) the values from the received json object are retrieved by using $request->get('key').
So in your case the component code could be
<template>
<form id="createAdministrator" #submit.prevent="createAdministrator">
<div class="form-group">
<input type="text"
name="username"
id="txtUserName"
placeholder="Username"
autocomplete="off"
v-model="username"
/>
</div>
<input type="submit" value="Submit">
</form>
</template>
<script>
export default{
template:require('./generate-admin-template.html'),
data() {
return {
username: ''
}
},
computed:{
formData(){
return {
username:this.username
}
}
},
methods: {
createAdministrator: function() {
this.$http.post('/admin', this.formData).then(function(response) {
console.log(response);
}, function() {
console.log('failed');
});
}
}
}
</script>
Then in your routes.php file
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin/create', function () {
return view('admin.create');
});
Route::post('/admin', function (Request $request) {
return response(['results' => $request->get('username')]);
});
I guess the Illuminate\Http\Request instance returns a $request - Collection so we need to access the values using Methods available on Collections.
I have tested the above code along with your code for main.js and '/admin/create'.
One more thing - I think if you send serialized form data to the controller, then within the controller it needs to be de-serialized in order to get object or array containing $key=>$value pairs to facilitate fetching required data.
All variables ($attributes, $request, $query, etc) on Request and SymfonyRequest classes are protected, since neither class implements __toString, php does its best to give you what it can.
If you need to see each value, you need to call correct getter. Something like:
Route::post('/admin', function(Request $request) {
return response(['server' => $request->server(), 'form'=>$request->all()]);
});

laravel 5 simple ajax retrieve record from database

How can I retrieve data using ajax? I have my ajax code that I've been using in some of my projects when retrieving records from database but dont know how to make it in laravel 5 because it has route and controller.
I have this html
<select name="test" id="branchname">
<option value="" disabled selected>Select first branch</option>
<option value="1">branch1</option>
<option value="2">branch2</option>
<option value="3">branch3</option>
</select>
<select id="employees">
<!-- where the return data will be put it -->
</select>
and the ajax
$("#branchname").change(function(){
$.ajax({
url: "employees",
type: "post",
data: { id : $(this).val() },
success: function(data){
$("#employees").html(data);
}
});
});
and in my controller, I declared 2 eloquent models, model 1 is for branchname table and model 2 is for employees table
use App\branchname;
use App\employees;
so I could retrieve the data like (refer below)
public function getemployee($branch_no){
$employees = employees::where("branch_no", '=', $branch_no)->all();
return $employees;
}
how to return the records that I pulled from the employees table? wiring from routes where the ajax first communicate to controller and return response to the ajax post request?
any help, suggestions, recommendations, ideas, clues will be greatly appreciated. Thank you!
PS: im a newbie in Laravel 5.
At first, add following entry in your <head> section of your Master Layout:
<meta name="csrf-token" content="{{ csrf_token() }}" />
This will add the _token in your view so you can use it for post and suchlike requests and then also add following code for global ajax setting in a common JavaScript file which is loaded on every request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
So, you don't need to worry or add the csrf_token by yourself for methods who require this _token. Now, for a post request you may just use usual way to make an Ajax request to your Controller using jQuery, for example:
var data = { id : $(this).val() };
$.post(url, data, function(response){ // Shortcut for $.ajax({type: "post"})
// ...
});
Here, url should match the url of your route declaration for the employees, for example, if you have declared a route like this:
Route::post('employees/{branch_no}', 'EmployeeController#getemployee');
Then, employees is the url and return json response to populate the select element from your Controller, so the required code for this (including javaScript) is given below:
$.post('/employees/'+$(this).val(), function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
$.each(response.employees, function(i, employee){
$('<option/>', {
value:employee.id,
text:employee.title
}).appendTo(branchName);
})
}
}, 'json');
From the Controller you should send json_encoded data, for example:
public function getemployee($branch_no){
$employees = employees::where("branch_no", $branch_no)->lists('title', 'id');
return response()->json(['success' => true, 'employees' => $employees]);
}
Hope you got the idea.
First check url of page from which ajax call initiates
example.com/page-using ajax
In AJAX
If you call $.get('datalists', sendinput, function())
You are actually making GET request to
example.com/page-using ajax/datalists
In Routes
Route::get('page-using-ajax/datalists', xyzController#abc)
In Controller Method
if (Request::ajax())
{
$text = \Request::input('textkey');
$users = DB::table('datalists')->where('city', 'like', $text.'%')->take(10)->get();
$users = json_encode($users);
return $users;
}
In Ajax Success Function
function(data) {
data = JSON.parse(data);
var html = "";
for (var i = 0; i < data.length; i++) {
html = html + "<option value='" + data[i].city + "'>";
};
$("#datalist-result").html(html);
}
Add in your route:
Route::post('employees', [
'as' => 'employees', 'uses' => 'YourController#YourMethod'
]);
Ajax:
Change:
url: "employees"
to:
url: "/employees"

Categories