I know this question has been asked before, but I have tried just about every way to get this to work, AJAX, JQUERY, trying to use p5.js and none seem to work.
All I want to do is open my api, parse the JSON data, and log the first_name element of the JSON data
I am willing to use other functions to achieve the API result.
var apiURL = 'url';
var request1 = new XMLHttpRequest();
request1.open('GET', apiURL, true);
request1.onload = function()
{
if (this.status === 200)
{
console.log(JSON.parse(request1.responseText));
ting = JSON.stringify(JSON.parse(request1.responseType));
console.log(ting);
console.log(ting.first_name);
console.log(ting.first_name[0]);
}
};
request1.send();
the API url is https://api.hunter.io/v2/email-finder?domain=asana.com&first_name=Dustin&last_name=Moskovitz&api_key={API KEY}
the JSON data is
JSON Gyazo
This logs your first_name to the console using jQuery AJAX.
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$.ajax({
url: "https://api.hunter.io/v2/email-finder?domain=asana.com&first_name=Dustin&last_name=Moskovitz&api_key={API_KEY}",
type: 'GET',
}).done(function(dataObj) {
console.log(dataObj.data.first_name);
}).fail(function(xhr, textStatus, errorThrown) {
alert("Error: " + xhr.status + " " + textStatus);
});
</script>
You were almost there, first_name is under obj.data.first_name not obj.first_name
var apiURL = 'https://api.hunter.io/v2/email-finder?domain=asana.com&first_name=Dustin&last_name=Moskovitz&api_key=0409bb7315acf3ed037b22818e10fd51ff7be5e4';
var request1 = new XMLHttpRequest();
request1.open('GET', apiURL, true);
request1.onload = function()
{
if (this.status === 200)
{
var obj = JSON.parse(request1.responseText);
console.log(obj.data.first_name)
}
};
request1.send();
Related
I am trying to develop a component in Joomla 4. I have a simple button that should fire of a script to update the database.
I can make the call to the JavaScript ok, but the JavaScript does not appear to open the request URL, if anything it opens the current URL or refreshes the page. The script works fine outside of Joomla but not inside.
I have tried both the following, and the same thing happens:
*function buttonLike()
{
var xhr = new XMLHttpRequest();
var parentEl = this.parentElement;
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
console.log('Get Here OK' + parentEl.id);
xhr.open('GET', 'liked.php', true);
// Form data is sent appropriately as a POST request
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function ()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var result = xhr.responseText;
console.log('Never Here Result: ' + result);
}
if(xhr.readyState == 4 && xhr.status == 0)
{
console.log('Always Here');
}
};
xhr.send("id=" + parentEl.id);
}*
OR
function buttonLike()
{
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
var request = new Ajax(url, {
method: 'post',
update: some_div,
data: options,
onComplete: function (){
$('some_field').setHTML('I am finished!');
}
}).request();
Been going round in circles on this one, any help would be appreciated.
Hello i now using this php code for get steam nicknames
function EchoPlayerName($steamid){
$xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xml
if(!empty($xml)) {
$username = $xml->steamID;
echo $username;
}
}
or
$steam = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64", true);
$steamarray = json_decode($steam, true);
$name = $steamarray['response']['players'][0]['personaname'];
but i this using for listing players and loading page is slow
so i want this data load via javascript after full load page
any ideas?
API example
{"response":{"players":[{"steamid":"76561197964477177","communityvisibilitystate":3,"profilestate":1,"personaname":"The [G]amerX #ππ¨π‘π£πππ¬.π½πΏπΌ","lastlogoff":1558765863,"commentpermission":1,"profileurl":"https://steamcommunity.com/id/gamerxcz/","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013.jpg","avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_medium.jpg","avatarfull":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_full.jpg","personastate":0,"realname":"Community Owner","primaryclanid":"103582791433644720","timecreated":1076786008,"personastateflags":0,"loccountrycode":"CZ"}]}}
First, you should get Data using ajax of pure javascript or jquery. Then you should target an HTML element that you want to fill it using this retrieved data. Imagine element with ID target.
jQuery:
$(document).ready(function () {
$.ajax({
url: "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64",
}).done(function (data) {
var json = JSON.parse(data);
$('#target').text(json['response']['players'][0]['personaname']);
});
});
pure javascript:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64');
xhr.onload = function () {
if (xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
document.getElementById('target').innerHTML = json['response']['players'][0]['personaname'];
} else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
Remember to place these scripts at the end of your document.
I'm trying to perform an asynchronous Ajax sparql query on dbpedia with Firefox but I got a weird result and I'm not able to figure out the error. It all seems to work (and it actually works in Chrome, Edge and Internet Explorer) but if it's performed in Firefox the page keeps loading indefinitely after having performed the query and if you refresh the page it shows a blank page. Can somebody explain me why is this happening?
I even tried to use jQuery but with the same result.
<script>
//async request to the url -> print the result
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//query worked
document.write(xmlHttp.responseText);
//xmlHttp.abort();
}
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
//sparql query
var query = [
"PREFIX dbo: <http://dbpedia.org/ontology/>",
"SELECT ?album ?artist WHERE {",
"?album dbo:artist ?artist .",
"} LIMIT 10"
].join(" ");
//url for the query
var url = "http://dbpedia.org/sparql";
var queryUrl = url + "?query=" + encodeURIComponent(query);
//query call
httpGetAsync(queryUrl);
</script>
With jQuery:
<script>
//async request to the url -> print the result
function httpGetAsync(theUrl) {
$.ajax({
url: theUrl,
data: {
format: 'json'
},
error: function() {
document.write("error");
},
dataType: 'json',
success: function(data) {
document.write(JSON.stringify(data));
},
type: 'GET'
});
}
//sparql query
var query = [
"PREFIX dbo: <http://dbpedia.org/ontology/>",
"SELECT ?album ?artist WHERE {",
"?album dbo:artist ?artist .",
"} LIMIT 10"
].join(" ");
//url for the query
var url = "http://dbpedia.org/sparql";
var queryUrl = url + "?query=" + encodeURIComponent(query);
//query call
httpGetAsync(queryUrl);
</script>
Editing an element of the dom instead of writing directly into the document solved the problem.
document.getElementById('element').innerHTML = xmlHttp.responseText;
I'm hoping to extract one custom header response from a site using the Javascript code below:
<html>
<head>
<script>
var data = null;
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
//console.log(this.responseText);
}
});
var URL = "http://somesite.xml/records"
xhr.open("GET", URL);
xhr.setRequestHeader("authorization", "Basic itworks");
xhr.send(data);
var xrecords = xhr.getResponseHeader("X-Records");
console.log(xrecords);
</script>
</head>
Two questions:
1. What changes do I need to make to have the response pull the content of that custom header?
2. The content of the header is a number of records. How can ensure that the data type is a number?
EDIT: Turned out the issue I was having was because I wasn't using an async function. A snipped of my resolved code is below:
function selector(x){
function fooO(callback) {
function overdue (x){
return "tasks.json?responsible-party-ids="+x+"&filter=overdue";
}
return $.ajax({
url: 'https://' + company + '.site.com/' + overdue(x),
headers: {
"Authorization": "BASIC " + window.btoa(key)
}
})
}
I would like to convert this ajax function to a jquery function but im not sure how it would be done in jquery
function ajax_posta() {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "javas.php";
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById('status').innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send("num=" + (--num)); // Actually execute the request
document.getElementById('status').innerHTML = "<img src = 'loading.gif' height = '30' width = '30'>";
}
$(document).ready(function()
{
$('.eventer.button').click(function () {
var self = this;
$.post('javas.php', function (data) {
$(self).parent('div').find('.status').html(data);
})
});
}
)
;
</script>
You're pretty much there
$.ajax('javas.php', {
success: function(response) {
$(".status").html(response);
},
data: "num=" + (--num)
});
If these are the only two pieces of data you need to send to your request, you could just use $.post, but the advantage here is that if you ever want to specify more options, like contentType, all you'd have to do is add it to the existing options object.