Reading JSON format from URL - javascript

I am trying to make a website that analyzes data from a game called Overwatch.
I have this (https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/) and when you visit it, all you see is text in the json format.
Is there anyway I can read this using JavaScript and send it to a nice <p> tag on my website?
Current Code:
<script>
var obj = JSON.parse('https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/');
document.getElementById("elims").innerHTML = obj.Eliminations;
</script>
<p id="elims"></p>

You didn't tag this with jQuery so I'm going to assume you're wanting to do this with vanilla JS. .jsonParse() doesn't actually request JSON from a URL--it parses existing JSON-data into an object.
To handle this, you'll first want to request the data. This can be done using an XMLHttpRequest():
var requestUrl = "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/";
You next want to build out and perform your request. Create a function once the JSON data is fully loaded (onload):
let request = new XMLHttpRequest();
request.open('GET', requestUrl);
request.responseType = 'json';
request.send();
request.onload = function() {
logData(request.response);
}
An example function that handles the data could be:
function logData(data) {
document.querySelector('.elims').innerText = `Genji Eliinations: ${data['Genji']["Combat"]["Eliminations"]}`;
}
This appends it to an element with the class .elims, for example, a tag:
<p class="elims"></p>
I've added the whole code below. This should be enough to get you in the correct direction:
let requestUrl = "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/";
let request = new XMLHttpRequest();
request.open('GET', requestUrl);
request.responseType = 'json';
request.send();
request.onload = function() {
logData(request.response);
}
function logData(data) {
document.querySelector('.elims').innerText = `Genji Eliinations: ${data['Genji']["Combat"]["Eliminations"]}`;
}
<p class="elims">
</p>

Good way to start, so the URL you are trying to access is the REST web service which is just a GET method which produces the JSON. All you have to do is make an AJAX call via Javascript or Jquery and you can parse this to a Javascript variable then you can use those variable values you can generate the Paragraph elements to your HTML page.

You need to load data from server using HTTP GET request like this,
$.get( "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/", function( data ) {
console.log(data);
//process your data here
});

Since your url (https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/) is in json format. In order to retrieve it you need to use something like getJson.
Example:
$.getJSON( "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/", function( json ) {
console.log( "JSON Data: " + json.Assists["Healing Done"]);
});
You can read more on how to use getJson.

Related

Sending array to PHP using XMLHttpRequest (pure JS)

I'm attempting to send an array from JS to PHP using AJAX.
What seems to be happening is that the request is going through and is successful, but no data is received on the server (my test.php script needs the data from this array). Here is what I have so far...
Javascript
myButton.onclick = function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState==4 && xhr.status==200) {
console.log("Done. ", xhr.responseText);
}
}
//xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send('myArray='+JSON.stringify(myArray));
};
test.php
<?php
//$myArray = json_decode($_POST['myArray']); //Undefined index
print_r($_POST);
Note, myArray is not shown in the above code, but it is a valid array.
I've searched around SO (which led me to adding the 'setRequestHeader' in), as well as the wider internet. However, this has made no difference and I seem to be going round in circles. When I print $_POST, it's always an empty array.
I'm sure there's something I'm missing/misunderstanding.
Edit
As requested...
var myArray = ["John", "Jill", "James"];
I've also attempted this with an array of booleans, as well as an associative array/object.
Edit 2
As requested, adding screen shot from dev console...
you can use formData :
let data = new FormData();
let values = [1, 2, 3];
data.append('myArr', JSON.stringify(values));
// send data to server
and in php use json_decode :
$Values = json_decode($_POST['myArr']);
another way is to create HTML checkbox or select elements with javascript , assign values , serialize them and send them to back-end .

How do I parse this value in javascript from XMLHttpRequest and use it as a variable?

I am working on a chrome extension that gets some variables from a google sheets spreadsheet. I finally got the api setup correctly and can successfully query the data for the first variable from a cell in that spreadsheet. The problem for me is I am not familiar with the format the data is in.
Here is my code to query the google spreadsheet:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://sheets.googleapis.com/v4/spreadsheets/*spreadsheetID*/values/A2?key=*API Key*", false);
xhr.send();
var result = xhr.responseText;
The output I receive is:
{
"range": "Sheet1!A2",
"majorDimension": "ROWS",
"values": [
[
"https://www.access.com/home/"
]
]
}
the URL https://www.access.com/home is what I am trying to parse from the spreadsheet. If I change the code to parse the responseText in json I can get the value for range, just not for the "values" data to get the URL:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://sheets.googleapis.com/v4/spreadsheets/*spreadsheetID*/values/A2?key=*API Key*", false);
xhr.send();
var result = JSON.parse(xhr.responseText);
var data = result.range;
What am I doing wrong and how do I correctly parse the URL?
*While the post at Access / process (nested) objects, arrays or JSON does a great job at explaining how to access nested objects that are named, I was unable to figure out that how to access the nested array in my object because it didn't have a name.
var data = result.values[0][0];

referencing an unnamed javascript object in a JSON file

