how to access ajax response data inside of data - ajax

0: description: "Highest Intent"intent_id: 1intent_level: "highest"num_of_accounts: 0__proto__: Object1:
1: {intent_id: 2, intent_level: "high", description: "High Intent", num_of_accounts: 0}
2: {intent_id: 3, intent_level: "medium", description: "Medium Intent", num_of_accounts: 0}
3: {intent_id: 4, intent_level: "low", description: "Low Intent", num_of_accounts: 0}length: 4__proto__: Array(0).
Here i need to access intent_level either "high" or "medium" or "low".
axios.get("/some_api/", {
async: false,
params: {
client_id: clientObj.id,
metric: "intent",
campaign_id: campaign_id,
from_date : moment.tz(this.state.intentStartDate, clientObj.timezone_name).format("YYYY-MM-DD"),
to_date : moment.tz(this.state.intentEndDate, clientObj.timezone_name).format("YYYY-MM-DD")
}
}).then(res => {
console.log(res);
console.log(res.data.metric_data);
console.log(res.data.metric_data);
console.log(res.data.campaign_id);
console.log(res.data.intent_level);
let intent_obj = new Object();
res.data.metric_data.forEach(
function (d) {
intent_obj[d.intent_level] = d.num_of_accounts
console.log("vvsv"+d.intent_level);
in1_level = d.intent_level;
}
);
});

Related

When I use intercept it doesn't click button whenever Other test block runs - Cypress

I have 2 selectbox country and city This selectboxs interdependent i
used intercept for city selectbox
before(() => {
cy.viewport(1280, 720);
cy.visit(url)
cy.url().should("include", url)
loginPageContent_.formEmailInput()
.type('user')
loginPageContent_.formPasswordInput()
.type('pass')
loginPageContent_.formButton()
.click();
});
beforeEach(() => {
cy.viewport(1280, 720)
})
it("wait the form elemnets", () => {
cy.wait(5000)
cy.visit(urlTwo)
cy.wait(5000)
cy.url().should("include", urlTwo)
})
it("select item in selectbox ", () => {
// click the country selectbox
cy.xpath('//countrySelecbox').click()
// select the country item in selectbox
cy.xpath('//countrySelecboxItem').click()
cy.intercept({
method: 'GET',
url: 'get-city-by-country/3',
}, {
statusCode: 200,
body: {
data: [{ id: 4, code: '34', countryId: 3, name: 'city1' }, { id: 5, code: '34', countryId: 3, name: 'city2' }]
},
}).as('interceptEndpoint')
cy.wait('#interceptEndpoint')
})
This code working and select the country selectbox and my city drop
is get my intercept citys (city1,city2)
enter image description here
and im add a anaother test block and my code not click the country
button.
note: ım sure this is not a scope problem
it("select item in selectbox ", () => {
// click the country selectbox
cy.xpath('//countrySelecbox').click()
// select the country item in selectbox
cy.xpath('//countrySelecboxItem').click()
cy.intercept({
method: 'GET',
url: 'get-city-by-country/3',
}, {
statusCode: 200,
body: {
data: [{ id: 4, code: '34', countryId: 3, name: 'city1' }, { id: 5, code: '34', countryId: 3, name: 'city2' }]
},
}).as('interceptEndpoint')
cy.wait('#interceptEndpoint')
})
it("Step 1: open selectbox ", () => {
cy.xpath("//citySelecbox").click()
})
enter image description here

How to detect click on chart js 3.7.1 axis label?

