I am trying to create a search bar. With every input change, a fetch API is triggered, which calls function in my Controller:
app.js
document.querySelector('#search')
.addEventListener('input', event => {
if(!event.target.value) return;
fetch('/search' + '/' + event.target.value);
});
Controller
<?php
namespace App\Http\Controllers;
use MeiliSearch\Client;
class SearchController extends Controller
{
protected $client;
public function __construct()
{
$this->client = new Client('http://127.0.0.1:7700');
}
public function search($searchFor)
{
$indexes = $this->client->getAllIndexes();
$searchResult = ['test' => 'test'];
foreach($indexes as $index) {
$searchResult[$index->getUid()] = $index->search($searchFor)->getHits();
}
return response($searchResult);
}
}
Next, the Controller returns records for the given parameters and I want to catch them in JS and send them into blade component. Returning view() with results data in it is not an option since view won't rerender itself every time and that's why I am trying to do this through JS.
The reason I need that data inside blade is because I want to loop through it and display results under the search bar
Return json_encoded value from your controller and get the result in fetch callback function then access any element from within the page and render the data.
*I am assuming the app.js file is included in your blade file.
Related
I have a route,
Route::post('/shop', 'ShopController#index');
Route::resource('/shop', 'ShopController')->parameters(['shop' => 'slug']);
I want to filter products via price range.
this is my :
filter_data();
var sliderrange = $('#slider-range');
var amountprice = $('#amount');
function filter_data() {
var min_price = $("#min_price").val();
var max_price = $("#max_price").val();
console.log(min_price);
$.ajax({ url:"/shop", method:"GET",
data:{ min_price:min_price, max_price:max_price,},
success:function (data) { },
});
};
and this is the controller:
public function index(Request $request)
{
$min = $request->input('min_price');
$max = $request->input('max_price');
return view('front.pages.shop', ['products' => Product::where('status', 1)->whereBetween('price', ['min', 'max'])->latest()->paginate(15)]);
}
Apparently the problem is that the controller isnt returning the correct data (As far as i can tell.)
The first step in debugging such a issue is checking if the parameter youre using to query are actually filled.
This can be done like this:
dd($min, $max)
If the output of the dd function shows empty values the issue is withtin the ajax request.
If they are set you want to do the following:
public function index(Request $request)
{
$min = $request->input('min_price');
$max = $request->input('max_price');
$products = Product::where('status', 1)->whereBetween('price', ['min', 'max'])->latest()->paginate(15);
dd($products);
return view('front.pages.shop', ['products' => $products]);
}
Place your products in a variable and run the dd() function with the variable to see if you have data. When done debugging remove the dd() function.
If you have data the problem might be somewhere else.
Note:
If you want to get data you should actually use the GET method for the route instead of using the POST method.
Example:
Route::get('/shop', 'ShopController#index');
I hope this is a little push in the right direction, try debugging step by step to find the exact point where there might be a issue.
What exactly is the error message you're receiving in the browser?
If the problem is related to CORS and you're using Laravel 7 you should update the config/cors.php file so that it works with your project. (eg setting 'allowed_origins' => ['*']).
See documentation for details.
I am building a site what lets you build a time table (for school subjects) I wrote a component that fetches data from database and then calculates corect placement in time table
<div class="timetable col-lg-8">
<div class="rowT">
<div style="width : 16%">Day</div>
<div *ngFor="let head of timeTableHeader"
[style.width]="headerWidth">
{{head}}
</div>
</div>
<div *ngFor="let sublists of allData" class="rowT">
<div *ngFor="let sublist of sublists"
id="{{sublist[0]}}"
class="timetable-cell"
[style]="getMyStyles(sublist[1])"
(click)="showDetails($event,sublist[3])">
{{sublist[0]}}
</div>
</div>
now I wrote a form which allows somebody to edit particular subject(e.g. time changed or class room) it works fine it saves the changes in DB adn now I want to show these changes in my view I thought I just call the function that calculates subject placements in time table but that results in rendering the time table again and leaving the old one there.
#Component({
selector: 'time-table',
templateUrl: './timetable.component.html',
styleUrls: ['./timetable.component.css']
})
export class TimeTableComponent {
allSubjects: Array<Subject>;
headerWidth: string;
timeTableHeader: Array<string> = new Array();
allData: Array<Array<Array<string>>> = new Array<Array<Array<string>>>();
constructor(private http: Http) {
this.fetchAndMake(); //function that fetches data and calls other function
//to make calculations... too long and not sure if relevant
// so I wont post it here
}
fetchAndMake(){
this.allSubjects = new Array<Subject>();
let params : URLSearchParams = new URLSearchParams();
params.set('userName', this.authService.currentUser.userName);
let reqOption = new RequestOptions();
reqOption.params = params;
this.http.get(this.configurations.baseUrl + "/SubjectModel/TimeTable", reqOption).subscribe(result => {
this.makeSubjects(result.json());
});
}
updateSubject(subj){
let subject = subj as SubjectData;
this.http.post(this.configurations.baseUrl + "/SubjectModel/UpdateSubject",helper)
.subscribe();
this.editSubjectView = false;
this.fetchAndMake();
}
}
Thanks in advance for the help.
First you should not be fetching the data directly from the component but rather from a data service. When you use a data service and inject it into components that use it the data service is a singleton. Not sure if that solves your problem but in any case it is a design issue you should look into before you go any further down this road.
Also, you are calling the primary function in the constructor. The only thing you should be doing in the constructor is to inject the data service. You need to implement the OnInit interface and call your function that fetches the data from the data service you injected in the constructor in the ngOnInit() method.
Check out some of the many Angular 4 tutorials and look for examples of creating a data service, making it a provider in app.module.ts. Then in your component
import { Component, OnInit } from '#angular/core';
import { MyDataService } from '../shared/my-data.service';
....
export class TimeTableComponent Implements OnInit {
...
constructor(private _mydata: MyDataService) { }
ngOnInit(){
// call method in data service that fetches data and do whatever you need to
// with the returned result. Now everything will be available to your view
}
There is a chance that
this.fetchAndMake()
gets called before
this.http.post(this.configurations.baseUrl +
"/SubjectModel/UpdateSubject",helper)
.subscribe();
is complete in updateSubject function. Subscribe just initiates the call , if you want to ensure that the new data is updated only after the post is complete, edit the updateSubject() function as follows :-
updateSubject(subj){
let subject = subj as SubjectData;
this.http.post(this.configurations.baseUrl + "/SubjectModel/UpdateSubject",helper)
.subscribe(result =>{
this.allData = new Array<Array<Array<string>>>();
this.fetchAndMake();
});
this.editSubjectView = false;
}
I have a javascript file that reads the input from textbox inputs in MVC/AngularJS. The method looks like the following:
$scope.Clients_CW = {
....
}
function sendForm(data)
{
$scope.Clients_CW = data;
var submitData = registrationService.SaveFormData($scope.Clients_CW);}
I'm using the jQuery wizard with next, previous and finish buttons. This is in a different javascript file to the code above. My finish button looks like the following:
$($this.buttons.finish).click(function() {
if(!$(this).hasClass('buttonDisabled')){
if ($.isFunction($this.options.onFinish))
{
var context = { fromStep: $this.curStepIdx + 1 };
if (!$this.options.onFinish.call(this, $($this.steps), context))
{
return false;
}
}
else {
var frm = $this.target.parents('form');
if (frm && frm.length)
{
alert($scope.Clients_CW);
frm.submit();
}
}
}
return false;
});
My question and problem is... how do I pass through the $scope.Clients_CW data to the finish button method or how do I call the sendForm(data) method and it's parameter in the finish button method?
You can very well use route params to pass data between states. Refer ngRoute. You could also store the data in $rootScope or $localStorage for example to use the data in multiple states. The latter step would also work if both the files are required for the same state.
so yeah... I have been searching for information about wiring up a dropdownlist so that it run a function in the controller with in the asp.net mvc tool.
$(function() {
$("#title").change(function() {
var selectedVal=$(this).val();
$.getJSON("UserController/YourAction",{ id: selectedVal } , function(result) {
//Now you can access the jSon data here in the result variable
});
});
});
Assuming you have an Action method called YourAction in your UserController which returns JSON
public ActionResult YourAction(int id)
{
//TO DO : get data from wherever you want.
var result=new { Success="True", Message="Some Info"};
return Json(result, JsonRequestBehavior.AllowGet);
}
so when I use this it's not doing anything???
I don't know what json is but I know I don't need my application to return any thing...
So this what was tried... In the edit form I have this element:
$('#RES_TEST_ID').change(function () {
var CurVID = $(this).val();
var IntVID = $(document.getElementById('BUVID')).val();
//alert(CurVID);
//alert(IntVID);
debugger
$.getJSON("TEST_REQUESTController/CheckCTEST", { Int_TEST_ID: IntTID, Cur_TEST_ID: CurTID }, function (result) {
});
});
In the Edit controller... I tired this part in both the Post and Get sections as the post did not state where you should add this in your controller:
public ActionResult CheckChangeTEST(int Int_TEST_ID, int Cur_TEST_ID)
{
if (Int_TEST_ID != Cur_TEST_ID)
{
var SelectedTEST = db.TEST_TEST_INFO.Find(Int_TEST_ID);
SelectedTEST.VI_STATUS = 1;
SelectedTEST = db.TEST_TEST_INFO.Find(Cur_TEST_ID);
SelectedTEST.VI_STATUS = 2;
var result = new { Success = "True", Message = "Some Info" };
return Json(result, JsonRequestBehavior.AllowGet);
}
return null;
}
For me, nothing happens... I try to see break points but they never go to the controller. Again I put this in both Post and get section under the edit control as I want this to run when the user edits changes the value in the dropdown list. Anyone have any Ideas they can share on what's going on here?
in your ajax call to your controller, you need to fix your route parameter for the Controller and for the action. The "Controller" name is automatically understood by the framework. So if you had FooController and you wanted to route to Bar action method, then you URL path would be "Foo/Bar".
$.getJSON("TEST_REQUESTController/CheckCTEST" ...
should be
$.getJSON("TEST_REQUEST/CheckChangeTEST" ...
also on your action you can decorate the action with the Get attribute decorator:
[HttpGet]
public ActionResult CheckChangeTEST(int Int_TEST_ID, int Cur_TEST_ID)
{
//your code
}
I have this code in my controller:
public function showAction($name)
{
$weights = "3,5,8,12,16,21";
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BreedrGeckoBundle:Gecko')->findOneByName($name);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Gecko entity.');
}
$deleteForm = $this->createDeleteForm($name);
return array(
'entity' => $entity,
'weights' => $weights,
'delete_form' => $deleteForm->createView(),
);
}
As you can see i have some data inside $weights which i would like to move into my show.html.twig file. Inside this file i am using {{dump(weights)}} which dumps that data fine. How can i use this data inside some jQuery as data points on my chart? I essentially need to transfer it into a javascript variable.
Currently you are just tranferring a string of numbers to the template...
if you want to use the variable in javascript you simply need to set the content of the twig-var to the js-var:
var myJsVar = {{ myTwigVar|default('') }}
this sets your js-var to the twig var or to an empty string if the variable can't be found or is empty...
PS: I don't know what you want to accomplish but I think an array of values would be more appropriate.