I am referencing a JSON file through a web service. The file contains an unnamed object. How do I refer to the object?
I am referencing the file like any normal JSON file
<script src="http://somewebservice.com/object.json"></script>
object.json
{
"one":1,"two":2,"three":{
"one":1,"two":2
}
}
Do I really need to use JSON.parse()? It's already in a JSON file format.
JSON is format that uses human-readable text to transmit data objects, so if "referencing a JSON file through a web service" means you get it as String in HTTP response, then yes, you have to use JSON.parse() to get javascript object from the string.
Loading your data using <script src="http://somewebservice.com/object.json"></script> will leave you with no handle to the loaded resource.
Either use JSONP or, if a cross-origin policy is place, load the resource using some ajax mechanism.
Using fetch
fetch("http: //somewebservice.com/object.json").then(function (res) {
try {
console.log(JSON.parse(res));
}
}).catch(console.error);
I ended up using AJAX to retrieve the remote file.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var objects=JSON.parse(this.responseText);
console.log(objects);
}
};
xhttp.open("GET", "http://somewebservice.com/object.json", true);
xhttp.send();

JS counter write to database

Is there any way I can use this JS second counter, to write to mysql:
var counter = 0;
setInterval(function () {
++counter;
}, 1000);
Can I export it as a variable and then use that variable to write to mysql?
What I'm attempting to do is save the time the user was on the page.
Is this even possible?
To help solve your ajax part (need jquery):
$.ajax({
type:'POST',
url: "yourfile.php",
data:{
"foo": filename // to add more variables you add on the spot after filename but remember the last one variable you send shouldn't have a comma
}
});
on the receiving end (php):
<?php
$filename = $_POST["foo"];
?>
basically ajax is used to send data to a php script.
Javascript is a language that is used in client side and can't write to MYsql. The code above will help you send data to your script. Your php script will run once it recieves the data through AJAX
You would need to write a bit of back-end php to handle ajax query from your front-end javascript.
Your JS may look like this:
function ajaxRequest(data) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "path/to/back-end.php", true);
xmlHttp.timeout = 1000;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) { //DONE
//success
console.log("Successfully sent to back-end.php");
}
};
xmlHttp.send(data);
}
You can refer to http://www.w3schools.com/ajax/default.asp for more information.
Then your php will retrieve the body of this POST request and insert it to mysql database accordingly.

Using AJAX to access to the Twitter API

I'm thinking about adding some twitter functions in my web-application, so I started doing some tests. I checked the way to call the search twitter URL (more info in: http://dev.twitter.com/doc/get/search) in order to get tweets that contains the searched word/sentence. I realized that you can do it in php just getting the JSON file that the search URL returns with the file_get_contents() function. Also you can do it directly in JavaScript creating a script object, appending it to the body and use the callback parameter of the search URL to process the data.
Different ways to do, but that's the way I finally did it:
MAIN HTML FILE:
<title>Twitter API JSON</title>
<script type="text/javascript">
//function that created the AJAX object
function newAjax(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
//function that search the tweets containing an specific word/sentence
function gettweets(){
ajax = newAjax();
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'getsearch.php', true);
// Process the data when the ajax object changes its state
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 ) {
if ( ajax.status ==200 ) { //no problem has been detected
res = ajax.responseText;
//use eval to format the data
searchres = eval("(" + res + ")");
resdiv = document.getElementById("result");
//insert the first 10 items(user and tweet text) in the div
for(i=0;i<10;i++){
resdiv.innerHTML += searchres.results[i].from_user+' says:<BR>'+searchres.results[i].text+'<BR><BR>';
}
}
}
}
ajax.send(null);
} //end gettweets function
</script>
#search_word Tweets
<input type="button" onclick="gettweets();"value="search" />
<div id="result">
<BR>
</div>
</html>
PHP WHERE WE GET THE JSON DATA:
$jsonurl = "http://search.twitter.com/search.json?q=%23search_word&rpp=10";
$json = file_get_contents($jsonurl,0,null,null);
echo $json;
And that's it, in this way it works fine. I call the PHP file, it returns the JSON data retrieved from the search URL, and in the main HTML JavaScript functions I insert the tweets in the div. The problem is that at the first time, I tried to do it directly in JavaScript, calling the search URL with Ajax, like this:
MAIN HTML FILE:
//same code above
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'http://search.twitter.com/search.json?q=%23search_word&rpp=10', true);
//same code above
I thought it should return the JSON data, but it doesn't. I'm wondering why not and that is what I would like to ask. Does someone have any idea of why I can't get JSON data using the Ajax object? If the search URL http://search.twitter.com/search.json?q=%23search_word&rpp=10 returns JSON data, it should be obtained in the ajax object, right?
XHR requests are generally limited to same-domain requests; e.g, if you're on bertsbees.com, you can't use an Ajax method to pull data from twitter.com.
That said, Twitter's API supports a popular data transport method known as JSON-P, which is really just a glorified injection technique. You simply pass it a callback method, and the data returned will be wrapped in your desired function, so it gets eval'd and passed in.
You cannot make a cross domain request using javascript, unless you are doing from an browser addon.

Categories

Resources