How to detect click on an axis label with chart.js
In the example bellow, I can only detect click on the graph itself
https://stackblitz.com/edit/ng2-charts-bar-template-qchyz6
You will need to implement a custom plugin that can listen to all the events of the canvas:
const findLabel = (labels, evt) => {
let found = false;
let res = null;
labels.forEach(l => {
l.labels.forEach((label, index) => {
if (evt.x > label.x && evt.x < label.x2 && evt.y > label.y && evt.y < label.y2) {
res = {
label: label.label,
index
};
found = true;
}
});
});
return [found, res];
};
const getLabelHitboxes = (scales) => (Object.values(scales).map((s) => ({
scaleId: s.id,
labels: s._labelItems.map((e, i) => ({
x: e.translation[0] - s._labelSizes.widths[i],
x2: e.translation[0] + s._labelSizes.widths[i] / 2,
y: e.translation[1] - s._labelSizes.heights[i] / 2,
y2: e.translation[1] + s._labelSizes.heights[i] / 2,
label: e.label,
index: i
}))
})));
const plugin = {
id: 'customHover',
afterEvent: (chart, event, opts) => {
const evt = event.event;
if (evt.type !== 'click') {
return;
}
const [found, labelInfo] = findLabel(getLabelHitboxes(chart.scales), evt);
if (found) {
console.log(labelInfo);
}
}
}
Chart.register(plugin);
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>
Adpatation for Angular with ng2-charts (chart-js v3.7.1)
Just use Chart.register
i.e. put the following functiion into component ngOnInit()
RegisterPlugin() {
Chart.register(
{
id: 'yAxisCustomClick',
afterEvent: (chart: Chart<'bar'>, event: {
event: ChartEvent;
replay: boolean;
changed?: boolean | undefined;
cancelable: false;
inChartArea: boolean
}) => {
const evt = event.event;
if (evt.type === 'click' && evt.x! < Object.values(chart.scales).filter(s => s.id === 'x')[0].getBasePixel()) {
const labelIndex = Object.values(chart.scales).filter(s => s.id === 'y')[0].getValueForPixel(evt.y!);
const label = Object.values(chart.scales).filter(s => s.id === 'y')[0].getTicks()[labelIndex!]?.label;
if (label) {
console.log('Do the stuff for', label)
}
}
}
}
);
}
Example in stackblitz udpated
https://stackblitz.com/edit/ng2-charts-bar-template-qchyz6

Cannot pass custom result from resolver to Graphql

