Can't get JSON with JQuery - javascript

I'm trying get json from url but it not working, also i'm not getting any error
index.js:
$(function () {
$.getJSON("http://telegram-socks.tk/json", function (data) {
$("textarea").html(JSON.stringify(data));
}
);
});
index.html:
<html>
<head>
<meta name="viewport" content="initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row text-center">
<div class="col">
<textarea class="form-control text-center" rows="50"></textarea>
</div>
</div>
</div>
</body>
</html>
telegram-socks.tk/json:
{
"Proxies": [
"188.166.91.133:1080",
"51.15.100.63:1080",
...
]
}
(telegram-socks.tk/json is valid JSON according to jsonlint.com)

If you open your console you will probabily see an error like this:
Mixed Content: The page at 'https://yourpage.com' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://telegram-socks.tk/json'. This request has been blocked; the content must be served over HTTPS.
That happens because you are on a page that is cryptography by SSL, and are trying to access a unsecure url, that most browser will natively block.
Or even like this:
Failed to load http://telegram-socks.tk/json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
That is the browser again blocking your request because of insecure resource in other pages
See the bellow snippet and check the console:
$(function() {
$.getJSON("http://telegram-socks.tk/json", function(data) {
console.log(data);
}).error(function(e) {
console.log(e);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<div class="row text-center">
<div class="col">
<textarea class="form-control text-center" rows="50"></textarea>
</div>
</div>
</div>
You can check more information about it in here and here

Try this :
$.getJSON("http://telegram-socks.tk/json", function(data) {
console.log( "success" );
}).fail(function( jqxhr, textStatus, error ) {
console.log(data);
});

Related

Youtube API program won't run -- JavaScript

I'm relatively new to API's right now. I'm trying to allow a user to search for a youtube video and have it display the first three results. Refer to code below (I have used the youtube video "Using the Youtube API to search for videos" - FSquare for assistance and give them credit -- there are some modifications and it is not the exact same; it was merely used to help me understand how the API works) :
HTML
(index.html)
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<title>Youtube API</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" />
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js"></script>
<script src="1.4.8.angular.min.js"></script>
<script src="3.1.1.jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
<script type="text/javascript" src="script.js"></script>
<script src="app.js"></script>
</head>
<body>
<header>
<h1>Youtube Viral Search</h1>
</header>
<section>
<form action="#">
<input type="text" id="searchText" placeholder="Search Video...">
<input type="submit" id="searchButton" value="search">
<p id="response"></p>
</form>
</section>
</body>
</html>
JS
(Note: ApiKey is defined as a variable in my code; I am choosing not to showcase it)
$(document).ready(function() {
$(function() {
$("form").on("submit", function(e) {
e.preventDefault();
//prepare request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: encodeURIComponent($("#searchText").val()).replace(/%20/g, "+"),
maxResults: 3,
order: "viewCount",
publishedAfter: "2016-01-01T00:00:00Z" //Will get videos published after midnight, 2015.
});
//execute request
request.execute(function(response) {
console.log(response);
});
});
});
function init() {
gapi.client.setApiKey(ApiKey);
gapi.client.load("youtube", "v3", function() {
alert("The Youtube API is ready! Use away.");
});
}
})
For now I want to see what results look like in the console. However, when I run it on a simple Python HTTP Server, the following error results in the console:
Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://127.0.0.1:8000" from accessing a cross-origin frame.
at contents (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/vendor/jquery.min.js:2:5154)
at Function.map (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/vendor/jquery.min.js:1:14862)
at ot.fn.init.ot.fn.(anonymous function) [as contents] (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/vendor/jquery.min.js:2:5271)
at HTMLIFrameElement.eval (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/components/ActivityMonitor/views/overlay/ActivityMonitorOverlayView.js:1:1894)
at Function.each (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/vendor/jquery.min.js:1:14059)
at ot.fn.init.each (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/vendor/jquery.min.js:1:11922)
at e.bindActivityDetectors (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/components/ActivityMonitor/views/overlay/ActivityMonitorOverlayView.js:1:1853)
at e.init (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/components/ActivityMonitor/ActivityMonitorController.js:1:255)
at onLoaded (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/content.js:1:979)
at eval (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/ComponentFactory.js:1:943)
From research, it appears that I need to run this on an HTTPS server to see my results, but am unclear on how to do this or if that is the reason.

Use JQuery to get data from JSON file

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.

scribd set page not working

I am using scribd to display pdf. By clicking on the Page 3,Middle,End links the corresponding pages should load. But the pages are not loading properly. And in FF i am not getting any errors. But in chrome console i am getting this error. Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://www.scribd.com') does not match the recipient window's origin ('https://www.scribd.com'). Can anyone help me out in this?
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Scribd Javascript API Demo</title>
<script type="text/javascript" src='https://www.scribd.com/javascripts/scribd_api.js'></script>
</head>
<body>
<div id="container">
<div id='col1'>
<div id='embedded_doc'><a href='https://www.scribd.com'>Scribd</a></div>
</div>
<div id='col2'>
<h2 id="header"> Loading Document... </h2><br/>
<span id="author"></span>
<div id="bookmarks">
<h4>Bookmarks</h4>
<ul>
<li>Page 3</li>
<li>Middle</li>
<li>End</li>
</ul>
</div>
<div id="comment"></div>
</div>
<div class="clearfix"> </div>
</div>
<script type="text/javascript">
// Data
// Instantiate iPaper
var scribd_doc = scribd.Document.getDoc(2520449, 'key-1127428tb3rbejns9bhr');
// Parameters
scribd_doc.addParam('height', 420);
scribd_doc.addParam('width', 530);
scribd_doc.addParam('auto_size', true);
scribd_doc.addParam('mode', 'slideshow');
scribd_doc.addParam('jsapi_version', 2);
// Write the instance
scribd_doc.write('embedded_doc');
// Bookmark Helpers
var goToPage = function(page) { alert(scribd_doc.api.getPageCount());
if (scribd_doc.api){
scribd_doc.api.setPage(3);
}
}
var goToMiddle = function() {
if (scribd_doc.api){
goToPage( Math.floor(scribd_doc.api.getPageCount()/2) );
}
}
var goToEnd = function() {
if (scribd_doc.api) {
goToPage(scribd_doc.api.getPageCount());
}
}
</script>
View Source and you'll see that this is all dynamically generated using the Scribd Javascript API.
</body>
</html>
I fixed this issue by downloaded the scribd_api.js file and modified the path to https in js. And now the set page is working without any errors.

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.)?

Getting a 501 error

I am getting the following error when I am trying to run this code on the browser.
"Error response
Error code: 501
Message: Unsupported method ('POST').
Error code explanation: 501 - Server does not support this operation."
The following errors were in the browser console:
"1. Failed to load resource: the server responded with a status of 404 (File not found)
'http://localhost:8002/js/jquery-1.3.2.min.js'
Resource interpreted as Script but transferred with MIME type text/plain:
pquery-0.0.1.js:1
Failed to load resource http://mdsad.com/p.js?v=1372783767755
undefined login.html:61
POST
http://localhost:8002/login.html 501 (Unsupported method ('POST')) login.html:1
Resource interpreted as Script but transferred with MIME type text/plain:
pquery-0.0.1.js:1
GET http://mdsad.com/p.js?v=1372783801500 download.js:33"
The login of users via stackmob also fails. I get a 'Failure' alert message. Here is the code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/stackmob-js-0.9.1-bundled-min.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Form</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function() {
$(".username").focus(function() {
$(".user-icon").css("left","-48px");
});
$(".username").blur(function() {
$(".user-icon").css("left","0px");
});
$(".password").focus(function() {
$(".pass-icon").css("left","-48px");
});
$(".password").blur(function() {
$(".pass-icon").css("left","0px");
});
});
</script>
<script type="text/javascript">
function nextpage(form){
StackMob.init({
publicKey:"my_key",apiVersion:0
});
var u=document.getElementById('username').value;
var p=document.getElementById('password').value;
var user = new StackMob.User({ username: u, password: p});
user.login(false, {
success: function(model, result, options) {
alert("Success");
StackMob.isUserLoggedIn(form.username.value, {
yes: function() { alert("Yes"); },
no: function() {
alert("No");}
});
},
error: function(model, result, options) {
console.log(result);
alert("Failure");//or print out the error
} }); };
</script>
</head>
<body>
<div id="wrapper">
<div class="user-icon"></div>
<div class="pass-icon"></div>
<form name="login-form" class="login-form" action="" method="post">
<div class="header">
<h1>Login Form</h1>
<span>Fill in the details</span>
</div>
<div class="content">
<input id="username" name="username" type="text" class="input username" value="Username" onfocus="this.value=''" />
<input id="password" name="password" type="password" class="input password" value="Password" onfocus="this.value=''" />
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button" onclick="nextpage(this.form)"/>
<input type="submit" name="submit" value="Register" class="register" />
</div>
</form>
</div>
<div class="gradient"></div>
</body>
</html>
However, I am sure about the stackmob part because it worked well in a simple code of mine. Here is the working simple code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/stackmob-js-0.9.1-bundled-min.js"></script>
<script type="text/javascript">
function nextpage(form){
StackMob.init({publicKey:"my_key",apiVersion:0});
var u=document.getElementById('username').value;
var p=document.getElementById('password').value;
user.login(false, {
success: function(model, result, options) {
alert("Success");
StackMob.isUserLoggedIn(form.username.value, {
yes: function() { alert("Yes"); },
no: function() {
alert("No");
}
});
},
error: function(model, result, options) {
console.log(result);
alert("Failure");//or print out the error
}
});
};
</script>
</head>
<body>
<form>
<table>
<tr><td>Username</td><td><input id="username" type="text"></td></tr>
<tr><td>Password</td><td><input id="password" type="text"></td></tr>
<tr><input type="button" value="LOGIN" onclick="nextpage(this.form)"></tr>
</table>
</form>
</body>
</html>
Can someone please tell me where am I going wrong?
You are running a local server on port 8802 but the javascript file "jquery-1.3.2.min.js" is not at the location specified, hence the 404 error.
The 501 error is because the server you are using (presumably something like simpleHTTPServer) doesn't support POST requests.
To resolve that error you need to use a server that supports POST requests (e.g. Apache, IIS).
Your importing Jquery twice, and two different versions, this could add all sorts of strange issues assuming the 404 is inaccurate.
Remove this line:
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
If nothing else it will clear the 404

Categories

Resources