I use celery and redis as backend for my async tasks. I like to paginate my results in the template.
I use Javascript (ajax Requests) to request the data.
Now I like to paginate the results also with Javascript after request the data.
I hope someone can help me.
Thats my javascript:
$(document).ready(() => {
console.log('Sanity Check!');
});
$('.button').on('click', function() {
$.ajax({
url: '/tasks/',
data: { type: $(this).data('type'),},
method: 'POST',
})
.done((res) => {
getStatus(res.task_id);
getStatusConfluence(res.task_id_confluence);
})
.fail((err) => {
console.log(err);
});
});
function getStatus(taskID) {
$.ajax({
url: `/tasks/${taskID}/`,
method: 'GET'
})
.done((res) => {
num_hosts = res.value.length
for (i=0; i < num_hosts; i++){
const html = `
<tr>
<td>${res.value[i]['name']}</td>
<td>${res.value[i]['OK']}</td>
<td>${res.value[i]['WARN']}</td>
<td>${res.value[i]['CRIT']}</td>
</tr>
`
$('#result').prepend(html);
}
const taskStatus = res.task_status;
if (taskStatus === 'SUCCESS' || taskStatus === 'FAILURE') return false;
setTimeout(function() {
getStatus(res.task_id);
}, 1000);
})
.fail((err) => {
console.log(err)
});
}
function getStatusConfluence(taskID) {
$.ajax({
url: `/tasks/${taskID}/`,
method: 'GET'
})
.done((res) => {
num_hosts = res.value.length
for (i=0; i < num_hosts; i++){
const html = `
<tr>
<td>${res.value[i]['title']}</td>
</tr>
`
$('#result_confluence').prepend(html);
}
})
.fail((err) => {
console.log(err)
});
}
Related
import { getCustomer } from './Customers';
let optionItems=[];
export const LOV: React.FunctionComponent = () => {
const loadCustomer = async () => {
const data = await getCustomer();
for (var i=0; i < data.value.length ; ++i)
{
optionItems.push({
key: data.value[i].CustomerId,
text: data.value[i].CustomerName
});
}
}
useEffect(() => {
loadCustomer();
}, [])
return (
<SearchableDropdown options={optionItems}/>
);};
Code in Customers.tsx
export const getCustomer = async (): Promise<any> => {
const response = await
$.ajax({
url: apiURL,
type: "GET",
headers: headers,
data: null,
cache: false,
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Bearer ' + accessToken);
}
})
.done( function (data) {
return data;
})
.fail(function (jqXHR) {
if (jqXHR.status == 401) {
promptAuth(jqXHR.getResponseHeader("WWW-Authenticate"));
}
else {
console.log("NOT 401");
}
});
return response;
}
I'm trying to populate a dropdown dynamically using a promise. I'm using Fluent-react Dropdown. getCustomer() loads values to const data. However, I can't see any values in the dropdown even though data is not null. Please help.
Fluent Dropdown => https://developer.microsoft.com/en-us/fluentui#/controls/web/dropdown
Your optionsItems need to be reactive. Try using useState-hook
export const LOV: React.FunctionComponent = () => {
const [optionItems, setOptionItems] = useState([]);
const loadCustomer = async () => {
const data = await getCustomer();
const options = [];
for (var i=0; i < data.value.length ; ++i)
{
options.push({
key: data.value[i].CustomerId,
text: data.value[i].CustomerName
});
}
setOptionItems(options)
}
useEffect(() => {
loadCustomer();
}, [])
return (
<SearchableDropdown options={optionItems}/>
);};
Please make sure your data.value[i].CustomerId and data.value[i].CustomerName are valid strings. You need to supply string, but it looks like your API call returns null there. After you fix this problem, together with Stutje's solution your app should start to work.
When I update ref() array, q-table not updating.
I am initiating the rows ref with the "getApplications()" function.
Then when i call the reviewed() function from a line in the q-table, the table does not update with new data after i update the rows ref.
<q-table
v-model:selected="selected"
:loading="loading"
title="Applications"
:rows="rows"
:columns="columns"
row-key="id"
></q-table>
<script setup>
import { api } from "boot/axios";
import { ref } from "vue";
const columns = ref([ ........]);
let rows = ref([]);
getApplications();
function getApplications() {
api({
method: "get",
url: "/webdata/_partition/apply/_design/apply-list/_view/apply-list",
})
.then((response) => {
var row = fncArrayAll(response.data.rows);
rows.value = row;
})
.catch((e) => {
console.log("e: ", e);
alert(e);
})
.finally(() => {
loading.value = false;
});
}
function reviewed(prop) {
loading.value = true;
api({
method: "get",
url: "/webdata/" + prop.row._id,
})
.then((response) => {
var newData = response.data;
newData.office.reviewed = !newData.office.reviewed;
api({
method: "put",
url: "/webdata/" + prop.row._id,
data: newData,
})
.then((response) => {
console.log("new response: ", response);
})
.catch((e) => {
console.log("e: ", e);
alert(e);
})
.finally(() => {
loading.value = false;
});
})
.catch((e) => {
console.log("e: ", e);
alert(e);
})
.finally(() => {
loading.value = false;
});
}
function fncArrayAll(items) {
var filtered = [];
for (var i = 0; i < items.length; i++) {
filtered.push(items[i].value);
}
// console.log(filtered);
return filtered;
}
</script>
When rows is updated in the reviewed function, the q-table is not updated.
Thanks for any help
I'm trying to return data from a called function that has a promise in it. How do I get the data into the variable?
var job = fetchJob(data[k].employer);
function fetchJob(name) {
var test = 'null'
fetch(`https://${ GetParentResourceName() }/jsfour-computer:policeFetchJob`, {
method: 'POST',
body: JSON.stringify({
type: 'policeFetchJob',
data: {
'#name': name,
}
})
})
.then( response => response.json() )
.then( data => {
if ( data != 'false' && data.length > 0 ) {
return data
})
return null;
};
You can get the promise value with async/await or with Promises, bellow I do an example with this two techniques:
function fetchJob(name) {
return fetch(`https://${GetParentResourceName()}/jsfour-computer:policeFetchJob`, {
method: "POST",
body: JSON.stringify({
type: "policeFetchJob",
data: {
"#name": name,
},
}),
})
.then((response) => response.json())
.then((data) => {
if (data != "false" && data.length > 0) {
return data;
}
});
}
async function getResponseWithAsyncAwait() {
const job = await fetchJob(data[k].employer);
}
function getResponseWithPromises() {
fetchJob(data[k].employer).then((data) => {
const job = data;
});
}
I am new to the web development. I am using react.js.So, Here I want to use the async/awaitfor the API call. I am using axios.
Now,
what I have is like
export function fetchToken(bodyjson) {
return (dispatch) => {
let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
return post(url, bodyjson)
.then((response) => {
if (response.status === 200) {
localStorage.setItem('user', bodyjson.userName);
localStorage.setItem('access_token', response.payload.access_token);
history.push('/');
dispatch({
type: LOGIN_SUCCESS,
data: response.payload,
})
}
else {
dispatch({
type: LOGIN_FAILED,
data: response.status,
});
}
})
}
}
and my post service is like,
export const post = (url, post_data) =>
axios.post(
apiGatewayEndpoint.apiGatewayEndpoint + url,
post_data,
{
headers: {
"Authorization": localStorage.getItem("access_token") !== null ? `Bearer ` + localStorage.getItem("access_token") : null,
"Content-Type": "application/json"
}
}
).then(data => {
if (data.status === HttpStatus.OK) {
return {
status: data.status,
payload: data.data
};
}
}).catch(err => {
return {
status: err.response.data,
payload: null
};
});
Now, I want to use the async await over here. I am very confused between this. I have gone through lots of the tutorials.
I want to call an API immediately after the login. on that basis I want to redirect user to the diff pages.
So, can any one help me with this async-await
THANKS:-)
Now I am using it like,
export function fetchToken(bodyjson) {
return async (dispatch) => {
let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
let response = await post(url, bodyjson)
if (response.status === 200) {
localStorage.setItem('user', bodyjson.userName);
localStorage.setItem('access_token', response.payload.access_token);
let fetchJd = FETCH_JD_ROOT_URL + page + "&" + size;
let newApiResponse = await get(fetchJd)
if (newApiResponse.status === 200) {
dispatch({
type: LOGIN_SUCCESS,
data: response.payload,
})
dispatch(sendUserJd(newApiResponse.payload));
}else {
dispatch({
type: LOGIN_FAILED,
data: response.status,
});
}
}
else {
dispatch({
type: LOGIN_FAILED,
data: response.status,
});
}
}
for get requests, you can use params to send data etc etc.
export const getData = async () => {
try {
const { data } = await axios({
method: 'get', //you can set what request you want to be
url: `yoururl`,
params: {
// key values pairs
}
headers: {
'token': token
}
});
// run some validation before returning
return data;
} catch (e) {
console.log(e);
return .. some error object;
}
};
for post request
export const getData = async (params) => {
try {
const { data } = await axios({
method: 'post', //you can set what request you want to be
url: `url`,
data: params,
headers: {
'x-auth-Token': token
}
});
// run some validation before returning
return data;
} catch (e) {
console.log(e);
return .. some error object;
}
};
error object example
{
status: 'error',
message: 'failed with something'
}
then you can call any api like this,
async componentDidMount() {
const data = await getData();
if(data.status === 'Something') {
// do something
}
}
You dont exactly need async await for this purpose.
With then chain approach
export function fetchToken(bodyjson) {
return (dispatch) => {
let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
return post(url, bodyjson)
.then((response) => {
if (response.status === 200) {
localStorage.setItem('user', bodyjson.userName);
localStorage.setItem('access_token', response.payload.access_token);
history.push('/');
dispatch({
type: LOGIN_SUCCESS,
data: response.payload,
})
//next api call
return post(newUrl, newBodyjson)
}
else {
dispatch({
type: LOGIN_FAILED,
data: response.status,
});
}
})
.then((newApiResponse) => {
//Do stuffs with new api response
})
}
}
But if you want to use async-await approach only
export function fetchToken(bodyjson) {
return async (dispatch) => {
let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
let response = await post(url, bodyjson)
if (response.status === 200) {
localStorage.setItem('user', bodyjson.userName);
localStorage.setItem('access_token', response.payload.access_token);
history.push('/');
dispatch({
type: LOGIN_SUCCESS,
data: response.payload,
})
let newApiResponse = await post(newUrl, newBodyjson)
//Do stuffs with new api response
}
else {
dispatch({
type: LOGIN_FAILED,
data: response.status,
});
}
}
}
Here is my code so far:
var Qs = require('qs');
function runRequest() {
return axios({
method: 'GET',
url: 'https://proxy.hackeryou.com',
dataResponse: 'json',
paramsSerializer: function (params) {
return Qs.stringify(params, { arrayFormat: 'brackets' })
},
params: {
reqUrl: `https://od-api.oxforddictionaries.com:443/api/v1/entries/en/bomb/synonyms;antonyms`,
proxyHeaders: {
'header_params': 'value',
"Accept": "application/json",
"app_id": "8ec64674",
"app_key": "b5a5e3f12d46fc718b916e1aaa1c3509"
},
xmlToJSON: false
}
}).then((result) => {
const synonym = result.data.results.map(res=>{
return res.lexicalEntries.map(secondResult=>{
return secondResult.entries.map(thirdResult=>{
return thirdResult.senses.map(fourthRes=>{
return fourthRes.synonyms.map(fifthRes=>{
turnArray(fifthRes.id)
return fifthRes.id;
})
})
})
})
});
})
.catch((error) => {
alert("Oops!");
});
}
function turnArray(list){
console.log(list)
}
runRequest();
What I am trying to do is turn this list (see image) into one array
Example: ["explosive", "incendiary_device"];
I would like to do this in my turnArray() function. How can I go about doing that?