Uncaught ReferenceError: CallApi is not defined - javascript

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

Related

PHP & JS - append html and scripts on page

I'm using an ajax call to append a MVC partial view with some styles sheets and script files to my php page.
However it is not appending de <script> tags. I already checked my HTTP request on the network and it really brings those tags.
My code:
$.ajax({
type: 'POST',
url: 'http://localhost:63322/MyController/MyAction', //external url project
data: JSON.stringify(parameters),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
crossDomain: true,
processdata: true,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Headers": "*"
},
success: function(result){
$(".pageContainer").html(result);
},
error: function(er){ alert('Error'); }
});
On ajax success function I already tried:
to use $(".pageContainer").empty().append(result)
to separate the script tags and add to <head> like this:
var elems = $(result);
var scripts = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() == "script";
}catch(er){ return false; }
});
var remainElems = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() != "script";
}catch(er){ return false; }
});
$.each(scripts, function(){ $('head')[0].appendChild(this); });
$(".pageContainer").append(remainElems);
to give some time before appending with setTimeout(function(){ $(".pageContainer").html(result); }, 1000);
to change <script> tags to <link type="text/javascript" src="http://someurl.com" rel="tag"/> and it was appended but the code wasn't executed
But nothing works.
What is wrong? What I'm missing?
My PHP page uses jquery-1.8.3 and jquery-ui-1.9.2.custom. This is the problem?
NOTE:
My question is very different from that on: Executing inside retrieved by AJAX
If you read both you will see they are very different. I already readed what and noticed that.
Solved. I don't know why but seems jquery-1.8.3 don't performs the insertion of the <script> tags to the html code dynamically.
I changed
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
to
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
and now it works.

Uncaught ReferenceError when calling REST Service using jQuery

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

XML Parsing remote server

I have followed some tutorials on how to parse XML from remote websites and came across the wonderfully articulated question and answer in stackoverflow.
However even after following the question, following program is not working.
<!DOCTYPE html>
<html>
<head>
<title>Aviation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.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).find("City").text();
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>
The website which I am trying to parse is same.
US FAA
Also I want to develop it as stand alone application i.e. Just HTML interacting with the remote website.
As mentioned, you can (need to) use jsonp because faa.gov apparently forgot to add the appropriate header to their API responses.
By the way - always prefer json over xml with Javascript - it's so much nicer to work with.
// ask faa.gov to add the HTTP header "Access-Control-Allow-Origin: *" to their response
// then you can use this
// jQuery.getJSON('http://services.faa.gov/airport/status/IAD?format=json');
jQuery.ajax({
url: 'http://services.faa.gov/airport/status/IAD?format=json',
dataType: 'jsonp',
success: function (data) {
document.myform.result1.value = data.city;
}
});

What is ReferenceError and when its counted

I m trying to send json data via ajax.but I m getting
ReferenceError: $ is not defined
Here is my code
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#btnSubmit").click(function () {
var email = $("#email").val();
var password = $("#pwd").val();
authenticate(email, password);
});
});
function authenticate(email, password) {
$.ajax
({
type: "POST",
url: "authenticate.php",
dataType: 'json',
async: false,
data: '{"email": "' + email + '", "password" : "' + password + '"}',
success: function () {
}
})
}
You must include jQuery on the site. Try adding the following script to access jQuery from a CDN at the begining of the page's head section:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Add this inside your head tag
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
The error may cause because of jquery conflict,If you already included jquery
Try jQuery.noConflict()
$ in there is about jQuery which is a javascript library that simplifies javascript usage. In order to use jQuery, you must include it into your page e.g.:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
But the place is important, it must be before other <script> tags which contains jQuery functions(starting with $ or jQuery).

Javascript not performing Ajax Call

I have a HTML page which i am running on localhost. I want to access some data from a Python script and use it in my HTML page, The Ajax call in the function doesn't work, If i remove it the program runs perfectly. Any help?
Javascript Function :
<script src="/js/jquery.min.js" type = "text/javascript" ></script>
<link rel="stylesheet" href="LoginStyle.css" type="text/css" />
<script type = "text/javascript" >
function getData()
{
//Code doesn't even enter this function but when i remove the $.ajax part it enters the function
alert("I AM HERE");
$.ajax(
{
type: "GET",
url: "/cgi-bin/check.py" // Path of the script/code i want to run
success: function(response)
{
$("#username").text(data); //this is where i should get the response, Not sure about the syntax i.e. whether i should
//output in a <div> tag or a text box
}
});
}
Calling the Function in HTML like this:
<form name="login-form" class="login-form" action="" method="post" onsubmit="getData();return false;"">
<input id="Uname" name="username" type="text" class="input username" placeholder="Username" />
Python Script:
#!/usr/bin/python
from StringIO import StringIO
import json
def htmlData():
content=json.loads('{"access": {"token": {"issued_at": "2013-04-18T14:40:23.299903", "expires": "2013-04-19T14:40:23Z", "id": "4c5ef01f52c7404fb5324c520d25d1fe"}}}')
data=json.dumps(content, indent=4, separators = (', ', ': '))
print data
return
htmlData()
You have a missing , in the url property
function getData() {
//Code does not even enter this function but when i remove the $.ajax part it enters the function
alert("I AM HERE");
$.ajax({
type: "GET",
//--> here missing , in url
url: "/cgi-bin/check.py", // Path of the script/code i want to run
success: function (response) {
$("#username").text(data); //this is where i should get the response, Not sure about the syntax i.e. whether i should
//output in a <div> tag or a text box
}
});
}
Try using, you have missed to add , end of url string
url: "/cgi-bin/check.py",
instead of
url: "/cgi-bin/check.py"

Categories