quasar framework datatable laravel server pagination doesn't work - laravel-5

I only want pagination of datatable to work, I used code in documentation here it is:
request ({ pagination }) {
// we set QTable to "loading" state
this.loading = true
// we do the server data fetch, based on pagination and filter received
// (using Axios here, but can be anything; parameters vary based on backend implementation)
axios
.get(`/api/`+this.dataSource+`/?page=${pagination.page}`,{ headers: { Authorization: 'Bearer '.concat(localStorage.getItem('token')) } })
.then(response => {
// updating pagination to reflect in the UI
this.serverPagination = pagination
// we also set (or update) rowsNumber
this.serverPagination.rowsNumber = response.data.data.data.rowsNumber
// then we update the rows with the fetched ones
this.tableData = response.data.data.data
// finally we tell QTable to exit the "loading" state
this.loading = false
})
.catch(error => {
// there's an error... do SOMETHING
// we tell QTable to exit the "loading" state
this.loading = false
})
}
and in laravel api used this code
`/api/`+this.dataSource+`/?page=${pagination.page}`,{ headers: { Authorization: 'Bearer '.concat(localStorage.getItem('token')) } }
it returns data for the first page but datatable's arrow buttons are disabled, Despite the existence of other data.
thanks in advance

I found the solution here is it
request ({ pagination }) {
this.loading = true
axios
.get(`/api/`+this.dataSource+`?page=${pagination.page}`, { headers: { Authorization: 'Bearer '.concat(localStorage.getItem('token')) } })
.then(({ data }) => {
this.serverPagination = pagination
this.tableData = data.data.data
this.serverPagination.rowsNumber = data.data.total
this.loading = false
})
.catch(error => {
// there's an error... do SOMETHING
console.log(error)
// we tell QTable to exit the "loading" state
this.loading = false
})
}
in controller :
$any_data = $this->dataRepo->paginate(5);

Related

Form data sends empty request to the server

I am using vuejs and laravel to make a panel for admin
I understand i can not send any files without form data
so i gotta use formData like this
onSubmit(evt) {
evt.preventDefault();
this.emptyValidator();
let data = new FormData();
console.debug(this.form)
for (let input in this.form) {
data.append(input, this.form[input]);
}
data.append('image', this.image);
console.debug(data)
console.debug(this.image)
ProductDataService.update(this.id, data)
.then(response => {
let data = response.data;
if (data.data) {
Swal.fire('edited successfully', '', 'success');
}
})
.catch(error => {
if (error.response.status && error.response.status === 422)
this.handleValidation(error);
})
},
Note: i am using it in production mode
and when i try to dd in laravel it shows me empty
i did not have any problem with sending manual and formData in edit is a pain in my ass

How to fix 405 (Method Not Allowed) using vue js and laravel

Hi developers I have currently problem this project is an old project where the developer created. right now, we need to adjust some of there functionality. Right now I already extract the files to my localhost folder and now work without error on run watch and artisan serve. So the problem here is on login on the console it shows that http://localhost:8000/project/oauth/token 405 (Method Not Allowed), I really don't understand why this shows on the localhost however on the live server it works.
This project created using Vue Js and Laravel for the backend.
I will show you guys the authentication function.
Login Function:
authenticate(){
this.login_alert = false
this.$validator.validateAll().then((result)=>{
if(result){
const self = this;
const authUser = {}
try{
const data = {
username: this.email,
password: this.password,
remember: this.remember_me,
client_id: '2',
client_secret: 'secret',
grant_type : 'password',
scope : ''
}
this.$store.dispatch('AUTH_REQUEST',data)
.then(response=>{
console.log(data);
authUser.access_token = response.access_token
authUser.refresh_token = response.refresh_token
authUser.expires_in = response.expires_in
window.localStorage.setItem('project_token',JSON.stringify(authUser))
/*LOGIN*/
this.login_alert = false
this.loading = false
window.location.reload()
})
.catch(error=>{
this.login_alert = true
window.localStorage.removeItem('project_token')
this.loading = false
})
}catch(err){
console.log(err);
}
}
})
}
For the AUTH REQUEST:
AUTH_REQUEST:({commit,dispatch},obj)=>{
return new Promise((resolve,reject) => {
axios({
url: '/project/oauth/token',
data: obj,
method:'post',
config:'JSON'
})
.then(response=>{
if(response.status == 200){
resolve(response.data);
}
})
.catch(error=>{
reject(error);
localStorage.removeItem('project_token');
commit('AUTH_ERROR',error);
})
})
},
Hope some one experience this. thanks.
In my case, the compilation of the route should be specified properly, for example
async purchaseDelete(purchase) {
Csrf.getCookie();
return Api.delete('/api/purchase_settings/${purchase.id}');
},
the single tick on the axios delete method didnt represent correctly
async purchaseDelete(purchase) {
Csrf.getCookie();
return Api.delete(`/api/purchase_settings/${purchase.id}`);
}
When changed to back ticks, it responded with the correct result

Can the completion of one async call be sequenced before the start of another using useEffect?

