Perform an Ajax SPARQL query in Firefox - javascript

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;

Related

Joomla 4 Component Development & AJAX - not opening URL but itself

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.

Loading a specific part of JSON API data

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();

How get steam nickname via javascript

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.

Why is PHP not receiving my AJAX request string?

I am puzzled as to why PHP sees my request string as undefined.
$_GET['ask'] in my php file
produces this error -> Notice: Undefined index: ask.
But when I query the php file from the url bar in the browser like this
localhost/Websites/webProject/data.php?ask=myquery
I have set the php file to echo my string and it does do exactly that but only when I query it from the browser URL bar.
But when running the AJAX code normally from the parent html/php file
request.open("GET", "data.php?ask=myquery", true);
The PHP file does not see the query string and thinks its undefined.
Why is this the case?
I have tried to use
$_REQUEST[]; but to no avail.
I am using pure javascript for the AJAX requests.
Here is the javascript
requestResponse();
function requestResponse()
{
var READY_STATE_DONE = 4; /* request finished and response is ready */
var SUCCESS = 200; /* "OK" */
setInterval(function(){
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(this.readyState == READY_STATE_DONE && this.status == SUCCESS)
{
var response = this.responseText;
console.log(request.responseText);
document.getElementById("test").innerHTML += "<br>" + response;
}
}
request.open("GET", "data.php?ask=myquery", true);
request.send();
}, 3000)
}
Here is the PHP content
testRequest();
function testRequest()
{
$reqString = $_REQUEST['ask'];
include("dbCredentials.php");
include("dbConnect.php");
if($reqString == "myquery")
{
echo("<br />REQUEST IS: " . $reqString);
echo("<br /> Your request is granted");
}
}
DISCLOSURE: I have replaced the previous php file with data.php.
Try using Jquery Ajax request. this is mostly effective when you want to pass strings instead of serialized data
HTML:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
$.ajax({
type: 'post',
url: 'data.php?ask=whut',
success: function(response){
alert(response);
}
});
});
</script>
PHP Content:
echo $_GET['ask'];

Validating username/password through Ajax

I am trying to use Ajax to validate a username and password stored in a php document on a server. The usernames and passwords are pre stored in the document.
On my HTML page is a field for the username, and a field for the password. Then, when they click the Log-In button it calls the following function:
function checkLogin() {
var user = document.getElementById("username").value;
var password = document.getElementById("password").value;
var data = "userName=" + user + "&password=" + password;
var request = new XMLHttpRequest();
request.open("POST", "check.php", false);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(data);
if (request.status === 200) {
window.open("test.html");
} else {
var messageSpan = document.getElementById("response");
var responseJson = JSON.parse(request.responseText);
messageSpan.innerHTML = "Your password of " + responseJson["password"] + " was not corerct. Please try again.";
}
}
The problem I'm having is that it never gets to the else if the username/password are incorrect. Even if there's nothing in the fields, it opens the new page. What am I doing wrong for it to think that all data is correct?
NOTE: The above code is for testing purposes only, and won't actually be used when publishing the web page. I just want to see what's happening and get it to work before moving on. Thanks.
Most likely your check.php echos out true or false on response in some cases you echo out user ID on success. Anyways, your response code is 200 for successful server communication. Examine request.responseText in case of getting 200.
if (request.readyState == 4 && request.status === 200) {
var responseJson = JSON.parse(request.responseText);
if (responseJson['success'] == 1){
window.open("test.html");
} else {
var messageSpan = document.getElementById("response");
messageSpan.innerHTML = "Your username and password combination was incorrect.";
}} else {
//For debugging purpose add an alert message here. alert(request.status);
messageSpan.innerHTML = "A server connection error occurred!"; }
It's noticeable that you are sending back json response. So you may add a node called success whith value of true or false to examine logged in success. It's not a good practice to show password in response message though.
Well the problem is you are getting status 200 from your check.php every time.
In your check.php you need to do some thing like
// let validate() be function that validates your username/password
// and returns true/false on validation
if(validate()){
http_response_code(200);
} else {
http_response_code(401);
}
hope it helps
simply you can use ajax like this,
<script>
function checkLogin() {
var user = document.getElementById("username").value;
var password = document.getElementById("password").value;
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//progress
xhr.upload.addEventListener("progress", function(e) {
//progress value e
}, false);
return xhr;
},
type: "POST",
url: "check.php",
data: {'userName' : user , 'password' : password},
dataType:json,
success: function(msg) {
//when success //200 ok
if(msg.status=="done"){
window.open("test.html");
}else{
var messageSpan = document.getElementById("response");
messageSpan.innerHTML = "Your password of " + msg.password+ " was incorrect.";
}
},
error: function(jqXHR, textStatus, errorThrown) {
//when error
}
});
}
</script>
your php server side like this,
//$status="fail" or "done"
//success must be always success
$respond=array("success"=>"success","status"=>$status,"password"=>$password);
echo json_encode($respond);
exit;
I think this useful for you !

Categories

Resources