I'm really new in web services, so I would appreciate any help here. I have created a RESTful web service using Spring-boot. The code for my web service is simple as I'm just testing:
#RestController
public class MainController {
#RequestMapping("/test")
public String getStringTest(#RequestParam(value="name", defaultValue="Test") String name){
System.out.println("Name received: " + name);
return "HelloTest: " + name;
}
}
After deploying the web service, I'm able to access it using: http://localhost:8080/imagesTest and I get the "HelloTest" string in my browser, so it's working fine. But the problem is when When I try to access it using jQuery in a web page it's not working. This is the page:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<p id="info"></p>
</body>
</html>
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: "http://localhost:8080/test?name=Gabriel",
success: function(data){
alert("Success: " + data);
},
error: function(){
alert("Something went wrong.");
}
});
})
</script>
When I execute my page, I get the following error message in the console:
Uncaught ReferenceError: HelloTest is not defined(anonymous function)
# imagesTest?callback=jQuery1113027941066049970686_1447350578572&_=1447350578573:1
Any help on this would be very much appreciated so I can understand what's really going on.
Thank you in advance for your help.
dataType: 'jsonp' tells jQuery to expect JSONP, but your returning a plain string "HelloTest: Gabriel"
Change the dataType to something more suitable, such as "text" (or remove it completely)
$.ajax({
type: 'GET',
dataType: 'text',
url: "http://localhost:8080/test?name=Gabriel",
success: function(data){
alert("Success: " + data);
},
error: function(){
alert("Something went wrong.");
}
});
The possible values are listed in the api documentation of the $.ajax method
Related
I'm trying to call an API using a submit button but i'm getting the following errors when i inspect the page on Chrome:
Uncaught ReferenceError: CallApi is not defined
My code is as follows:
<script type="text/javascript" href="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
function CallApi(event)
{
var username = "****"
var password = "***"
var engagamentId=$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val();
if (engagamentId)
$.ajax({
url: 'https://hello.com/engagements/engagementdetails/'+ $('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(),
type: "GET",
crossDomain: true,
dataType: "jsonp",
jsonp: "json_callback",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)"
},
success: function (data) {
$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(data.EngagementID);
$('#ctl00_ctl05_fvlc_Form1_txtClientName').val(data.ClientName);
$('#ctl00_ctl05_fvlc_Form1_txtPOA').val(data.AccountingEndPeriod);
$('#ctl00_ctl05_fvlc_Form1_txtCurrentTaxYear').val(data.TaxYear);
$('#ctl00_ctl05_fvlc_Form1_txtEngagementManager').val(data.EngagementManager);
},
error:function(a,b,c)
{
alert(a.responseText);
//alert("Engagement not found!");
}
});
else alert("Please enter 'Engagement ID'");
}
And my button has the following HTML:
<input type="button" value="Get Engagement Details" onclick="CallApi(event)" class="RadButton RadButton_Cora rbButton rbRounded rbIconButton">
Could anyone advise what i'm doing wrong? I have looked at related questions/answers but can't seem to get it working.
Thanks!
the function is not defined, so most likely the javascript file is not included correctly.to prevent mistakes like this:
include files using src instead of href
<script src="myscripts.js"></script>
include files in the correct order (first jquery, then your script)
understand what the term hoisting means in js
check developer tools in chrome (network) to check if files are loaded correctly or check window.CallApi, since it should be defined globally
if you define scripts direclty in html, still wrap them with script tags <script>function CallApi(event) {console.log(event);};</script>
You are both trying to import JQuery and write a custom JS code in the same script tag.
You must include JQuery in a tag.
Then in another tag declare your custom JS code.
Do it this way (i'm just doing an alert for demonstration purpose) :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
function CallApi(event) {
alert('test')
}
</script>
</head>
<body>
<input type="button" value="Get Engagement Details" onclick="CallApi(event)" />
</body>
</html>
The following HTML file works for me, in so far as it can call your API url, and get a 404, then alert in the error callback:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function CallApi(event)
{
var username = "****"
var password = "***"
var engagamentId=$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val();
if (engagamentId)
$.ajax({
url: 'https://hello.com/engagements/engagementdetails/'+
$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(),
type: "GET",
crossDomain: true,
dataType: "jsonp",
jsonp: "json_callback",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
success: function (data) {
$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(data.EngagementID);
$('#ctl00_ctl05_fvlc_Form1_txtClientName').val(data.ClientName);
$('#ctl00_ctl05_fvlc_Form1_txtPOA').val(data.AccountingEndPeriod);
$('#ctl00_ctl05_fvlc_Form1_txtCurrentTaxYear').val(data.TaxYear);
$('#ctl00_ctl05_fvlc_Form1_txtEngagementManager').val(data.EngagementManager);
},
error:function(a,b,c)
{
alert(a.responseText);
//alert("Engagement not found!");
}
});
else alert("Please enter 'Engagement ID'");
}
</script>
<input type="button" value="Get Engagement Details" onclick="CallApi(event)"
class="RadButton RadButton_Cora rbButton rbRounded rbIconButton">
<input type="text" id="ctl00_ctl05_fvlc_Form1_txtEngagementID" value="foo" />
</html>
It doesn't work because on moment the DOM is created by the browser, the CallApi function doesn't exist yet. This occurs because of the order that element and the scripts is loaded. I believe if you insert the script in <head> section, the function should work.
I recommend change to something like this:
$ (document) .ready (function () {
$ ('#id-of-my-button-element').on('click', CallApi);
});
is it possible to call a page of another website from an ajax call ?
my guess is that is possible since connection is not denied , but i can't figure out how to make my ajax call works , I am calling a list of TV Channels of a website , but I am getting no results , would you please see if my script contains any errors
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl+"&callback=?",
data: "channelType="+all,
type: 'POST',
success: function(data) {
$('#showdata').html(data);
},
error: function(e) {
alert('Error: '+data);
}
});
}
showValues();
html div for results
<div id="showdata" name ="showdata">
</div>
Ajax calls are not valid across different domains.you can use JSONP. JQuery-ajax-cross-domain is a similar question that may give you some insight. Also, you need to ensure thatJSONP has to also be implemented in the domain that you are getting the data from.
Here is an example for jquery ajax(), but you may want to look into $.getJSON():
$.ajax({
url: 'http://yourUrl?callback=?',
dataType: 'jsonp',
success: processJSON
});
Another option is CORS (Cross Origin Resource Sharing), however, this requires that the other server to enable CORS which most likely will not happen in this case.
You can try this :
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl,
data: channelType="+all,
type: 'POST',
success: function (data) {
//do something
},
error: function(e) {
alert('Error: '+e);
}
});
}
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'm trying to replicate the WhateverOrigin service, seen here:
http://stackshare-importer.herokuapp.com/get_website?url=http://firebase.com
However when I try to run it on my browser this code which worked perfectly on WhateverOrigin no longer works with my dummy service:
$.getJSON("http://stackshare-importer.herokuapp.com/get_website?url=" + import_url + "&callback=?", function(data) {
console.log(data);
});
Uncaught SyntaxError: Unexpected token <
I just want to work with the html source string, how can I achieve this?
Edit:
Also tried this and get the same result:
$.ajax({
url: "http://stackshare-importer.herokuapp.com/get_website?url=" + import_url + "&callback=?",
jsonp: "callback",
dataType: 'jsonp',
success: function(response) {
console.log(data);
}
});
Sites like WhateverOrigin and AnyOrigin get the page you want and convert it to a JSON/JSONP object, which allows it to be used cross-origin.
If you are trying to replicate what those websites are doing, you will need to create a PHP script which gets the page as a variable and then converts it to JSON and outputs it in a JSONP object.
Change the PHP on your page "get_website" to:
<?php
$page = file_get_contents($_GET['url']);
echo 'jsonCallback({"html":'.json_encode($page, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT).'});';
?>
Then use this HTML/JS on any site to output the JSON:
<div class="stuffhere"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("document").ready(function () {
$.ajax({
type: 'GET',
url: 'http://stackshare-importer.herokuapp.com/get_website?url=http://firebase.com',
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
alert(json.html);
$("div.stuffhere").html(json.html);
}
});
});
</script>
..and it will work!
I would like to parse the xml data from a remote website http://services.faa.gov/airport/status/IAD?format=xml...But I was not able to parse the xml data and I am only getting error. But I was able to parse the JSON data from the same remote website http://services.faa.gov/airport/status/IAD?format=json. The code I have used to parse the xml data is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Aviation</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=xml",
dataType: "xml",
success: function (xml) {
result = xml.city;
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the city name" onclick=xmlparser() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
I was only getting the error as 'o Error' in the alert box since I have printed the error message. Anybody please helpout to parse the xml data from the remote website.
Note: I have also 'City' instead of 'city' but its not working...
Thanks in advance...
I don't believe that will work since the service is still returning xml. jsonp is expecting a n object literal as an argument to pass to the callback. I believe if you run this locally you'll realize there's no data being consumable in your success. Try this
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=json",
dataType: "jsonp",
success: function (data) {
document.myform.result1.value = data.city;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
Here is the example for creating a proxy with asp.net mvc 3. I just created an action that returns a ContentResult which maps to a string but I define the content type as text/xml. This simply just makes a webrequest to the service and reads the stream in to a string to send back in the response.
[HttpGet]
public ContentResult XmlExample()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://services.faa.gov/airport/status/IAD?format=xml");
string xml = null;
using (WebResponse response = request.GetResponse())
{
using (var xmlStream = new StreamReader(response.GetResponseStream()))
{
xml = xmlStream.ReadToEnd();
}
}
return Content(xml, "text/xml");
}
Your xmlParser function will look like this:
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "XmlExample",
dataType: "xml",
success: function (xml) {
result = $(xml).find("City").text();
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
jQuery ajax's converts the data by using $.parseXML internally which removes the requirement for us to even call this in the success block. At that point you have a jQuery object that you can use it's default DOM functions to find the City Node.
Make sure to replace the XmlExample with the url that it maps to based on your controller.
The solution is quite simple (mentioned in Pekka's comment)
1.On your server add a file IAD_proxy.php
2.Put the following code inside it
header("Content-type: text/xml; charset=utf-8");
echo file_get_contents('http://services.faa.gov/airport/status/IAD?format=xml');
3.Change the url in your Ajax request to IAD_proxy.php.
In case you're using any other server-side language, try to implement the same idea.
Edit: Please read about Parsing XML With jQuery, here's what I've tried and it's working.
Javscript:
$.ajax({
type: "GET",
url: "IAD_proxy.php",
dataType: "xml",
success: function (xml) {
alert($(xml).find('City').text());
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
Here I tried it with document.write($(xml).find('City').text());