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
Related
This is how my Controller and View work
Controller
class DayhomeController extend Controller{
public function index(){
$Dataset = Modal::all();
return view('DayHome')->with('DataSet',$DataSet)
}
View
<div class="container" id="container1">
<input type="date" id="datepicker" name="datepicker" value="<?php echo date('Y-m-d'); ?>"
</div>
#for ($i = 0; $i < count($DataSet); $i++)
<div class="container" id="container2">
<div> {{$DataSet[$i]->name}} </div>
<div> {{$DataSet[$i]->number}} </div>
</div>
#endfor
<script type="text/javascript">
$('#datepicker').on('change', function() {
var datepicker = $('#datepicker').val();
alert(datepicker);
$.ajax({
url: '/orderdata',
data: datepicker,
type: "get",
cache: false,
success: function () {
$('#something').empty();
$('#something').append();
},
error: function () {
;}});});
</script>
Route
Route::get('/orderdata', 'DayhomeController#OrderDataorIndex');
1.I would like to ask if I use ajax to pass the datepicker value to the controller, should I pass it to the index or create another public function OrderData($Request $datepickerVal){} ? because I need to use the value of the datepicker as a condition to retrieve the modal update Dataset[i] again.
2.The data enters function index or function OrderData, and finally returns a new dataset[], will this help me refresh the page, or should I do something like $('#something').empty $('#something').append() in ajax success:function to update my object and its {{$DataSet[$i]->name}} {{$DataSet[$i]->number}} number?
You have 3 ways to accomplish this
Page reload
Reload the page and send query string in the url eg: "/yourpath?date=" + $date, then in your controller:
window.location.href = 'https://your.url/path?date=' + $('#datepicker').val();
class DayhomeController extend Controller{
public function index(){
$Dataset = Modal::all();
if(request()->get('date')){
$Dataset = $Dataset->where('date',request()->get('date'))
}
return view('DayHome')->with('DataSet',$DataSet)
}
Ajax return HTML
you could make a controller+page/view that only returns the HTML of your rendered data set.
then you can call this route/controller and just replace the html with jQuery:
$.ajax({
url: '/orderdata',
data: datepicker,
type: "get",
cache: false,
success: function (htmlReceived) {
$('#something').html(htmlReceived);
},
});})
Ajax + javascript rendiner library
you could also always get the Data set via ajax and instead create your render method locally using, react, alpineJS, svelte, vue or any other frontend rendering library or framework
*** This code does not follow best practises but tries to explain your problem
I have a div that has lots of posts which is created dynamically from the database. The div has input for comment facility as well. I have no problems in posting the comments and I do it using a POST method. Then I redirect to the page using return redirect('/'); method. But it links to the beginning to the page which doesn't create a good impression on the user. The user might be in the middle of the page and when he/she comments he will go to the beginning of the page and will have to scroll down again. Luckily, I have the divs with class equal to the post_id. So, isn't there any method to go to the post in which the user posted using that class?
attach the id with the url like /#post-id
Inside your contorller where you are processing and saving the comments:
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
public function yourCommentSaveFunction()
{
...
//Get the Post ID and store in $postid
return Redirect::to(URL::previous() . '#' .$postid);
}
This should work fine.
But the best way would be to use AJAX to post comments.
Edit (As request by OP)
THE AJAX METHOD
Controller will be something like:
public function saveComment(Request $request)
{
//you do the saving part..
...
$comment = $request->comment;
//after saving the comment return a json response
//you can also send other varibales like username, created at etc..
return Response::json(array(
'success' => true,
'comment' => $comment,
));
}
Route:
Route::post('/save-comment', [
'as' => 'save-comment',
'uses' => 'yourController#saveComment',
]);
And your View:
<form action="{{ route('save-comment') }}" class="comment-form">
<input type="text" name="comment">
<input type="submit" name="submit">
<input type="hidden" name="_token" value="{{ csrf_token() }}"
<div class="comment"></div>
</form>
<script>
$('.comment-form').submit(function(event){
event.preventDefault();
var comment = $this.val();
var token = $('.token').val();
var $url = "{{ route('save-comment') }}";
$.ajax({
url: route,
type: 'POST',
data: {_token: token, comment: comment},
dataType: 'JSON',
success: function (data) {
$(".comment").append('<div class="new-comment">' +data.comment +'</div>');
},
error: function(data) {
console.log("Something went wrong");
}
});
});
</script>
Please note: this is just a sample code.
I want to send drop-down list data from view to controller via AJAX as a form variable using post method.
I am able to send the drop-down list data from view to controller using get method and using route parameters.
Here is my view code snippet:
function drawChart(frmyear, toyear)
{
console.log(frmyear);
console.log(toyear);
var jsonData = $.ajax({
url: "get_salesthree/"+ frmyear + "/"+ toyear +"/",
dataType: 'json',
async: false
}).responseText;
console.log(jsonData);
Route code snippet:
Route::get('get_salesthree/{frmyear}/{toyear}', array('uses'=>'Analytics\DashboardController#get_salesthree'));
For security reasons I don't want to pass user input data using route parameters. Also I have multiple user input parameters which needs to send to controller hence above method is not feasible as well. Hence any other alternative solution available in this case?
Controller code snippet:
public function get_salesthree($frmyear, $toyear)
{
return \Response::json(Salethree::get_formatted_salesthree($frmyear, $toyear ));
}
Dropdownlist code snippet:
<label>From Date</label>
<select id="ddlfrmyear" name="frmyear" onchange="check(this);">
<option value="-1">Select Date </option>
#foreach ($date_lists as $date_list)
<option value="{{ $date_list}}">{{ $date_list}}</option>
#endforeach
</select>
JavaScript check function:
function check(sel)
{
document.getElementById('ddltoyear').disabled = !sel.selectedIndex;
var frmyear = document.getElementById('ddlfrmyear').value;
var toyear = document.getElementById('ddltoyear').value;
console.log(frmyear);
console.log(toyear);
if (toyear != '-1')
{
drawChart(frmyear, toyear);
//drawChart();
}
}
Now I am getting check function is not defined after changing ajax call as suggested. I am wondering what it the relation between on-select event of drop-down list and AJAX route?
This is just an example for your understanding, I hope this will guide you to get your functionality.
if you don't want to show your data/parameter in URL, then you can also use Ajax Post,
$.ajax({
type: 'POST'
url: "get_salesthree/",
data: yourForm.serialize()
dataType: 'json'
and in your routes, remove variable for query string, and make it like this.
Route::post('get_salesthree/', array('uses'=>'Analytics\DashboardController#get_salesthree'));
and in your controller
public function get_salesthree(Request $request){
$frmyear = $request->input('frmyear');
$toyear = $request->input('toyear');
//do your functionality as per your need
return \Response::json(Salethree::get_formatted_salesthree($frmyear, $toyear ));
}
Try this jquery answer:
js:
$('form').submit(function(e){
e.preventDefault();
var frmyear = $('#ddlfrmyear').val();
var toyear = $('#ddltoyear').val();
$.ajax({
type: 'POST'
url: "get_salesthree/",
data: {frmyear:frmyear ,toyear:toyear},
dataType: 'json',
success:function(data){
console.log(data);
}});
});
laravel:
Route::post('get_salesthree/', function(Request $request){
$frmyear = $request->input('frmyear');
$toyear = $request->input('toyear');
return \Response::json(Salethree::get_formatted_salesthree($frmyear, $toyear
});
I am building an application where users can upload projects. I am implementing a system where users can 'Like/Unlike' other projects. I am trying to use an AJAX call to save likes. Users are able to like projects on the detail page of a project (/projects/{id})
I have a table users, projects and likes. My plan is to save the likes in the likes table obviously so a record looks like this: id, user_id, project_id. In the future I can do a COUNT query and find out how many likes each project has, etc.
For some reason when I click on the like button my application gets stuck and keeps loading until it crashes.
My files:
Ajax call
$(document).ready(function(){
console.log("js loaded");
$('#likeform').on('submit', function(e) {
console.log("like submitted");
e.preventDefault();
$.ajax({
url: $(this).parent().attr('action'),
type: "post",
data: {'_token': token, 'user_id': $('input[name=user_id]').val(), 'project_id': $('input[name=project_id]').val()},
success: function(data){
alert(data);
}
})
});
});
My Form
{!! Form::open(array('url'=>'projects/'.$project->id.'/like','method'=>'POST', 'id'=>'likeform')) !!}
<input type="hidden" id="token" value="{{ csrf_token() }}">
{!! Form::Submit('Like', array('class'=>'send-btn')) !!}
{!! Form::close() !!}
My Routes:
Route::get('/', 'LikeController#index');
Route::post('projects/{id}/like', 'LikeController#like');
My like function in the LikeController:
public function like()
{
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
}
The
gets stuck and keeps loading until it crashes
part may be related to the fact that the ajax post expects some kind of response, but you are not responding at all in your controller. Try something like
public function like()
{
if(Request::ajax()) {
$data = Input::all();
return Response::json([
'error' => false,
'insertedData' => $data
], 200);
}
}
Remenber to use Response in your controller. Now you are returning something to the ajax call and you should be able to access $data
success: function(data){
alert(data.insertedData);
}
Are you experiencing the same behaviour? If not you can move on and perform the actual db insert.
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"