how to Invoke api using simple html code? - javascript

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.

Related

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.

getting JSON out of jQuery - from Foursquare API

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();

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/

Display View in New Window

I have developed an ASP.NET MVC application that will run several prescreen functions based on user input.
The plan is to call this new mvc app from an existing HTML/JavaScript application. I would like to display the controllers's view in a new browser window outside of the calling application.
My AJAX call will look something like this
$.support.cors = true;
$.ajax( {
url: "http://mvc_url/prescreen",
data: jsonObject,
type: "POST",
processData: false,
dataType: 'html',
contentType: "application/json; charset=utf-8",
timeout: 60000,
//dataType: "json",
success: function ( msg )
{
...on success msg = html rendered from view...
},
error: function ( XMLHttpRequest, textStatus, errorThrown )
{
...error handling...
}
} );
I've tested this and on success msg does contain the fully rendered HTML from the view. My question is how do I open a new window using the rendered HTML?.
I've tried the following:
var newWindow = window.open( "", "", "" );
newWindow.document.write( msg );
and that seems to work. sort of. The new window opens and the html is displayed, but then my style sheets and included javascript files, for the view, are missing. So if using the above window.open code is correct, then how do I bring down the necessary stylesheets and javascript files?
EDIT
Utilizing the suggestion provided by AndyJ, I've modified my view to include relative paths based on my base application. Here is the returned mark up from my MVC
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Offer</title>
<link href="../css/site.css", type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container body-content">
... Page Content ...
<script src="/baseapp/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script src="/baseapp/js/someInclude.js" type="text/javascript"></script>
<script type="text/javascript">
InitializeForm();
</script>
the InitializeForm method is defined within the someInclude.js.
Based on the above and assuming the files are locates in the paths, everything should link up, correct? So what else might I be doing wrong?
In addition to the help provided by Andy J (Thank you), I also found that when the response was rendered in the new window, the JQuery library was loading AFTER my initialization script. To circumvent this, I simply added my event handlers to the inline attributes of the controls.
This may be a work around, but for now it seems to be working for me.
If you are returning raw HTML in the AJAX request you will probably need to add the CSS and JS references there. You are not really returning a view that would normally have a layout that includes the references.

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!

Categories

Resources