I have made an Ajax call to Bing to get its daily image, however i get an error in the console:
this is the full code its on a localhost using wamp
index.php
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
$.ajax({
url : "http://bing.com/HPImageArchive.aspx?format=js&idx=0&n=1",
dataType:"jsonp",
});
function mycallback(data)
{
$('#output').html(data.images[0].url);
}
</script>
I think you should study the documention for jquery ajax call.
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
(function() {
var bingImagesUrl = "http://bing.com/HPImageArchive.aspx";
$.getJSON( bingImagesUrl, {
idx:0,
n:1,
format: "js"
}).done(function( data ) {
$('#output').html(data.images[0].url);
});
})();
</script>
#Below_the_Radar: your answer does not really help as OP is likely getting the same error even if he makes the Ajax call correctly.
According to Is there a way to get Bing's photo of the day?, it seems that Bing.com only supports XML, JSON, and RSS. I guess OP want to make the call with dataType: "jsonp" probably because he would like to bypass the browsers same-origin policy.
This can be solved client-side in browser by using a Chrome extension, but I guess that is not OP's use case. I bet OP is trying to get a picture from Bing's archive and thus use it in his own website. If that is the case, it has no solution as we need to have "Access-Control-Allow-Origin": "*" in the response's headers returned by Bing, which we do not have control.
I suggest considering an alternative. Try this: https://source.unsplash.com/
Related
I have a small requirement that needs to make REST API POST call using HTML code. I have copied the sample code below and some reason this is not working. I am unable to see any call using the below code. Please let me know If there is any change required in the code.
<html>
<head>
<title>My first API script</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<H1>Testing the API call</h1>
<form>
<label for="msg">Message</label>
<button id='submitButton'>Submit</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var API_URL = 'https://example.com/'; // this will be my API like https://example.com
$('#submitButton').on('click', function(){
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringfly({"message": $('#msg'.val())}),
contentType: "application/json",
success: function(data){
location.reload();
}
})
})
</script>
</body>
</html>
Rewrite $('#msg'.val()) to $('#msg').val(), and implement an error(xhr, textStatus, errorThrown) function in .ajax too so you'd catch the error next time.
Several things need to be fixed in your code. Not sure if that's the one you're actually using but:
Change stringfly to stringify.
label doesn't have an id="msg" but you're trying to access it with #msg.
Add a e.preventDefault() on your click callback function. Make sure to receive e as parameter.
label-s don't have a val() function. If you're trying to get the "Message" inside the label, use $('msg').text().
Try using API placeholders like JSONPlaceholder instead of example.com so you don't get CORS errors.
Finally, add an error callback to your AJAX so you can catch and handle errors.
I am converting my webapp from PHP / HTML to JS/HTML so that it can work with phonegap. I am keeping the php server side files separate and on the server. I am having issues with executing AJAX calls from my local HTML file. When i check the console on chrome, it doesn't show any errors, but the ajax call doesn't return any value either. Ive simplified the issue so that people can easily understand what the problem is.
My JS code is
<head>
</head>
<body>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$.ajax({
url: "http://www.betsmart.org/betsmart/models/test.php",
method: "get",
dataType: "json",
crossDomain: true,
success: function(result){
console.log(result);
$("#text").html(result);
}
});
</script>
<h1 id="text"></h1>
</body>
My PHP code in test.php is
<?php
header("Access-Control-Allow-Origin: *");
echo "test";
?>
The success callback isn't executing. I understand the same origin policy will probably come into play here but i thought that doesn't matter with Phonegap.
Please do let me know where i'm going wrong or an alternate way to do this. If i have to use jsonp, what will be the client side and server side code?
Thanks
Gagan
I am having difficulty with a specific JQuery $.post call to a PHP-based processor. I created a test page with the code below located here: http://goo.gl/Bg7H2u
Note this is located on a subdomain, but we are not doing cross-domain posting. Everything should be included on the subdomain.
There do not seem to be any JS errors as reported in the error console.
The processor /get-data.html is the general purpose PHP processor, and, if you load the processor page with the right value, it returns a dataset from the MySQL database in JSON format. We have this working on the main domain without issue, and other $.post calls seem to work OK from this subdomain (not to this /get-data.html processor, but other processors that process form content).
See the actual processor output here: http://goo.gl/yOzrm2
I must be missing something obvious, but I am coming up empty. Thoughts?
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=320px, initial-scale=1">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var prices;
$(document).ready(function(){
$.post( "/get-data.html", { table: 'prices' },
function( data ) {
prices = data;
alert(prices);
}, 'json');
});
</script>
</head>
<body>
<div style="overflow-x: hidden;" id="divMain">
</div>
</body>
</html>
Thanks for any advice you can provide.
If you do View Source on the processor output, you'll see that your script is returning:
<p>{"Basic Plan":["349"],"Basic":["349"],"Premium Plan":["549"],"Premium":["549"],"Standard Plan":["429"],"Standard":["429"],"Bonus Plan":["175"],"Additional Central AC System":["99"],"Additional central heating system":["99"],"Central Vacuum":["99"],"Whole home humidifier":["49"],"Pool (in-ground)":["179"],"Spa (in-ground)":["179"],"Septic System":["99"],"Sump Pump":["99"],"Well pump":["99"],"Whole home water softener":["99"],"Lawn sprinkler system (in-ground)":["99"],"Wine refrigerator":["49"],"Ice maker (free standing)":["49"],"Home phone (unlimited)":["49"],"TV Protection (Flat screen up to 60 inches)":["99"],"PC Protection (laptop or desktop)":["49"]}</p>
There's <p> at the beginning and </p> at the end. This is not valid JSON. You need to fix the server script so that it doesn't print anything other than the JSON (whitespace is OK, that's it).
1.confirm that /get-data.html is the correct relational url for your file location.
If you navigate directly to the /get-data.html, does it produce the results that you are after.
try running the same code without , 'json' and see if it works.
hope this helps
Here is my code:
<!DOCTYPE html>
<html lang="en" >
<head>
<script type="text/javascript">
function showResponse(response){
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
function onClientLoad(){
gapi.client.load('youtube','v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad(){
gapi.client.setApiKey('MyActualKey');
search();
}
function search(){
var request = gapi.client.youtube.search.list({
part: 'snippet'
});
request.execute(onSearchResponse);
}
function onSearchResponse(response){
showResponse(response);
}
</script>
<title></title>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
</head>
<body>
<div id="response"></div>
</body>
</html>
This code is from Codecademy, and I thought I can use it on an html page and it would work.
I got an API key from google and I set my Youtube data api v3 setting to enabled in my google developers console, but this code gives me a blank page.
What am I doing wrong?
There are a few missing pieces, code snippets which codecademy likely took for granted but which are essential when placing it in your own server outside of their app. First of all, you need a line that actually loads the gapi library from google. You can put this in your code, just before the closing :
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
In short, this will get the library from Google's servers, and when it's loaded the library will automatically call your onClientLoad method, kicking off your app.
Next, you say you have an API key; make sure you put that key into your code by replacing this:
gapi.client.setApiKey('MyKey');
with this:
gapi.client.setApiKey('{WHATEVER_YOUR_ACTUAL_KEY IS');
Finally, as the commenters mentioned, your body is empty, so when your code executes the showResponse method there's no place to put what comes back. Add this:
<div id="response"></div>
So, I've just read online about a fairly specialized HTTP method known as HEAD, which is basically supposed to only send metadata, without sending the actual document body. It seems that jQuery supports this, but when I attempted to create it for real, the body was still sent along with the headers. When I checked in the console, Chrome told me that a head request was actually sent. Huh?
Here's the code:
<!DOCTYPE html>
<html>
<head>
<meta charset = 'UTF-8'/>
<title>Headers</title>
</head>
<body>
<script language="Javascript" type="text/javascript"
src="2-jquery-1.11.0.min.js"></script>
<script language="Javascript" type="text/javascript"
src="jquery-ui-1.10.4.custom.min.js"></script>
<script language="Javascript" type="text/javascript">
$(function() {
$.ajaxSetup({ cache: false }); // not exactly necessary for head requests
// to be used for other ajax request types
//..is this interfering?
function reloader() {
$.ajax({ type: 'HEAD', url: "chatbox.txt" })
.done(function(data, status, xmlhttp) {
console.log(xmlhttp.getResponseHeader('Last-Modified')); })
.fail(function() { alert("error!"); })
.always( function() {} ); } // end reloader
var matrix = setInterval(reloader,3000);
$('#stop').click(function() { clearInterval(matrix); alert('stopped!');
}); // end click
}); // end $(document).ready()
</script>
<button id = 'stop'>Stop</button>
</body>
</html>
Everything works fine, except for the body being sent as well. What's the problem exactly? Am I accidentally sending the body along with the request? If so, where in the code is this?
P.S. I know I can do this with PHP, but I'm interested in js/jQ.
Thanks!