I have problem with get the returned data from a link . It is not working .
I have search more and try everything but it still not working . could anyone help me .
the link : https://www.routingnumbers.info/api/data.json?rn=13442323
my code is
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var request = $.ajax({
type: 'GET',
data: "rn=" + "54455445",
url: "https://www.routingnumbers.info/api/data.json",
success: function(data) {
alert("Data: " + data + "\nStatusA: " + status);
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Data: " + "Err" + "\nStatus: " + status);
console.log(jqXHR, textStatus, errorThrown);
request.abort();
}
});
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
Thank you
Well, first of all, I'd always advise using proper JSON formatting in ajax requests. The data attribute should be an object instead of a variable assignment. In the end, it doesn't actually matter; the request will complete with either format. It's always nice to look at consistently-formatted code, though. Regardless, the major problems that were causing the request to fail were the type of request you were making and its origin.
In the code you provided, you were making a request to an https address. The page you were requesting from, however, was not an https page, but an http page instead. This caused the request to return the error net::ERR_INSECURE_RESPONSE.
If you fix that, however, the request still won't complete successfully. This is because XMLHttpRequest doesn't allow requests to websites that aren't the same as the one that you are requesting from. For example, you could request content from routingnumbers.info if you're running the script from within routingnumbers.info itself, but not if you're running it from elsewhere. This can be fixed by specifying the request as a jsonp request instead of the default json request.
$("button").click(function(){
$.ajax({
type: "GET",
dataType: "jsonp",
async: true,
url: "http://www.routingnumbers.info/api/data.json",
data: {
rn: "54455445"
},
success: function(data) {
var array = [];
$.each(data, function(index, value){
array.push(index + ': ' + value);
});
alert(array.join("\n"));
},
error: function(data) {
alert(data.statusText);
}
});
});
JSFiddle
Hope this is helpful!
Related
I'm referring a question answered here.
Trying to append an external PHP file in to jQuery and tried load.
$(".chatbox").load("./one.php");
This gives me the output;
Your success message!
However the concern is this removes all HTML in the body and does not really 'append' the success message.
I tried the following instead.
$(".chatbox").append("./one.php");
which merely prints this!
./one.php
Am I missing something here?
The .load() load data from the server and place the returned HTML into the matched element. But you need to use $.ajax() or $.get() that get data and return it into callback function.
$.get("./one.php", function(data) {
$(".chatbox").append(data);
});
in case if the page you're trying to load is failing due to some reason, you also need to handle the error block to inform you about the issue. Here is a more comprehensive way to do it. Here I have called a wiki page but you will know, all the php pages are in fact interpreted as valid html by PHP engine :)
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
$.ajax({
type: "GET",
url: "https://en.wikipedia.org/wiki/PHP",
data: { },
success: function(data){
$('#demo').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#demo').html("Status: " + textStatus + "<br/>Error: " + errorThrown);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo"></div>
I am new to html and javascript.As far as i know the following code should give an alert when i press "Get JSON Data" button.But the page is not giving me any response.Any help is greatly appreciated.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
I suspected that should be the Cross-domain issue. That is why I asked for the console log. you have couple of choices:
config the cross-domain headers from your servlet/backend response.
(ex: if you're using a Servlet:)
response.setHeader('Access-Control-Allow-Origin','*');
use jsonp call back
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
The "?" on the end of the URL tells jQuery that it is a JSONP
request instead of JSON. jQuery registers and calls the callback
function automatically.
use $.ajax with CORS enabled or with jsonp
ex:
$.ajax({
url: surl,
data: {
id: id // data to be sent to server
},
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback"
});
// Named callback function from the ajax call when event fired.
function jsonpcallback(rtndata) {
// Get the id from the returned JSON string and use it to reference the target jQuery object.
var myid = "#" + rtndata.id;
$(myid).feedback(rtndata.message, {
duration: 4000,
above: true
});
}
or else, download and configure "CORS.jar" in your server side which will allow the cross-domain requests.
HOW ?
Hope you can get some idea. follow which suits for you ..
Replace the JSON call with
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err )
});
That way you can see what goes wrong. The javascript looks OK, I suspect it's a server issue.
You could also try getting back JSON from some random source, like http://1882.no/API/business/get/results.php?q=skole&page=0
I am using the answer given on this question.
As a result, my html page looks like this:
<!DOCTYPE html>
<html>
<head>
<script src="path\jquery-2.1.1"></script>
<script>
function myFunction() {
alert('Clicked!');
$.ajax({
url: "http://localhost:51399/api/webapi",
type: 'GET',
success: function (data) {
alert(data.error);
$('#demo').html(data);
},
error: function (data) {
alert(data);
}
});
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>
When I click the button nothing happens. I am not sure if the ajax call is ever made or if there is no success on the callback. What am I missing and how can I fix it so that the GET REST call goes through to the URL I specified?
P.S.: I am a beginner at javascript and jquery.
Maybe try:
$.ajax({
url: "http://blockchain.info/latestblock",
type: 'GET',
success: function(data) {
$('#demo').html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("error: " + errorThrown + " || status: " + textStatus + " || data: " + jqXHR);
}
});
or (the more modern way):
function myFunction(){
$.ajax({
url: "http://blockchain.info/latestblock",
type: 'GET'
});
}
function handleData(data) {
$('#demo').html(data);
}
function handleError(jqXHR, textStatus, errorThrown) {
console.log("error: " + errorThrown + " || status: " + textStatus + " || data: " + jqXHR);
}
myFunction().fail(handleError)
myFunction().done(handleData);
Wold's answer above is completely valid. However, the issue with my code was that I was trying to reference the jquery.js file using its absolute path which is prohibited. Once I made the path relative (and added the extension...stupid me) the call went through.
Hi i am using this code to get contents from a json file but i am not able to show results
my code is
$(document).ready(function(){
$.ajax({
url: 'http://50.116.19.49/rest/user.json',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 50000,
success: function(data, status){
alert(data);
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
In google chrome i can see that the request status is 200 and data is loaded. here is the link from which i am copying code The Link.... Any help!!!!
Thanks
Your code doesn't work because the http://50.116.19.49/rest/user.json resource return a JSON response instead of JSONP (difference).
So you can't make cross-domain calls via ajax BUT you can create a some proxy script ON YOUR SERVER which will make it for you. Example:
cross-domain-call.php
<?php echo file_get_contents('http://50.116.19.49/rest/user.json');?>
And change your script to
$(document).ready(function(){
$.ajax({
url: 'http://127.0.0.1/cross-domain-call.php',
dataType: 'json',
timeout: 50000,
success: function(data, status){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
});
Since you don't seem to have access to remote webservice to convert it to JSONP, here is a solution using Yahoo's YQL as a proxy. YQL will retrieve file contents from any remote site and return as xml or jsonp.
Working DEmo http://jsfiddle.net/Uh8cz/2/
You will notice the response object has additional properties created by YQL
var yqlBaseUrl = 'http://query.yahooapis.com/v1/public/yql?q=';
var restUrl = 'http://50.116.19.49/rest/user.json';
var yqlQuery = 'select * from json where url="' + restUrl + '" ';
var yqlFormat = 'format=json'
var jQueryCallback = '?'
var fullQueryUrl = yqlBaseUrl + yqlQuery + '&' + yqlFormat + '&' + jQueryCallback;
$.getJSON(fullQueryUrl, function(json) {
var jsonString = JSON.stringify(json.query.results.json.json, null, ' ')
$('body').append('<h1>Response</h1><pre>' + jsonString)
})
If you can control the content of "user.json", wrap it around a function:
user.json content:
execute_jsonp({you_json)
your javascript:
$(document).ready(function(){
$.ajax({
url: 'http://50.116.19.49/rest/user.json',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 50000,
success: function(data, status){
data(); //execute the function that is sent
},
error: function(){
output.text('There was an error loading the data.');
}
});
function execute_jsonp(json){ //recreate the function so you may access the json as a parameter
alert(json);
}
});
Hope this helps ;)
I'm trying to make a JavaScript that is fetching a JSON (IP DATA) and retrieves data from it (GEO IP) with AJAX and this is what I have so far:
$(document).ready(function(){
var path_to_the_webservice = "http://www.pathtothescript.com/check.php";
$.ajax({
url: path_to_the_webservice,
success: function(html)
{
if(html)
{
alert('3');
$('#content').append(html);
}
else
{
alert('4');
}
}
});
});
and I get alert(4), WHY?
Basically when you access http://www.pathtothescript.com/check.php from browser, retrieves a JSON that I have to parse with:
$.getJSON(path_to_the_json,
function(data)
{
$.each(data, function(i,item)
{
});
}
but I'm not sure how to make it.
The JSON looks like this http://j.maxmind.com/app/geoip.js
Any help?
It can be caused by Same origin policy.
Try to use JSONP request:
$.getJSON('http://example.com?callback=?', function(data) {
console.log(data);
});
Handling the response from http://j.maxmind.com/app/geoip.js
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.get('http://j.maxmind.com/app/geoip.js', function(data) {
console.log('Retrieved data:',
data,
'is type of', typeof data);
// Now we have some functions to use:
console.info('Some info:', geoip_country_name(),
geoip_latitude(),
geoip_longitude());
});
Fiddle
UPDATE:
In chat we found that my previous example works good in Google Chrome but doesn't work in Mozilla Firefox.
Though I played a little bit with it and found the solution:
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.ajax({
url: 'http://j.maxmind.com/app/geoip.js',
type: 'GET',
success: function(data) {
// Now we have some functions to use:
alert(geoip_country_name() + ': ('
+ geoip_latitude() + '; '
+ geoip_longitude() + ')');
},
error: function(e) {
console.log('Error:', e);
},
contentType: 'application/javascript; charset=ISO-8859-1',
dataType: 'script'
});
Fiddle
Also I've set a charset accordingly to service documentation.