I am trying to fetch data with sequelize with an attribute and pass it to graphql.
The result is fine in console but the graphql query is returning null for the attribute field.
my resolver
getUnpayedLessons: async (_, args, { models }) => {
const { Attendance, Student } = models;
return await Attendance.findAll({
include: {
model: Student,
},
where: {
fk_lessonsSerieId: { [Op.is]: null },
},
attributes: ["id", [sequelize.fn("count", sequelize.col("absenceFlag")), "unpayedLessons"]],
group: ["student.id"],
});
},
query
getUnpayedLessons {
id
unpayedLessons
student {
id
firstName
lastName
}
}
schema
type UnpayedLessons {
id: Int
unpayedLessons: Int
student: Student
}
extend type Query {
getUnpayedLessons: [UnpayedLessons]
}
and this is the console.log of the resolver when I run the query
[
attendance {
dataValues: { id: 2, unpayedLessons: 8, student: [student] },
_previousDataValues: { id: 2, unpayedLessons: 8, student: [student] },
_changed: Set {},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [Array],
includeNames: [Array],
includeMap: [Object],
includeValidated: true,
attributes: [Array],
raw: true
},
]
and from graphql
{
"data": {
"getUnpayedLessons": [
{
"id": 2,
"unpayedLessons": null,
"student": {
"id": 2,
"__typename": "Student"
},
"__typename": "UnpayedLessons"
},
]
}
}
Any idea how I can have unpayedLessons passed to graphql?
To debug this you need to check what is returned from DB, the shape:
const values = await Attendance.findAll({...
console.log( values );
// adapt structure to match query requirements
// finally return
return values;

laravel with jquery ajax populate select option with value

I have two questions
(
1. how to automatically select the current level_id and populate it to the select box
2. how do i can i fix this issue in modal when closing and re-open another modal the select option keeps on adding the previous data)
controller:
$stream = Stream::with('level')->findOrFail($uuid);
$levels =Level::all();
return response()->json(['stream'=>$stream,'levels'=>$levels,'status'=>true]);
Ajax Jquery
jQuery('body').on('click', '.open-modal', function() {
var stream_id = $(this).val();
$.get('streams/' + stream_id + '/edit', function(data) {
if (data.status == true) {
$.each(data.levels, function(i, level) {
$('#sel_level').append($('<option>', {
value: level.id,
text: level.name
}));
});
}
jQuery('#stream_id').val(data.stream.id);
jQuery('#stream_name').val(data.stream.name);
jQuery('#stream_code').val(data.stream.code);
jQuery('#btn-save').val("update");
jQuery('#streamEditorModal').modal('show');
})
});
Question 2 image
Json response;
levels: Array(2)
0: {id: 3, name: "Level 1", code: "LVL1", uuid: "U7iHTp2pyM843HwfJ3CEB66rrD2vKAJvBHcrRYSGgXvmSaWh6IN3dGu1vZl29CwKTlULAdzduTglYyRFmn6MdY9S2xLhWZkvhSz0", created_at: "2020-06-25T07:59:14.000000Z", …}
1: {id: 4, name: "Level 2", code: "LVL2", uuid: "HZMe0wtyHfJrInriw4bA1ujOyZwZ7SkrSt37ZK2hCOHqSyki2b1Ysx2GBs8AU7oDemub2KmDNHBBiQhVaTkxyDAv7EXnUZ7O6DDi", created_at: "2020-06-25T07:59:25.000000Z", …}
length: 2
__proto__: Array(0)
status: true
stream:
code: "CLB3"
created_at: "2020-06-25T06:28:12.000000Z"
id: 17
level: {id: 3, name: "Level 1", code: "LVL1", uuid: "U7iHTp2pyM843HwfJ3CEB66rrD2vKAJvBHcrRYSGgXvmSaWh6IN3dGu1vZl29CwKTlULAdzduTglYyRFmn6MdY9S2xLhWZkvhSz0", created_at: "2020-06-25T07:59:14.000000Z", …}
level_id: 3
name: "Class B"
updated_at: "2020-07-02T07:58:39.000000Z"
uuid: "cq44VJZSOjRk4bB3S1Oz7UGX4yTPVHLnMvKYX648yVz1etQjj7obvzNuI9ExYfMCivMkuwNSSokmy82xvFPEAalhpmM2kFIhNPra"
_
how to automatically select the current level_id and populate it to the select box
To fix this issue you will need to reset the select element html content before appending new children like so:
before the jQuery $.each loop just add
$('#sel_level').html('');
how do i can i fix this issue in modal when closing and re-open another modal the select option keeps on adding the previous data)
To automatically select the current level you can check if the stream.level_id in the response match the current level id inside the loop like so:
$.each(data.levels, function(i, level) {
$('#sel_level').append($('<option>', {
value: level.id,
text: level.name,
selected: level.id == data.stream.level_id
}));
});
Fina code
jQuery('body').on('click', '.open-modal', function() {
var stream_id = $(this).val();
$.get('streams/' + stream_id + '/edit', function(data) {
if (data.status == true) {
$('#sel_level').html('');
$.each(data.levels, function(i, level) {
$('#sel_level').append($('<option>', {
value: level.id,
text: level.name,
selected: level.id == data.stream.level_id
}));
});
}
jQuery('#stream_id').val(data.stream.id);
jQuery('#stream_name').val(data.stream.name);
jQuery('#stream_code').val(data.stream.code);
jQuery('#btn-save').val("update");
jQuery('#streamEditorModal').modal('show');
})
});

Normalize linked ids

I have a weird set of data here.
const data = {
profiles: [
{ name: 'Joe', photos: [1, 2, 3] },
{ name: 'Ryan', photos: [2] },
{ name: 'Bob', photos: null }
],
linked: {
photos: [
{ id: 1, url: 'http://blah' },
{ id: 2, url: 'blah' },
{ id: 3, url: 'asdf' }
]
}
}
I get all the profiles like this:
const { entities } = normalize(data, {
profiles: [ Profile ]
});
But I want to replace the photos id array with the entries from linked.photos, is this possible? Or does it require post processing? I am currently doing custom post processing.
I'm not sure that normalizr is the best aproach for your task, but something like this will work
const photoSchema = new schema.Entity('photos', {});
const normalized = normalize(data.linked.photos, [photoSchema]);
const profileRawSchema = new schema.Entity('profiles', {}, {idAttribute: 'name'})
const profileSchema = new schema.Entity('profiles', {
photos: [photoSchema]
}, {idAttribute: 'name'});
const normalizedProfiles = normalize(
data.profiles,
[profileRawSchema]
);
normalized.entities.profiles = normalizedProfiles.entities.profiles;
// here is what you want
const desiredResult = denormalize(normalizedProfiles.result, [profileSchema], normalized.entities);
Docs for denormalize

Resources