Done this before in the past.
But having issues with this again
Trying to get the ids from a fb page using the api from fb
Here is an example of the outputted json.
{
"data": [
{
"created_time": "2019-01-10T05:50:49+0000",
"message": "hello world",
"id": "233542"
},
{
"created_time": "2019-01-10T05:50:48+0000",
"message": "hello world",
"id": "454524"
},
{
"created_time": "2018-12-24T06:19:31+0000",
"message": "hello world",
"id": "399434"
}
]
}
Script
var key = "(insert fb api here)";
<!-- facebook api get -->
var getkey = "https://graph.facebook.com/v3.2/(insert fb id here)/feed?access_token=" + key;
$.ajax({
type: 'GET',
url: (getkey),
contentType: 'application/json',
dataType:'jsonp',
responseType:'application/json',
xhrFields: {
withCredentials: true
},
headers: {
'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'GET',
'Access-Control-Allow-Headers':'application/json',
},
success: function(data) {
$.each(data, function (i, item) {
console.log(item[i].id);
});
},
error: function(error) {
console.log("error");
}
});
one way iv found that works is
console.log(item[0].id);
How ever this just console logs the first of the nested json,
Am I missing something?
Any help is appreciated.
try this :
$.each(data.data, function (i, item) {
console.log(item.id);
});
Related
I'm using ajax and javascript for a game and I created a server using json-server where I keep a db.json file with words that the user can input and become available in the game.
db.json
This is what the json file looks like
{
"words": [
{
"cuvant": "cuvant",
"id": 1
},
{
"cuvant": "masina",
"id": 2
},
{
"cuvant": "oaie",
"id": 3
},
{
"cuvant": "carte",
"id": 4
},
{
"cuvant": "fmi",
"id": 5
},
{
"cuvant": "birou",
"id": 6
},
{
"cuvant": "birou",
"id": 7
},
{
"cuvant": "canapea",
"id": 8
},
{
"cuvant": "pasare",
"id": 9
I managed to get the POST request (adding the words to the db.json) using this:
function addWord() {
var word = document.getElementById("input-name").value;
var info = {
cuvant: word
}
$.ajax({
url:'http://localhost:3000/words',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(info),
succes: function(info) {
console.log(info)
},
error: function(error) {
console.log(error);
}
})
}
This is what I tried for the GET request
But I'm not sure if it's correct.
And I also need a way to get only the value hold by the cuvant key and add it into an array.
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
contentType: "application/json",
succes: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}
I think your code is correct. It was just missing the "s" on "success":
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}
When I try to pass my json object for creating a task item and pass the content-type application/json-patch+json as well and the type PATCH i'm getting an erro: The request indicated a "Content-Type of \"\" for method type \"PATCH\" which is not supported. Valid content types for this method are application/json=patch+json. ".
It works fine when I call it in Postman with the same application type and type Patch. I'm trying to create a webpage and get this to call the service when I click a button on the form.
var newJson = '[{"op":"add","path":"/fields/System.Title","value":"JavaScript implementation for Microsoft Account"}]';
var oJson = JSON.stringify(newJson);
//AZURE URL
var url = "https://dev.azure.com/AIZ-GL-dryrun/375977db-f390-4aac-bc4d-808f51360f9a//_apis/wit/workitems/$task?api-version=5.1";
jQuery.support.cors = true;
$.ajax({
url: url,
async: true,
data: oJson,
type:'PATCH',
contentType: "application/json-patch+json;",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic "+btoa(username+':'+password));
},
success: function(data){
var myObject = JSON.stringify(data);
alert("RESULT: "+myObject);
},
error: function(err) {
alert(JSON.stringify(err))}
});
As Daniel pointed out, var url = "https://dev.azure.com/AIZ-GL-dryrun/375977db-f390-4aac-bc4d-808f51360f9a//_apis/wit/workitems/$task?api-version=5.1"
You were trying to use API with version 5.1. As you can see, this version is not supported with Team Foundation Server 2015.
Need to use version 2.x on TFS 2015 and try again. More detail about api version, kindly take a look at this official link-- REST API Versioning
Update, use post instead of patch and try again.
return $.ajax({
url: "https://{account}.visualstudio.com/DefaultCollection/{project}/_apis/wit/workitems/$Bug?api-version=1.0",
type: "POST",
headers: {
"Authorization": "Basic " + btoa("{user}:{password}"),
"X-HTTP-Method-Override": "PATCH",
"Content-Type": "application/json-patch+json; charset=utf-8"
},
dataType: 'json',
cache: false,
data: JSON.stringify(myData),
async: false,
error: function (jqXHR, textStatus, errorThrown) {
//alert(jqXHR.status + ': ' + errorThrown);
},
success: function (data) {
// alert(JSON.stringify(data));
}
});
Another way, you could also use Work item batch api instead:
For example:
http://[collection url]/_apis/wit/$batch?api-version=1.0
Body:
[
{
"method": "PATCH",
"uri": "/ScrumStarain/_apis/wit/workItems/$Product Backlog Item?api-version=1.0",
"headers": {
"Content-Type": "application/json-patch+json"
},
"body": [
{
"op": "add",
"path": "/fields/System.Title",
"value": "apip1"
},
{
"op": "add",
"path": "/id",
"value": "-1"
}
]
},
{
"method": "PATCH",
"uri": "/ScrumStarain/_apis/wit/workItems/$Task?api-version=1.0",
"headers": {
"Content-Type": "application/json-patch+json"
},
"body": [
{
"op": "add",
"path": "/fields/System.Title",
"value": "apip2"
},
{
"op": "add",
"path": "/id",
"value": "-2"
}
]
}
]
More information, you can refer to: Work item batch operations
I have a problem with jQuery UI autocomplete that I'm trying to resolve with a lot of research and only resolved it partialy. I've managed to make it work at all with this code:
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://wger.de/api/v2/exercise/?format=json",
type: "GET",
data: { name: request.term },
dataType: "json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item
}
}));
}
});
}
});
I'm working with open source API in JSON, here is an example:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 436,
"license_author": "Andrew Carothers",
"status": "1",
"description": "<p>1 Minute for each exercise</p>\n<ol>\n<li>Hold feet 6 inches off ground</li>\n<li>Crunches</li>\n<li>Side Crunches (L)</li>\n<li>Side Crunches (R)</li>\n<li>Heel Touches</li>\n<li>Plank Crunch</li>\n<li>Scissor Kicks</li>\n<li>Swim Kicks</li>\n<li>V Crunches</li>\n<li>Hold feet 6 in off ground</li>\n</ol>\n<p>Exercises can be substituted to vary workout</p>",
"name": "10 Min Abs",
"name_original": "10 Min Abs",
"creation_date": "2016-12-09",
"uuid": "3c5f6e1c-cb22-4a9f-a13e-d14afeb29175",
"license": 2,
"category": 10,
"language": 2,
"muscles": [],
"muscles_secondary": [],
"equipment": []
}
]
}
I want to get autocomplete suggestions with letters from "name" in JSON, but instead I've got whole JSON array, even with non-existing objects. I've already tried item.results[0].name, but everything I've got is TypeError: item.results is undefined. How to modify $.ajax to get "name" value of JSON object in autocomplete suggestions?
Thanks for any help.
does this work :
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://wger.de/api/v2/exercise/?format=json",
type: "GET",
data: { name: request.term },
dataType: "json",
success: function(data) {
response($.map(data.results, function(index,item) {
return {
label: item.name,
value: item.name
}
}));
}
});
}
});
I'm using the following function to load a DataTables table with data from the server. I would like to reload the table with different parameters on a click event only i cant work out how to do this. If i call reload it just reloads with the original parameters if i reinitialise the whole table it throws an error as the table already exists.
I have been looking into fnServerParams but cant work out if it would help or not.
If anyone can point me in the correct direction that would be great.
function LoadRiskProfileModalTable(userId, teamId, riskProfileClass) {
var params = {
userId: userId,
teamId: teamId,
riskProfileClass: riskProfileClass
};
var data = JSON.stringify(params);
//if (!$.fn.DataTable.isDataTable("#riskProfileTable")) {
var table = $("#riskProfileTable").DataTable({
"bProcessing": true,
"sAjaxSource": "WFMHome.aspx/GetRiskProfileDrillThroughDatatable",
"fnServerData": function (sSource, aoData, fnCallback) {
//aoData.push(JSON.stringify(params));
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": sSource,
"data": data,
"success": function (msg) {
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},
error: function (xhr, textStatus, error) {
if (typeof console == "object") {
appendAlert("errorAlertPlaceholder", xhr.responseText, 1, "danger");
console.log(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}
});
},
"columns": [
{ "data": "CaseHandler" },
{ "data": "caseAreaText" },
{ "data": "RiskProfileText" },
{ "data": "PassChecks" },
{ "data": "F1Checks" },
{ "data": "F2Checks" },
{ "data": "F3Checks" },
{ "data": "CurrentChecks" }
]
});
//}
//else {
// $('#riskProfileTable').DataTable().ajax.reload();
// }
};
If you just want to replace the data you have now by the data coming from the server, try to replace the success method by:
"success": function (msg) {
var json = jQuery.parseJSON(msg.d); //I assume it's the data set
var table = $("#riskProfileTable").DataTable();
table.rows.clear(); //clear the current data
table.rows.add(json).draw();
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},
I'm trying to display the json that i get and parse it in the success function of ajax.
What I have so far:
Ajax:
data = "Title=" + $("#Title").val() + "&geography=" + $("#geography").val();
alert(data);
url= "/portal/getResults.php";
$.ajax({
url: url,
type: "POST",
//pass the data
data: data,
dataType: 'json',
cache: false,
//success
success: function(data) {
alert(data);
}
});
getResults.php (JSON output):
{
"results": [
{
"DocId": 2204,
"Title": "Lorem ipsum dolor sit amet, consectetur",
"Locations": [
{
"State": "New York",
"City": ""
},
{
"State": "New York",
"City": "New York City"
}
],
"Topics": [
3,
7,
11
],
"PublicationYear": "2011",
"Organization": "New Yorks Times",
"WebLocation": "www.google.com",
"Description": "Lorem Ipsum"
}
],
"TotalMatches": 1
}
I expect the result in data to be the the json from getResults.php but instead I get [object Object].
I have also tried the code below but get no response:
success: function(data) {
var json1 = JSON.parse(data);
alert(json1);
}
since you're telling jQuery that you want dataType:'json', the ajax function parses the JSON response into an object for you. the result object you see should be an object with data matching the JSON response from your server. if you need the string version, try JSON.stringify(), otherwise you can just use the object as is: data['results'][0]['DocId'], etc
good luck!
Here is an example for your request : http://jsfiddle.net/5y5ea98n/
var echo = function(dataPass) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: dataPass,
cache: false,
success: function(json) {
alert(JSON.stringify(json));
}
});
};
$('.list').live('click', function() {
$.get("http://www.json-generator.com/api/json/get/bQxORzxQGG?indent=2", function(data) {
var json = {
json: JSON.stringify(data),
delay: 1
};
echo(json);
});
});
I tried some code relate to this and it worked successfully.
function ajaxToParseJson(){
AUI().use('aui-io-request', function(A){
A.io.request('${jsonAjaxURL}', {
dataType:'json',
method: 'post',
data: {
execute: 'JsonLogic',
numberVal:'Pass Json String Here if needed from Screen'
},
on: {
success: function()
{
var empName = this.get('responseData').name;
var id = this.get('responseData').id;
console.log("Name: "+empName);
console.log("Id: "+id);
/** Since return type of this function is bydefault Json it will return Json still if you want to check string below is the way**/
var data = JSON.stringify(this.get('responseData'));
alert(data);
}
}
});
});
}
I have an Employee Class with two fields id,name.