I don't have idea how can i deleted all completed tasks from my json file and my app view:
json:
{
"list": [
{
"name": "Cleaning",
"desc": "by me",
"date": "11-3-2018 13:38",
"active": "false",
"id": 1
},
{
"name": "Wash the dishes",
"desc": "by me",
"date": "11-3-2018 23:11",
"active": "true",
"id": 2
},
{
"name": "Training",
"desc": "go with bro",
"date": "15-1-2016 23:41",
"active": "false",
"id": 3
}
]
}
I would like to deleted all tasks - active: false by one click button.
I have to use XMLHttpRequest.
You can loop through your JSON variable then have a condition on checking the active key. If its true then remove it. You can use splice to remove elements from an array. Then send it to your server side or etc.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
You will need to go server side to change the content of files, which I think you want to do.
Using JS and PHP you would get something like:
For the JS:
$("#yourButtonId").on('click', function(){
//Get the JSON file
var request = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
//Go over all tasks and remove if active is set to false
for (var i = 0; i < jsonObj.length; i++) {
if(jsonObj.list[i].active == "false"){
delete jsonObj.list[i];
};
}
//Send the updated json file as string to PHP
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "yourphpfile.php");
xmlhttp.send(JSON.stringify(jsonObj));
}
}
request.open("GET", "urlToJson.json", false);
request.setRequestHeader("Content-type", "application/json")
request.send(null);
});
For the PHP:
//Get your updated json string
$theJson = $GET['jsonObj'];
//Write the updated json string to the file
$myfile = fopen("urlToJson.json", "w") or die("Unable to open file!");
fwrite($myfile, json_encode($theJson));
fclose($myfile);
Try this :
var jsonObj = {
"list": [{
"name": "Cleaning",
"desc": "by me",
"date": "11-3-2018 13:38",
"active": "false",
"id": 1
},
{
"name": "Wash the dishes",
"desc": "by me",
"date": "11-3-2018 23:11",
"active": "true",
"id": 2
},
{
"name": "Training",
"desc": "go with bro",
"date": "15-1-2016 23:41",
"active": "false",
"id": 3
}
]
};
function removeCompletedTask() {
var resJson = jsonObj.list.filter(item => item.active == "true");
console.log(resJson);
}
<input type="button" value="Remove" onClick="removeCompletedTask()"/>
I use only json server (without php file)
If I want to delete single task I do this code
function deleteTask(task) {
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url + "/" + task.dataset.id, true);
xhr.onload = function() {
var json = JSON.parse(xhr.responseText)
if (xhr.readyState == 4 && xhr.status == 200) {
task.parentNode.parentNode.removeChild(task.parentNode);
}
}
xhr.send(null);
}
I did checkbox to change active my tasks and i would like to delete all of them i try something like this:
function clearTasksCompleted(task) {
var taskCompleted = task.parentElement.parentElement.querySelectorAll('li');
var completed = [];
for(let i =0; i<taskCompleted.length; i++){
if(taskCompleted[i].querySelector('.checkbox').checked)
{
completed.push(taskCompleted[i]);
}
}
for (let i=0; i<completed.length; i++) {
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url + "/" + completed[i].dataset.id, true);
xhr.onload = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
completed[i].parentNode.removeChild(completed[i])
}
}
xhr.send(null);}}
`
and this deleted tasks from json but dont render my page automatically, only after preload i don't see completed tasks
Related
I am calling from an API to get the response in json format. I would like to loop through that response and only get the data once as it brings up results twice.
var url = "api call";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Authorization", "Bearer $token");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
Response in json I get is:
{
"next": "url",
"data": [
{
"profile_id": "00000000-0000-0000-0000-000000012f44",
"value": {
"signal": 0.61,
"connection": "radio_low_power",
"profile_id": "00000000-0000-0000-0000-000000013ee4"
},
"timestamp": "2022-07-22T14:52:37.359000Z",
"type": "seen_device"
},
{
"profile_id": "00000000-0000-0000-0000-000000012f44",
"value": 0.61,
"timestamp": "2022-07-22T14:52:37.359000Z",
"type": "connection_signal"
},
{
"profile_id": "00000000-0000-0000-0000-000000012f44",
"value": {
"signal": 0.58,
"connection": "radio_low_power",
"profile_id": "00000000-0000-0000-0000-000000013ee4"
},
"timestamp": "2022-07-22T14:37:32.096000Z",
"type": "seen_device"
},
...]}
I would like to loop and show only the type:"seen_device", value, timestamp.
This is what i've tried so far to loop the data:
for(let i = 0; i < xhr.length; i++) {
let obj = xhr.responseText[i];
console.log("hello");
console.log(xhr.responseText.data);
}
}};
Because you looping async data, means you are trying to loop when data is not present, you need to add check if the response is not undefined and data on which you want to loop should have length
putting a sample code
function loopOverDat(){
response && response.length && response.forEach(item => .....);
}
I have an API which give me a JSON file like this :
(I edited my post.i hope it can help)
{
"events": {
"Israel Liga Bet South": [
{
"id": 47,
"league_name": "Israel Liga Bet South",
"home_team": "Otzma FC Holon",
"away_team": "Beitar Ramat Gan"
}
],
"Israel Liga Bet North": [
{
"id": 46,
"league_name": "Israel Liga Bet North",
"home_team": "Bnei HaGolan VeHaGalil",
"away_team": "Maccabi Maalot Tarshiha"
}
],
"India Bangalore Super Division": [
{
"id": 40,
"league_name": "India Bangalore Super Division",
"home_team": "ASC",
"away_team": "South United"
}
]
}
}
i wrote this code :
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var events;
events = myObj.events;
Object.keys(events).forEach(function (key) {
var inPlayEvents = events[key];
inPlayEvents.forEach(element => {
var div = document.createElement('div');
div.innerHTML = "my html codes";
div.setAttribute('class', 'event-type');
document.body.appendChild(div);
});
});
}
};
xmlhttp.open("GET", "json.txt", true);
xmlhttp.send();
but it showing me all of the matches
I want to show the same league matches in the same <div>
how can I do it?
thanks for your help
First, your JSON is wrongly formatted and it wouldn't even parse. Assuming the JSON object is like this:
"Categories": {
"cat1": [
{
"id": 1,
"Category_name": "cat1",
"Name": "iphone6",
"Details": "packed",
}
],
"cat2": [
{
"id": 2,
"Category_name": "cat2",
"Name": "GalaxyS10",
"Details": "stock"
}
],
"cat1": [
{
"id": 3,
"Category_name": "cat1",
"Name": "iphone5s",
"Details": "stock"
}
]
}
As for but it showing me all of the products I want to show the same category products in the same div you need to change the following in your iterator code:
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var Categories;
Categories = myObj.Categories;
Object.keys(Categories).forEach(function(key) {
var Products = Categories[key];
// create your div here
var div = document.createElement('div');
div.innerHTML = '';
Products.forEach(element => {
//[! remove this] var div = document.createElement('div');
//[! concatenate instead of assigning it] div.innerHTML = "html codes here";
div.innerHTML += 'your html here';
div.setAttribute('class', 'category-type');
Why? Because in your code you are reassigning the HTML to a new div for every product. Since you want to display all the information for all products under each category in a single div, your code would not work as expected.
I'm trying to retrieve the amount of open tickets from the zendesk api for a specific user. However I can't seem to get it to work. I keep getting this error:
Uncaught TypeError: Cannot read property '500' of undefined
The json format:
{
"user": {
"id": 500,
"url": "https://zendesk/api/v2/users/500.json",
"name": "Random name",
"email": "not important",
"created_at": "2016-05-18T15:26:43Z",
"updated_at": "2018-07-04T06:23:35Z",
"time_zone": "Brussels",
"phone": null,
"shared_phone_number": null,
"photo": {
"url": "https://google.com",
"id": 504,
"file_name": "keep-calm-and-shut-up-im-your-system-administrator.png",
"content_url": "https://google.com",
"mapped_content_url": "https://google.com",
"content_type": "image/png",
"size": 3298,
"width": 80,
"height": 50,
"inline": false,
"thumbnails": [
{
"url": "https://google.com",
"id": 90752965,
"file_name": "not important",
"content_url": "https://google.com",
"mapped_content_url": "https://google.com",
"content_type": "image/png",
"size": 3298,
"width": 32,
"height": 20,
"inline": false
}
]
},
"locale_id": 1005,
"locale": "nl",
"organization_id": 501,
"role": "admin",
"verified": true,
"external_id": null,
"tags": [],
"alias": "",
"active": true,
"shared": false,
"shared_agent": false,
"last_login_at": "2018-07-04T06:23:35Z",
"two_factor_auth_enabled": null,
"signature": "",
"details": "",
"notes": "",
"role_type": null,
"custom_role_id": null,
"moderator": true,
"ticket_restriction": null,
"only_private_comments": false,
"restricted_agent": false,
"suspended": false,
"chat_only": false,
"default_group_id": 503,
"user_fields": {
"agent_ooo": false
}
},
"open_ticket_count": {
"500": 15
}}
This is my javascript code:
<script>
function getJSON(url) {
var resp ;
var xmlHttp ;
resp = '' ;
xmlHttp = new XMLHttpRequest();
if(xmlHttp != null)
{
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
resp = xmlHttp.responseText;
}
return resp ;
}
var gjson ;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?
include=open_ticket_count');
console.log(gjson.open_ticket_count["500"]);
</script>
Can someone help me out? I'm not sure of what I'm doing wrong (the zendesk urls are the correct urls in the actual script and they can access it)
TLDR: I need to retrieve the variable from: open_ticket_count from a json.
Thank you!
Your getJSON function will not wait for the request to actually go through. A function like this would return the responseText only once it's finished:
const getJSON = function(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
let status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
You can then use this to get the Zendesk JSON:
getJSON('https://zendesk.com//api/v2/users/me.json?include=open_ticket_count', (status, gjson) => {
console.log(gjson.open_ticket_count["500"]);
});
Hard to say exacty without rest of the environment but I assume this will work:
var gjson ;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?include=open_ticket_count'');
var jsonObj = JSON.parse(gjson); // assuming getJSON returns the json as string, this is async, make sure next row has the data needed on time or rewqork this as promise
console.log(jsonObj.open_ticket_count["500"]);
So basically call the entire JSON and then parse it from string to object before using it like object
The clue is in the error
Uncaught TypeError: Cannot read property '500' of undefined
Which says that gjson.open_ticket_count is undefined.
You haven't actually parsed the JSON and trying to get a property of a string not the parsed JSON.
Try parsing it first.
var gjson;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?include=open_ticket_count');
var gobj = JSON.parse(gjson);
console.log(gobj.open_ticket_count["500"]);
You need to parse the JSON in order to access it. Use below code
<script>
function getJSON(url) {
var resp ;
var xmlHttp ;
resp = '' ;
xmlHttp = new XMLHttpRequest();
if(xmlHttp != null)
{
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
resp = xmlHttp.responseText;
}
return resp ;
}
var gjson ;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?
include=open_ticket_count');
gjson = JSON.parse(gjson)
console.log(gjson.open_ticket_count["500"]);
</script>
I am trying to get data from alchemynewsapi through javascript. The sample data i receive is:
{
"status": "OK",
"totalTransactions": "68",
"result": {
"docs": [
{
"id": "ODU1MjM4MjM0NnwxNDQ5MDk0Mzgy",
"source": {
"enriched": {
"url": {
"title": "North Scituate observatory hosts workshop on telescopes",
"url": "http://www.providencejournal.com/article/20151201/entertainmentlife/151209982"
}
}
},
{
"id": "ODEzMzYxODU5MHwxNDQ5MDYyMjM0",
"source": {
"enriched": {
"url": {
"title": "Mob Programming Workshop",
"url": "https://www.eventbrite.com/e/mob-programming-workshop-tickets-19710798529"
}
}
},
"timestamp": 1449062234
}
],
"next": "MzY5OTc0NjQzNzI2MjMxNzM2N3xPREU1TnpnNU9EWXhPSHd4TkRRNU1EWTNPVFE1",
"status": "OK"
}
}
I am trying the following for retrieving title and url fields of the data:
var jsonData=getJSON('http://urlofapi').then(function(data) {
for(var i=0; i<data.result.docs.length; i++)
{
result.innerText = data.result.docs[i].source.enriched.url.title; //for retrieving the title field
}
}, function(status) { //error detection....
alert('Something went wrong.');
});
getJSON is a function i have created :
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
But it only displays me the last title of the data i.e here the "Mob..."
What needs to be done to retrieve all the titles if there are 100's of items?
It's quite normal, your code has:
result.innerText = data.result.docs[i].source.enriched.url.title; //for retrieving the title field
Which means you constantly replace the contents of resultwith a new title, so at the end, you display the last one.
You need to concatenate the data somehow, or use console.log if you're just trying to see the results before doing something more with them.
I have a problem with javascript, im calling an ajax method that returns this string:
{
"ObjectResponse": {
"Operation": "OK",
"Response": "SUCCESS",
"Message": "List of AAA Found",
"List": [
{
"keySource": "gat\/images\/images_set\/apple.jpg",
"idSiteKey": "1",
"text": "Apple"
},
{
"keySource": "gat\/images\/images_set\/cat.jpg",
"idSiteKey": "2",
"text": "Cat"
},
{
"keySource": "gat\/images\/images_set\/coffee.jpg",
"idSiteKey": "3",
"text": "Coffee"
},
{
"keySource": "gat\/images\/images_set\/dog.jpg",
"idSiteKey": "4",
"text": "Dog"
},
{
"keySource": "gat\/images\/images_set\/horse.jpg",
"idSiteKey": "5",
"text": "Horse"
},
{
"keySource": "gat\/images\/images_set\/police.jpg",
"idSiteKey": "6",
"text": "Police"
},
{
"keySource": "gat\/images\/images_set\/tree.jpg",
"idSiteKey": "7",
"text": "Tree"
}
]
}
}
I assing the content in this way:
xhr.onreadystatechange = ensureReadiness;
....
responseText = xhr.responseText;
If i try to parse it on javascript with:
response = JSON.parse(responseText);
if I acces a property such response.ObjectResponse.Operation I do get the right content.. but when I try to access the List it allways brakes
and if I try the same String but instead of calling the service I assign the content to a var it works I do can access the List
var myTemporalString ='{"ObjectResponse":{"Operation":"OK","Response":"SUCCESS","Message":"List of Keys Found","List":...';
response.JSON.parse(myTemporalString);
Any suggestion why this could be happening?
You can try this way,
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
try{
var mJsonData = JSON.parse(xhr.responseText);
}catch(err){
console.log(err);
alert(err);
return;
}
for(i=0;i<jsondata.ObjectResponse.List.length;i++){
console.log(jsondata.ObjectResponse.List[i].text);
console.log(jsondata.ObjectResponse.List[i].keySource);
console.log(jsondata.ObjectResponse.List[i]. idSiteKey);
}
}
}
}
Use a loop!
var array = response.ObjectResponse.List;
var len = array.length;
for(i=0; i<len; i++) {
//Use array[i] to access the list
array[i].keySource
array[i].idSiteKey
array[i].text
}