getting JSON out of jQuery - from Foursquare API - javascript

I have not yet found a close enough answer to help me with this. I keep getting [object] as the output, I want the JSON so I can do things with it. Please help me do this correctly. I have tried the documentation for both Foursquare and jQuery, as well as a bunch of YouTube videos, and of course articles here. I am sure it is a simple thing, I just can't see it for being too close.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Blank Page</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body>
<p></p>
<script>
var url = "https://api.foursquare.com/v2/venues/search?v=20161016&ll=34.0707998%2C%20-84.0554183&query=park&intent=browse&radius=2000&client_id=O3VAAPG2MY5H2QERHNM2G03DOKVHN1L1ESUD31251FVEMUXY&client_secret=40B2KAJFL2F5UFSP1WXSBYAM3UPDFI3GAMTBRGC20KIN53YJ";
function getFoursquare(url){
var new_locations = $.ajax(url);
return new_locations;
};
$('p').text(getFoursquare());
</script>
</body>
</html>

In order for you to use the foursquare response, you need to have a json dataType for the AJAX, and you have to let the AJAX handle what happens with the response. To show you how that works, consider the following code. It adds the names of the venues to the paragraph:
function getFoursquare(){
var url = "https://api.foursquare.com/v2/venues/search?v=20161016&ll=34.0707998%2C%20-84.0554183&query=park&intent=browse&radius=2000&client_id=O3VAAPG2MY5H2QERHNM2G03DOKVHN1L1ESUD31251FVEMUXY&client_secret=40B2KAJFL2F5UFSP1WXSBYAM3UPDFI3GAMTBRGC20KIN53YJ";
$.ajax({
url: url,
dataType: 'json',
success: function(data){
var venues = data.response.venues;
$.each(venues, function(i,venue){
$('p').append(venue.name + '<br />');
});
}
});
};
getFoursquare();

Related

how to Invoke api using simple html code?

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.

Url with parameters does not work in ajax but works alone

I've this simple HTML / Javascript sample code ....
<html>
<head>
<meta charset='utf-8' />
<title>Open Pronto Soccorsi</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<!-- *** References for JQuery ... -->
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<script>
var city= "Torino";
$.ajax({
url: "http://www.webglobes.org/cesarefortelegram/Telegram/OpenProntoSoccorso/API/getProntoSoccorsoDetailsByMunicipality.php",
method: "GET",
data: {municipality: city, distance:0}
})
.done(function(output) {
alert("OK!");
})
.fail(function() {
// handle error response
alert("KO!");
})
</script>
</body>
</html>
... that invoke this url ...
http://www.webglobes.org/cesarefortelegram/Telegram/OpenProntoSoccorso/API/getProntoSoccorsoDetailsByMunicipality.php
with parameters:
municipality=Torino
distance=0
When I try to execute the result is always "KO" alert but if I try, in a new browser tab, the complete url that I can see in the browser console when I try to use my code
http://www.webglobes.org/cesarefortelegram/Telegram/OpenProntoSoccorso/API/getProntoSoccorsoDetailsByMunicipality.php?&municipality=Torino&distance=0
all works fine .... ???
Any suggestion will be appreciated
You haven't set a dataType in the request so jQuery is trying to decide which format the data is. That's fine, but if jQuery is inferring that the data is JSON then it is trying to parse it as well. If the data is not formatted correctly, then then you'll get a 200, but the parsing will fail and throw an error. That may be a good place to start.

Bing Image Archive Ajax Error

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/

How to use a jquery HEAD request to obtain just metadata (response headers)

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!

jQuery client for REST webservice with jersey

I am new in jQuery and I'm trying to develop a client for my web service. I've tried something simple, just for testing, but still it doesn't work, although it seems ok to me.
I have the jQuery library in my tomee/webapp folder, along with my html and javascript files. If I write some non-jQuery code in my javascript file, it works.
I have the following code:
index.html
<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="client.js"></script>
</head>
<body>
<input type="button" id="getAllButton" value="Get all books" onclick="return getAllBooks()"/>
<div id="messageBox"></div>
</body>
</html>
client.js
function getAllBooks() {
$.ajax({
dataType: 'application/xml',
type: 'GET',
url: rootURL + '/books',
success: function (data) {
alert(1);
},
error: function (data) {
alert(2);
}
});
}
The problem is that no alert will appear. If a write pure javascript (I mean without jQuery), alerts will do appear.
Why do alerts not appear? Any advice?
Thank you!
Sorin
Lets try to find out what works and what not; try changing your client.js to:
alert(1);
function getAllBooks() {
alert(2);
window.open(rootURL + '/books');
$.ajax({
dataType: 'application/xml',
type: 'GET',
url: rootURL + '/books',
success: function (data) {
alert(3);
},
error: function (data) {
alert(4);
}
});
}
If you see the alert #1 (when your html page loads) then your client.js path is OK. If you see alert #2 (when you click the button) then at least the function is being called.
Verify if window.open() shows what your web service is supposed to show you (even a error message will guide you throw the right path). And of course, if you see alert #3 or #4 then your problem was mysteriously solved by it self.... it sometimes happens :-)
NOTE: If you know how to use the javascript console of your browser use console.log() instead of alert() for debugging;
Thanks charlietfl for your tips! They helped me solve the problem.
The problem was that it didn't know who rootURL is. I found rootURL in an example and I thought that is something defined in jQuery. It seems it isn't.

Categories

Resources