I'm trying to use useEffect in my React app but also refactor things more modularly. Shown below is the heart of actual working code. It resides in a Context Provider file and does the following:
1. Calls AWS Amplify to get the latest Auth Access Token.
2. Uses this token, in the form of an Authorization header, when an Axios GET call is made to an API Endpoint.
This works fine but I thought it would make more sense to move Step #1 into its own useEffect construct above. Furthermore, in doing so, I could then also store the header object as its own Context property, which the GET call could then reference.
Unfortunately, I can now see from console log statements that when the GET call starts, the Auth Access Token has not yet been retrieved. So the refactoring attempt fails.
useEffect(() => {
const fetchData = async () => {
const config = {
headers: { "Authorization":
await Auth.currentSession()
.then(data => {
return data.getAccessToken().getJwtToken();
})
.catch(error => {
alert('Error getting authorization token: '.concat(error))
})
}};
await axios.get('http://127.0.0.1:5000/some_path', config)
.then(response => {
// Process the retrieved data and populate in a Context property
})
.catch(error => {
alert('Error getting data from endpoint: '.concat(error));
});
};
fetchData();
}, [myContextObject.some_data]);
Is there a way of refactoring my code into two useEffect instances such that the first one will complete before the second one starts?
You could hold the config object in a state. This way you can separate both fetch calls and trigger the second one once the first one finished:
const MyComponent = props => {
const myContextObject = useContext(myContext);
const [config, setConfig] = useState(null);
useEffect(() => {
const fetchData = async () => {
const config = {
headers: {
Authorization: await Auth.currentSession()
.then(data => {
return data.getAccessToken().getJwtToken();
})
.catch(error => {
alert("Error getting authorization token: ".concat(error));
})
}
};
setConfig(config);
};
fetchData();
}, [myContextObject.some_data]);
useEffect(() => {
if (!config) {
return;
}
const fetchData = async () => {
await axios
.get("http://127.0.0.1:5000/some_path", config)
.then(response => {
// Process the retrieved data and populate in a Context property
})
.catch(error => {
alert("Error getting data from endpoint: ".concat(error));
});
};
fetchData();
// This should work for the first call (not tested) as it goes from null to object.
// If you need subsequent changes then youll have to track some property
// of the object or similar
}, [config]);
return null;
};

Vue.js 2 & Axios - Filtering an api for a search feature

I'm trying to filter through a collection of films that i'm retrieving using axios. This is so i can compare it to a search string for a search feature. Everything works fine except when using the computed property it returns Cannot read property 'filter' of undefined" but when i check the vue dev tool it says that the computed property contains the array of films which doesn't really add up. The code is as follows.
created(){
this.fetchFilms();
},
methods:{
fetchFilms(page_url){
let vm = this;
// storing the page url
page_url = page_url || '/api/films'
axios.get(page_url)
.then(response => response)
.then(response => {
this.films = response.data;
vm.makePagination(response.meta, response.links);
})
.catch(err => console.log(err));
},
makePagination(meta,links){
let pagination = {
current_page: this.films.meta.current_page,
last_page: this.films.meta.last_page,
next_page_url: this.films.links.next,
prev_page_url: this.films.links.prev
}
this.pagination = pagination;
}
},
computed: {
filteredFilms () {
return this.films.data.filter((film) => {
return film.film_name.toLowerCase().match(this.searchString.toLowerCase())
})
},
}
This is how the data is returned
films:Object
data:Array[10]
links:Object
meta:Object
Any help is appreciated.
You're probably accessing filteredFilms before the request is done. I don't see any code to wait for the request. You could make filteredFilms check if the data is there and return an empty list if it isn't.

VueResource Vue.http.get Response Status Code 0

im having this issue where i send a request to the API to retrieve all users, the login function is called(index.vue) when called it tries to go to api/users/all which in this case should return all the users in that collection.
using Postman the API returns the correct results and if i console.log the output in the routeUsers before i send the response back, it outputs all the correct data to the console
when it returns to index.vue, the response status code is 0.
ive had a look online and some things are mentioning about CORS Headers but i dont think thats applicable to me and other things about the response has been cancelled,
can anyone shed some light on this for me and help me try to fix it?!
API main.js
var app = express();
var users = require('./routes/routeUsers');
app.use('/users', users);
module.exports = app;
api/models/users.js
var db = require('../Utilities/db')
module.exports.all = function(cb) {
var collection = db.get().collection('users')
collection.find().toArray(function(err, docs) {
cb(err, docs)
})
}
api/routes/routeUsers.js
var express = require('express')
, router = express.Router()
var user = require('../models/users');
router.get('/all', function(req, res) {
user.all(function(err, users) {
res.send(users);
})
})
Index.vue
export default {
data: function () {
return {
username: '',
password: '',
users: []
}
},
methods: {
login: function() {
Vue.http.get('/api/users/all').then((response) => {
console.log("SUCCESS",response);
this.users = response.body;
console.log(users);
}, function (error) {
console.log("Error", error.status); // handle error
});
}
}
};
The issue was that the inputs were in a form tag. removed Form tag and worked fine.

Resources