Use JQuery to get data from JSON file - javascript

Overflow!
I'm currently working on a little application I have to finish for school monday. I didn't have a lot of time to make something big. So I decided, why not retrieve information of Steam's Web Api and get the stats of players.
The url to the steam api:
http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=76561198263871727
The last parameter &steamid= represents the id of the player. Now I have found out how to get the steamid into a variable, but when trying to add the id to the rest of the url (http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=id should be here and fetching the data with the Ajax.getJson method.. It just doesn't work.. I'm for very experienced with JSON btw.. Can someone help me out with this?
My Web Page:
<!DOCTYPE html>
<html lang="en">
<head>
<!--Meta Information-->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--JQuery Mobile-->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!--FontAwesome-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<!--Custom Styles-->
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div data-role="page" id="index">
<div data-role="header">
<h1>CS:GO Stats</h1>
</div>
<div data-role="main" class="ui-content">
<div class="search">
<label for="search">Enter SteamID:</label>
<input type="search" name="search" id="inputSearch" />
<input type="submit" id="butSearch" data-inline="true" value="Search SteamID">
</div>
<div id="result">
</div>
</div>
</div>
<!--getSteamUserId function-->
<script src="js/getSteamUserId.js"></script>
</body>
</html>
My Javascript Code:
$(document).ready(function() {
$('#butSearch').click(function(event) {
var input = $('#inputSearch').val();
$.getJSON( "http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=" + input, function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "#result" );
});
})
})
Now what I want is to get the stats data from the JSON file into my web page. Would anyone know how to do this? I can also see the JSON is not only a flat JSON file.. Like it has different layers (if that's a good explenation)..
Thanks in advance!

Work with jsonP like here:
$.ajax({
url: url,
dataType: 'JSONP',
type: 'GET',
jsonp: 'jsonp',
success: handler
});
Working example here

I'm not entirely sure about the first part. It gives me an error which after googling led me to "No 'Access-Control-Allow-Origin' header is present on the requested resource" which advises using CORS. Error:
XMLHttpRequest cannot load http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=&76561198263871727. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.
Once you have the JSON it's easier. If it's stringified you can turn it into a javascript object with
steamObject = JSON.parse(steamJsonData);
and then navigate through it like a normal javascript object. Cycle through playerstats.stats[i] with a for loop and you can add the data to your page using normal DOM manipulation.

Related

innerhtml result to a better format

I am very novice with coding, I just started learning about it a week ago.
To cut the story short, i have a code here.
function lookup (){
var mac_address = document.getElementById('mac_address');
var resultDiv = document.getElementById("result");
if(mac_address.value.length<6){
alert('Enter at least 6 characters!')
}else{
var lookUpAdress = '<object type="text/html" id="lookupresult" data="http://macvendors.co/api/jsonp/'+mac_address.value+'"></object>';
resultDiv.innerHTML=lookUpAdress;
}
}
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin">
<div style="padding:0px;">
<label>Enter mac address:</label>
<input type="text" id="mac_address" />
<input type="button" value="Lookup!" onclick="lookup();" />
<div id="result" style="margin-top:10px;" class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin">
</div><!-- Result. -->
</div><!-- Input Box. -->
</div><!-- Container. -->
</body>
</html>
I want to get the result of the Look Up and show it in a better format like :
Company :
Prefix :
Address :
Takenote I'd be happy just to get the "Company."
TIA.
Load jquery together with your html, make sure jquery is loaded otherwise you wont be able to use $.ajax and will have to go the javascript way. Also it is alot easier to use jquery than javascript to manupilate the dom. So if you are a beginner, first learn jquery then move on to javascript.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
Use the above one or any other. You can google jquery cdn.
Then add a script to the bottom of your html:
<script>
$(document).ready(function(){
GetMacAddress();
});
function GetMacAddress(){
$.ajax({
url:'http://macvendors.co/api/jsonp/34:13:e8:1b:82:e4',
type:'get',
success:function(data){
// do something with data
alert(data.result.company);
},
error:function(){
console.log('oops');
},
});
}
</script>
This code will get you the result, change the code to suite your needs, i.e. display something in textbox
I guess this would solve your problem but:
You had to look up how to do it in non jQuery (or use jQuery)
I couldn't get it to work with https connections
$.getJSON('https://anyorigin.com/go?url=http%3A//macvendors.co/api/jsonp/34%3A13%3Ae8%3A1b%3A82%3Ae4&callback=?', function(data){
console.log(data.contents);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You may read more about it here:
https://medium.freecodecamp.org/client-side-web-scraping-with-javascript-using-jquery-and-regex-5b57a271cb86

sending data from html to php page without leaving page

I already used huge time for this in stack overflow and googling.But none of it worked for me.
I have a form in html and i need to send the data to a php without leaving the page.I used ajax and javascript.I can POST data by leaving the page but i don't want to leave the page.
here is my html:
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/topcoat-mobile-light.css" />
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<script src = "js/jquery.js"></script>
<script type="text/javascript" src = "js/index.js"></script>
<meta name="msapplication-tap-highlight" content="no" />
<title>Title</title>
</head>
<body>
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Header</h1>
</div>
</div>
<div class = "content text-input">
<form id = "form" name = "form" action="http://localhost/index.php" method = "post">
<p>Please fill the details.
<p> Name</p>
<input type="text" class="topcoat-text-input" placeholder="text" value="" id = "name" name = "name">
<input id = "submit" type="submit" class="topcoat-button" value = "Submit">
</form>
<script type="text/javascript">
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</div>
</body>
</html>
I can access "name" in php through post by leaving page, So I am not posting php here. Any Help would be highly appreciated. if anybody needs clarification i am here.
While your inputs have an id, they don't have a name attribute. Serialize uses the name to create the key value pairs for the data.
See: http://api.jquery.com/serialize/
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
Change your inputs to:
<input type="text" class="topcoat-text-input" placeholder="text" value="" id="name" name="name"/>
you should put target attribute in youre form so it will look like that:
<form id = "form" name = "form" action="http://localhost/index.php" method = "post" target="some_name">
and to put "some_name" as an iframe
<iframe id="some_name" name="some_name" style="display:none position:absulote; z-index:-100"></iframe>
that should do the job
Change the script part with this piece of code.... you need to call ev.preventDefault(); before ajax call....
<script type="text/javascript">
var frm = $('#form');
frm.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
});
</script>
I think there may be some mistake in javascript file <script src = "js/jquery.js"></script>. I have tried your code. Its working when I changed the javascript file. plz try with <script src = "http://code.jquery.com/jquery-1.11.0.min.js"></script> It has been worked for me.
I don't know how but this worked for me.Thanks for answers.
the html form worked when i place it at the same directory where index.php resides(ie at localhost:/).
if it is at another place It didn't work.I don't know why but I am figuring it out.
What you need is in here
http://malsup.com/jquery/form/
It submits the whole form and won't leave the current page.

Twitter bootstrap js getting blocked by Same Origin Policy, but non-bootstrap isn't. Why?

I've been attempting to put together a website that requires obtaining xml data from another website. So far, using only html and javascript (no twitter bootstrap), I can access the website XML and populate a select dropdown menu. Here is the non-bootstrap html code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/getXML.js"></script>
</head>
<body>
<h1>Test App</h1>
<button id="button1">submit</button>
<select id="selectState"></select>
</body>
</html>
and here is the bootstrap html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS-->
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
<!-- jQuery and JavaScript files -->
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/getXML.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<div class="container-fluid">
<div class="row-fluid">
<div class="span4 col-xs-3">
<form class = "well">
<h2 class="page-header">Inputs</h2>
<label class="control-label" for="selectState">Select State:</label>
<select id="selectState"></select>
<button type="submit" class="btn btn-default" id="button1" >submit</button>
</form>
</div>
</div>
</div>
</html>
and here is the getXML.js script:
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
$(document).ready(function(){
$( "#button1" ).click(function () {
aClient = new HttpClient();
aClient.get('http://www.waterqualitydata.us/Station/search?characteristicName=Caffeine&mimeType=xml&bBox=-92.8,44.2,-88.9,46', function(data) {
xmlDoc = $.parseXML( data ),
$xml = $( xmlDoc ),
$LocName = $xml.find( "MonitoringLocationName" );
var arr = [];
$.each($LocName,function() {
arr.push( $(this).text() );
});
for ( var i = 0; i < arr.length; i = i + 1 ) {
$('#selectState').append('<option>'+arr[i]+'</option>');
}
alert( "success" );
});
});
});
Now, when I try and using the Twitter bootstrap html, I am getting a Cross-Origin Request Block due to the Same Origin Policy.
Is there any reason why the scripts that don't use Twitter Bootstrap can get around the SOP, while the twitter bootstrap version can't?
Modify the Bootstrap script to include the 'type' attribute, like so:
<script src="js/bootstrap.min.js" type="text/javascript"></script>
The 'type' parameter here is key - it is what allows the remote request to happen. CSS and JS are allowed to do this kind of cross domain linking, as it is judged by the W3C gods to be a low security risk (at least last I checked).
Check these links out for more information on CORS:
IE's explanation: http://msdn.microsoft.com/en-us/library/ie/gg622939%28v=vs.85%29.aspx
Mozilla's thoughts: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
OK, I think I found the problem. I was placing the <button> inside a <form> element. This apparently raises the SOP block. Without the <form> element, no SOP block was raised.
I haven't looked at the exact reason behind this, but maybe its related to a security feature baked into the <form> element, since <form> elements can be used to pass sensitive information (passwords, etc.)?

Cannot access scripts when return to main page of Jquery site

Ok I'm reposting this from the start. I'm just so frustrated with this I'm about to just give up on JQM all together. This shouldn't be this hard.
My site structure:
OUI/
index.php
js/
pages/
images/
On my index.php page I have just a two line form for login I'm at http://localhost/~me/OUI/:
<? session_start();
?><!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=false,initial-scale=1;">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="stylesheet" href="js/jquery.mobile-1.4.0.min.css">
<link rel="stylesheet" type="text/css" href="css/jqm-datebox.min.css" />
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.4.0.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jqm-datebox.comp.datebox.min.js"></script>
<script src="js/mainsite.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/main.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>OUI CHEF</title>
</head>
<body style="background-image:url(media/kitchen.jpg)">
<div data-role="page" id="loginarea">
<div data-role="content" id="maincontentarea2">
<img src="media/OUIChef.png" style="margin-top:75px" id="mainimage">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" style="text-align:center" placeholder="Username"/><BR>
<label for="username">Password:</label>
<input type="password" name="password" id="password" value="" style="text-align:center" placeholder="Password"/>
</div>
<div style="text-align:center">
DO LOGIN
</div>
</div><!-- /page -->
</div>
</body>
</html>
So when I hit the login button it take me to my options.php page vi the following function:
function doLogin(){
$.ajax({
type: "POST",
url: "functions/checklogin.php",
data: {
usrnm: $('#username').val() , passwd: $('#password').val()
}
})
.done(function( msg ) {
if(msg.match(/YES/)){
$('#username').val('');
$('#password').val('');
$("body").pagecontainer("change","pages/options.php",{ });
}
else
{
alert(msg);
}
});
}
In the URL bar I now have http://localhost/~me/OUI/pages/options.php and everhthing in the page is working well. I have the signout button. in the code which calls
OPTIONS.PHP:
<div data-role="page" id="optionspage">
<div data-role="header">
Sign Out
<h1>MAIN</h1>
</div>
<div data-role="content" id="options1">
<? if($_SESSION['role']=='A'){?>
ADMIN PAGE
ORDER SETUP PAGE
<? } ?>
PRODUCTION
MENU / RECIPE PAGE
</div><!-- /content -->
</div>
this calls the JS:
function doSignout(){
$.ajax({
type: "POST",
url: "../functions/signout.php",
data: { }
})
.done(function( msg ) {
$('body').pagecontainer( "change", "#loginarea",{});
});
}
I can never get the link to the signout page to link correctly. If I put the double dots which should be correct from the "pages" folder I get it trying to link to
http://localhost/~me/functions/signout.php
and if I remove the double dots I get
http://localhost/~me/OUI/pages/functions/signout.php
both which are 404 errors.......this is BUNK in my book. the ".." is actually removing two directories..not just one.
What is happening? PLease help
As we don't see you log-in function, I'm assuming it looks something like the following?
$.ajax({
type: "POST",
url: "../functions/signin.php",
data: {}
})
If that is the case how does "../functions/signin.php" find it's mark when you are residing at /OUI/ initially — surely it would need to be "functions/signin.php" when you are on your home page.
Simply put I'm guessing your sign-in code is different on the homepage initially, and then after loading subsequent pages via ajax your sign-in code is getting overwritten or modified with code that is designed to work with a "../" prefix on deeper pages... and this isn't getting rectified when you switch back to the home page.
Basically you need to rewrite your code to detect how many folders deep the current URL is at and request your ajax files accordingly... either that or set one global variable (that is easily updatable) that keeps a full domain path to prefix all ajax urls with. i.e.:
var ROOT_URL = 'http://localhost/OUI/';
Depending on what you want to use this path can be generated by either PHP or JavaScript, PHP is more reliable — as in the end user does not require JavaScript — but it can be confused when hosted behind proxies and shared hosts.
var ROOT_URL = 'http://<?php echo $_SERVER["HTTP_HOST"]; ?>/OUI/';
var ROOT_URL = 'http://' + window.location.host + '/OUI/';

Not printing results from AJAX

I am working on a script to send data to a mysql table and I have it all working properly but the success part of the call, it is not loading my results in to my results column on my page. My code is below.
Any suggestions on what I can do to fix that? I am guessing the problem is within my "success:" option in my AJAX call.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="css/print.css" type="text/css" media="print" />
<!--[if IE]><link rel="stylesheet" href="css/ie.css" type="text/css" media="screen, projection"><![endif]-->
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
$('p.validate').hide();
$.getJSON("readJSON.php",function(data){
$.each(data.posts, function(i,post){
content = '<div id="post-'+ post.id +'">\n';
content += '<h3>' + post.author + '</h3>\n';
content += '<p class="small quiet">' + post.date_added + '</p>\n';
content += '<p>' + post.post_content + '</p>';
content += '<hr/>';
$("#contents").append(content).fadeIn("slow");
});
});
$(".reload").click(function() {
$("#posts").empty();
});
$("#add_post").submit(function() {
$('p.validate').empty();
// we want to store the values from the form input box, then send via ajax below
var author = $('#author').attr('value');
var post = $('#post').attr('value');
if(($('#author').val() == "") && ($('#post').val() == "")){
$("p.validate").fadeIn().append("Both fields are required.");
$('#author,#post').fadeIn().addClass("error");
}else{
$.ajax({
type: "POST",
url: "ajax.php",
data: "author="+ author + "&post=" + post,
success: function(result){
$('#contents').after( "<div>" +result +"</div>" );
}
});
}
return false;
});
});
/* ]]> */
</script>
<style type="text/css">
h3{margin:10px 0;}
p{margin:5px 0;}
#posts{display:none;}
</style>
</head>
<body>
<div class="container">
<div class="span-24">
<div id="post-container" class="span-9 colborder">
<h2>Posts loaded via Ajax:</h2>
<div id="contents"></div>
</div>
<div id="form" class="span-11">
<h2>New Post:</h2>
<form name="add_post" id="add_post" action="">
<label>Author:</label><br />
<input type="text" name="author" id="author" size="15" class="text" /><br />
<label>Post:</label><br />
<textarea name="post" id="post" rows="5" cols="5" class="text"></textarea><br />
<input type="submit" value="Post" id="submit" /><br />
</form><br />
<p class="validate error"></p>
</div>
</div>
<div class="span-24">
Reload
</div>
</div>
</body>
</html>
Questions to ask yourself...
Does jQuery even run your success callback?
If so is the response data well formed markup?
To begin I would add a "debugger;" statement to your success function (assuming you have firefox and firebug). This will enable you to break into the script console and get a better understanding of what is happening.
The debugger statement will cause the script execution to pause and break into the firebug console. Try the following
success: function(result){
debugger;
$('#contents').after( "<div>" +result +"</div>" );
}
If your script hits this I suspect your response markup is not well formed and jQuery is having issues parsing into the div but you can check all this when your at that breakpoint in firebug.
Another easy thing to check and dismiss in your debugging is
does your web server serve a valid (status 200) response (check the console or net tab in firebug to see this, or use the likes of fiddler if running in ie)
Let me know how you get on.
You might be getting an error try adding a debug statement to your ajax call using the error setting
$.ajax({
type: "POST",
url: "ajax.php",
data: "author="+ author + "&post=" + post,
error: function(XMLHttpRequest, textStatus, errorThrown)
{ alert(errorThrown); },
success: function(result){
$('#contents').after( "<div>" +result +"</div>" );
}
});

Categories

Resources