Route [SearchController.php] not defined. (View: - ajax

I have the following error: Route [SearchController.index] not defined. (View:
The code i am trying to execute is the following:
Search.blade.php
function fill_datatable(filter_distance = '', filter_hotel = '')
{
var dataTable = $('#customer_data').DataTable({
processing: true,
serverSide: true,
ajax:{
url: "{{ route('SearchController.index') }}",
data:{filter_distance:filter_distance, filter_hotel:filter_hotel}
},
columns: [
{
data:'distance',
name:'distance'
Now i have the following controller that should relate to this:
SearchController.php.
In my search controller i have the one method:
function index(Request $request)
{
if(request()->ajax())
{
if(!empty($request->filter_distance))
{
$data = DB::table('posts')
->select('distance', 'posts_t etc...
Web.php
Route::resource('search', 'SearchController');
Im not sure what is going on ?

If you consult php artisan route:list, you'll see that your route's name is search.index, not SearchController.index.
This should work:
url: "{{ route('search.index') }}",
or:
url: "{{ action('SearchController#index') }}",
Better yet, render your routes safe for use in JavaScript in the case of unexpected characters via the #json directive, like so:
url: #json(route('search.index')),

Your route name isn't going to be SearchController.index - please check documentation Resource Controllers for the corresponding route name - in your case to point to index action you'd use search.index, therefore
route('search.index')

Related

Laravel Websanova/Vue-Auth Login/Register Returning Undefined URL

So, I'm learning how to create Single Page Applications using Laravel & Vue.js, and I found this tutorial. I followed everything, I didn't change anything but I keep getting this undefined whenever I will login/register
I've double-triple checked everything.
Image showing the http://127.0.0.1:8080/undefined/api/auth/login -
https://imgur.com/LfpiMvS
Here's the code:
Auth.js
import bearer from '#websanova/vue-auth/drivers/auth/bearer'
import axios from '#websanova/vue-auth/drivers/http/axios.1.x'
import router from '#websanova/vue-auth/drivers/router/vue-router.2.x'
// Auth base configuration some of this options
// can be override in method calls
const config = {
auth: bearer,
http: axios,
router: router,
tokenDefaultName: 'recipe-lists',
tokenStore: ['localStorage'],
rolesVar: 'role',
registerData: {url: "auth/register", method: 'POST', redirect: '/login'},
loginData: {url: "auth/login", method: 'POST', redirect: '/', fetchUser: true},
logoutData: {url: "auth/logout", method: 'POST', redirect: '/', makeRequest: true},
fetchData: {url: "auth/user", method: 'GET', enabled: true},
refreshData: {url: "auth/refresh", method: 'GET', enabled: true, interval: 30}
}
export default config
api.php
Route::prefix('auth')->group(function () {
Route::post('register', 'Auth\AuthController#register');
Route::post('login', 'Auth\AuthController#login');
Route::get('refresh', 'Auth\AuthController#refresh');
Route::group(['middleware' => 'auth:api'], function(){
Route::get('user', 'Auth\AuthController#user');
Route::post('logout', 'Auth\AuthController#logout');
});
});
login.vue
<script>
export default {
data() {
return {
email: null,
password: null,
has_error: false,
isProcessing: false,
}
},
methods: {
login() {
// Get the redirect object
this.isProcessing = true
var redirect = this.$auth.redirect()
this.$auth.login({
body: {
email: this.email,
password: this.password
},
success: function() {
// Handle Redirection
const redirectTo = redirect ? redirect.from.name : this.$auth.user().role === 2 ? 'admin.dashboard' : 'dashboard'
this.$router.push('/')
},
error: function() {
this.has_error = true
},
rememberMe: true,
fetchUser: true
})
}
}
}
</script>
Can someone explain to me what's happening pretty noob here.
Thank you!
I expected the url to be http://127.0.0.1:8080/api/auth/login
I've faced a similar problem with the undefined part in URL.
The reason was that I did not have the MIX_APP_URL variable set up in my .env Laravel configuration file.
The way ${process.env.MIX_APP_URL} works is that an environment variable can be injected by Node at runtime, in this case the application url.
One reason we want the MIX_APP_URL in .env is that any developer using your application can easily set it up and only modify the MIX_APP_URL variable.
The other, very important reason is that the URL will differ for a local server and for production - in this case the solution to change it to a static URL would not work and would be prone to an error in a production environment.
One thing to notice though, when running the NPM watch task, the change of an .env variable does not apply immediately, the watch task has to be restarted.
It turns out my error was from my app.js, the code is:
axios.defaults.baseURL = `${process.env.MIX_APP_URL}/api`
After I changed it to:
axios.defaults.baseURL = `http://127.0.0.1:8000/api`
It worked, the undefined thingy is now gone. I didn't know why the first one didn't work but meh.
Reddit user /u/mrcat323 helped me get an answer in /r/vuejs.

Reload .twig template with AJAX

I am using https://github.com/gmrchk/swup in combination with Twig/Timber. It works great, however, I have realised that none of my if clauses work whenever I get to a new page, since SWUP can't read the if arguments from my twig files. (it is a JS library to load pages dynamically)
For example:
{% if fn('is_single') %}
<div class="progress"></div>
{% endif %}
wouldn't load at all when I initially load the page on a not single-post page.
My idea was to re-render header.twig (where the above mentioned if clause is) with an AJAX call.
The AJAX call looks like that:
function swupReplaceHeader() {
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'spx_replace_header',
},
success: function (output) {
console.log(output);
}
});
}
swupReplaceHeader();
document.addEventListener('swup:clickLink', swupReplaceHeader);
It is wrapped inside an event listener that fires every time I click on a link.
The WP function looks like that:
add_action('wp_ajax_spx_replace_header', 'spx_replace_header');
add_action('wp_ajax_nopriv_spx_replace_header', 'spx_replace_header');
function spx_replace_header()
{
$context = Timber::get_context();
Timber::render('templates/header.twig', $context);
wp_send_json_success(['AJAX is working']);
}
I added the send JSON message to test if my AJAX call is working.
Now, whenever I test the AJAX call without the Timber code it is working, but when I add the two Timber lines to the function, nothing happens - not even the JSON message appears. I tried Timber::compile as well without any luck.
I hope someone can help me..
Best,
Dennis
Answer posted by aj-adl on Github:
Hey Dennis,
You're making a call to wp-admin/admin-ajax.php, so conditionals like is_ajax() will return true but is_single() will definitely not.
Remember that PHP shuts down at the end of each request, discarding state etc, so the call to the admin-ajax.php script is a completely isolated process from the one that's delivered the initial markup for the page, and doesn't know what page it's being called from etc
For this reason, you'd want to pass in any data you'd need for conditionals, probably as a query string parameter.
PHP:
add_action('wp_ajax_nopriv_spx_replace_header', 'spx_replace_header');
function spx_safe_get_string( $key )
{
if ( ! isset( $_GET[ $key ] ) ) return '';
return sanitize_text_field( $_GET[ $key ] );
}
function spx_replace_header()
{
$context = Timber::get_context();
// Set this in the context, so we can access it in our twig file easily
$context[ 'type' ] = spx_safe_get( 'my_page_type' );
Timber::render('templates/header.twig', $context);
}
JS:
window.addEventListener('load', function() {
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'spx_replace_header',
my_page_type: 'single',
},
success: function (data) {
console.log(data);
}
});
})
Twig:
{% embed "objects/header.twig" with {'hamburger': 'hamburger--spring'} %}
{% endembed %}
{% if type == 'single' %}
<div class="progress"></div>
{% endif %}
{% embed "objects/header.twig" with {'id': '--sticky', 'hamburger': 'hamburger--spring'} %}
{% endembed %}

Display result of search within view

I have a page where I display all my clients. It uses paginate and only displays 16 clients per page. As such I have provided realtime search functionality.
When a search is perform, the option selected from the results triggers the following
select: function (event, ui) {
$.ajax({
url: "/returnClient",
type: "GET",
datatype: "html",
data: {
value : ui.item.value
},
success: function(data) {
$('.container').fadeOut().html(data.html).fadeIn();
}
});
}
That essentially calls the following function
public function returnClient(Request $request)
{
if($request->ajax()){
$selectedClient = $request->input('value');
$client = Client::where('clientName', $selectedClient)->first();
$html = View::make('clients.search', $client)->render();
return Response::json(array('html' => $html));
}
}
If I output the client variable above, I can see all the details for this particular client. This is then being passed to the partial clients.search.
Within clients.search, if I do
{{dd($client)}}
I get Undefined variable: client. Why does it not get the parsed Object within the view?
Many thanks
The issue is that you are improperly passing $client to the view. The Views documentation shows how to properly pass data via an associative array. The API docs confirm that an array is what is expected.
Do this instead:
public function returnClient(Request $request)
{
if($request->ajax()){
$selectedClient = $request->input('value');
$client = Client::where('clientName', $selectedClient)->first();
$html = View::make('clients.search', ['client' => $client])->render();
return Response::json(array('html' => $html));
}
}
Also, as a point of habit you may want to consider using dump() instead of dd().

Page error on page refresh Ember app

I have an ember app that I am developing and everything is working fine except when I refresh the page whilst on a nested route eg. /projects/1 I receive the following error:
Assertion Failed: You may not passundefinedas id to the store's find method
I am fairly sure this is to do with the way I have setup my routing but can't seem to reorganise them to fix it.
They look like so:
App.Router.reopen({
location: 'auto',
rootURL: '/'
});
App.Router.map(function() {
this.route('projects', { path: '/'});
this.route('project', { path: '/projects/:id' });
});
Any help would be awesome! Thanks.
My first suggestion for you would be to change :id segment do :project_id - it's how they define it in documentation. So your router code looks like:
App.Router.map(function() {
this.route('projects', { path: '/'});
this.route('project', { path: '/projects/:project_id' });
});
If this doesn't help, create:
App.ProjectRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('project', params.project_id);
},
});
If you still get error with passing undefined to store.find try to console.log(params) and see if project_id is defined there and matches value from URL.

Getting POST parameter on symfony 2.2 and Ajax

I am using Ajax.
And here is the Ajax-call part of my twig template,
$.post('{{path('acme_member_delScore')}}',
{data1: num }, //I assured that 'num' has right data in javascript
function(response){
if(response.code == 100 && response.success){//dummy check
//do something
console.log(response.id);
}
}, "json");
And my routing.yml contains,
acme_member_delScore:
pattern: /delScore
defaults: { _controller: AcmeMemberBundle:Default:delScore}
While the action in my Controller is defined as follow,
public function delScoreAction()
{
$request = $this->container->get('request');
$id = $request->query->get('data1');// but $id is null
// ...
Do you have any idea why my $id variable (in delScoreAction) is always set to null?
Is there anything I have to check?
Try something like this
$id = $request->request->get('data1');

Resources