I am using the answer given on this question.
As a result, my html page looks like this:
<!DOCTYPE html>
<html>
<head>
<script src="path\jquery-2.1.1"></script>
<script>
function myFunction() {
alert('Clicked!');
$.ajax({
url: "http://localhost:51399/api/webapi",
type: 'GET',
success: function (data) {
alert(data.error);
$('#demo').html(data);
},
error: function (data) {
alert(data);
}
});
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>
When I click the button nothing happens. I am not sure if the ajax call is ever made or if there is no success on the callback. What am I missing and how can I fix it so that the GET REST call goes through to the URL I specified?
P.S.: I am a beginner at javascript and jquery.
Maybe try:
$.ajax({
url: "http://blockchain.info/latestblock",
type: 'GET',
success: function(data) {
$('#demo').html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("error: " + errorThrown + " || status: " + textStatus + " || data: " + jqXHR);
}
});
or (the more modern way):
function myFunction(){
$.ajax({
url: "http://blockchain.info/latestblock",
type: 'GET'
});
}
function handleData(data) {
$('#demo').html(data);
}
function handleError(jqXHR, textStatus, errorThrown) {
console.log("error: " + errorThrown + " || status: " + textStatus + " || data: " + jqXHR);
}
myFunction().fail(handleError)
myFunction().done(handleData);
Wold's answer above is completely valid. However, the issue with my code was that I was trying to reference the jquery.js file using its absolute path which is prohibited. Once I made the path relative (and added the extension...stupid me) the call went through.
Related
So, I made updates to this code to fix some issues that were pointed out in another question. The function runs, but returns {"readyState":0,"status":0,"statusText":"error"}. I switched from $.getJSON to $.ajax so I could send headers to hopefully fix the error, but it's still giving me the same error without much detail.
<HTML>
<head>
<title>Ecobee API PIN TEST</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function PINCode() {
apiKey = 'kmkbJCrEUbMBpO2I6E90QeYcueAz1p00'
// set all apiKey inputs to have apiKey value entered
$(".apiKey").each(function() {
$(this).val(apiKey);
});
var url = 'https://api.ecobee.com/authorize?response_type=ecobeePin&client_id=' + apiKey + '&scope=smartWrite';
$.ajax({
dataType: "json",
url: url,
headers: { 'Access-Control-Allow-Origin': '*' },
success: function(data) {
$("#authCode").val(data.code);
alert("JSON Ran");
var response = JSON.stringify(data, null, 4);
$('#response1').html(response);
}
})
// $.getJSON(url,function(data) {
// // set authCode to be code attribute of response
// $("#authCode").val(data.code);
// alert("JSON Ran")
// var response = JSON.stringify(data, null, 4);
// $('#response1').html(response);
// })
.fail(function(jqXHR, textStatus) {
$('#response1').html("The following error was returned: <br><br>" + JSON.stringify(jqXHR) + "<p>Please Contact <b>M2 AV Consulting</b> at <a href=mailto:support#m2avc.com?subject='EcobeePINSupport'>support#m2avc.com</a>")
console.log(textStatus);
});
})
</script>
<pre id="response1" class="code-json">(Response JSON will appear here...I hope.)</pre>
</body>
</HTML>
I am trying hard to fix this issue but still didn't get the solution, tried many links and code, but facing a bit problem to fix this.
ISSUE:
I have an input type 'Text' to search the employees name.
When I Start entering characters like 'WY', it shows all the names starting with WY.
Once I get the employee I need, I can move that to other control and Run PDF report (which loads in another Tab).
The issue is when I go back to the page where I should start searching the employees again, it won't search! as shown below:
Here is my ajax code :
$("#EmployeeSearchBox").bind('input propertychange', function () {
if ($('#EmployeeSearchBox').val() != '') {
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
UI Control :
<input type="text" id="EmployeeSearchBox" class="search-box" aria-multiselectable="true" />
Please let me know, what I should be doing to get it fixed.
This might be the reason for the issue
The $("#EmployeeSearchBox").bind('input propertychange', function () { ..}); might not be available in the DOM.
To ensure whether the EmployeeSearchBox and propertyChange handler are still alive, place an alert inside the propertychange function. If the alert is shown then the issue is some where else.
$("#EmployeeSearchBox").bind('input propertychange', function () {
if ($('#EmployeeSearchBox').val() != '') {
alert("Inside Property Change "); // Add this alert
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
what do you mean by bind it again
This is the function which is binding the EmployeeSearchBox with the DOM $("#EmployeeSearchBox").bind('input propertychange', function () {.... and when you are moving to the PDF tab and coming back again to SearchBox tab the binding of this element is lost, it means the DOM doesnot know what to be done when the property change is fired on the EmployeeSearchBox. Two ways to solve it
1) Ensure that the Event handler is always present in the DOM even when you navigate between tabs.
2) If option 1 is not achievable in your scenario, kindly rebind the event handlers whenever you are coming to the search tab. Explicitly invoke this $("#EmployeeSearchBox").bind when you are in the search tab.
Please check that the ajax call has raised for your second search.. if not there must be a problem in condition checking area or function calling method. I always use this function for searching data
$("input").change(function(){
ajax call.....
})
Am upvoting the suggestion provided from "Clement Amarnath", which helped me to resolve this issue.
I found the fix for this , instead of using .Bind(), I used .on() inside (document), am posting the answer which I have fixed it.
Thanks all!
$(document).on("input propertychange", "#EmployeeSearchBox", function () {
if ($('#EmployeeSearchBox').val() != '') {
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
//error: function (XMLHttpRequest, textStatus, errorThrown) {
// alert(textStatus);
//}
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
NOTE :
below line too works :
.live() method
$("#EmployeeSearchBox").live('input propertychange', function () {... });
I have problem with get the returned data from a link . It is not working .
I have search more and try everything but it still not working . could anyone help me .
the link : https://www.routingnumbers.info/api/data.json?rn=13442323
my code is
<!DOCTYPE html>
<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(){
var request = $.ajax({
type: 'GET',
data: "rn=" + "54455445",
url: "https://www.routingnumbers.info/api/data.json",
success: function(data) {
alert("Data: " + data + "\nStatusA: " + status);
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Data: " + "Err" + "\nStatus: " + status);
console.log(jqXHR, textStatus, errorThrown);
request.abort();
}
});
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
Thank you
Well, first of all, I'd always advise using proper JSON formatting in ajax requests. The data attribute should be an object instead of a variable assignment. In the end, it doesn't actually matter; the request will complete with either format. It's always nice to look at consistently-formatted code, though. Regardless, the major problems that were causing the request to fail were the type of request you were making and its origin.
In the code you provided, you were making a request to an https address. The page you were requesting from, however, was not an https page, but an http page instead. This caused the request to return the error net::ERR_INSECURE_RESPONSE.
If you fix that, however, the request still won't complete successfully. This is because XMLHttpRequest doesn't allow requests to websites that aren't the same as the one that you are requesting from. For example, you could request content from routingnumbers.info if you're running the script from within routingnumbers.info itself, but not if you're running it from elsewhere. This can be fixed by specifying the request as a jsonp request instead of the default json request.
$("button").click(function(){
$.ajax({
type: "GET",
dataType: "jsonp",
async: true,
url: "http://www.routingnumbers.info/api/data.json",
data: {
rn: "54455445"
},
success: function(data) {
var array = [];
$.each(data, function(index, value){
array.push(index + ': ' + value);
});
alert(array.join("\n"));
},
error: function(data) {
alert(data.statusText);
}
});
});
JSFiddle
Hope this is helpful!
I inherited this project. I added the last 12 lines of code. The error doesn't have anything to do with what I added but it stops dev tools from stopping on a break point. The alert in my code works and gives me the correct data. But, I'm not getting the "checked" status on the checkbox I think I'm pointing at. Hard to debug. I'm getting "Uncaught TypeError: undefined is not a function". It appears right below a script> line. So it doesn't appear to be my code, but I can't find the problem. How can I debug this problem?
<script type="text/javascript">
colortab = function(tabName, color){
var tabs = ColdFusion.Layout.getTabLayout('mainTab');
var tab = tabs.getTab(tabName);
tab.el.dom.firstChild.firstChild.firstChild.style.color = color;
}
init = function(){
colortab('tab10', 'red');
}
</script>
<script type="text/javascript">
THIS IS WHERE THE ERROR SHOWS UP IN DEV TOOLS Uncaught TypeError: undefined is not a function
$(document).ready(function() {
//GetCityState = function(z){
//alert(z.value);
//$.ajax({
//type: 'Post',
//url: 'http://www.zip-info.com/cgi-local/zipsrch.exe',
//data: 'zip=' + z.value + '&Go=Go',
//success: function (response, textStatus, jqXHR) {
//alert('Response ' + response);
//},
//error: function(xhr, textStatus, errorThrown) {
// show error
//alert('error ' + errorThrown);
//}
//});
//}
$('#adminperson').click(function(){
ColdFusion.Window.show('AdminPersonWindow');
});
});
function SubmitAdminPersons() {
console.log("adminform " , $("#AdminPersonForm").serialize());
var AdminStr = $("#AdminPersonForm").serialize();
$.ajax({
type: 'Post',
url: 'cfc/updates.cfc?method=UpdateAdminPerson',
data: AdminStr,
success: function (response, textStatus, jqXHR) {
//alert('Response ' + response);
},
error: function(xhr, textStatus, errorThrown) {
// show error
alert('error ' + errorThrown);
}
});
ColdFusion.Window.hide('AdminPersonWindow');
alert('You have to refresh this page to see the new info.');
}
jQuery(document).ready(function() {
jQuery(".collapseContent").hide();
//toggle the componenet with class msg_body
jQuery(".collapseHeader").click(function()
{
jQuery(this).next(".collapseContent").slideToggle(500);
});
$('#jd_year').change(function() {
var jdyear = $('#jd_year').val();
//alert(jdyear);
if (jdyear){
$( "#skill_2" ).each(function( i ) {
if ( this.val() == "JD" ) {
this.checked;
return false;
}
});
}
});
});
</script>
I think this line "// show error" is not commented in your actual code.
Please check it in following code
$(document).ready(function() {
//GetCityState = function(z){
//alert(z.value);
//$.ajax({
//type: 'Post',
//url: 'http://www.zip-info.com/cgi-local/zipsrch.exe',
//data: 'zip=' + z.value + '&Go=Go',
//success: function (response, textStatus, jqXHR) {
//alert('Response ' + response);
//},
//error: function(xhr, textStatus, errorThrown) {
**// show error**
//alert('error ' + errorThrown);
//}
//});
//}
Here is the code to call webservice to return json
$('#page_job_list_pages').live('pageshow',function(){
try {
$.ajax({
url: "http://domain.com/json/" + encodeURIComponent(tid),
type: 'get',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('page_job_list_pages - failed to retrieve pages');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
$("#page_job_list_pages_list").html("");
$.each(data.nodes,function (node_index,node_value) {
console.log(JSON.stringify(node_value));
if(node_index != 0) {
var companyName = node_value.node.field_basic_info.match("Company:(.*)date");
$("#page_job_list_pages_list").append($("<li></li>",{"html":"<a href='#node_view' id='" + node_value.node.Nid + "' class='page_job_list_pages_list_title'>" + companyName[1] + "</a>"}));
}
});
$("#page_job_list_pages_list").listview("destroy").listview();
$("#page_job_list_pages_list").append('<a onclick="()" data-role="button" data-theme="a">TEST</a>');
}
});
}
catch (error) { alert("page_job_list_pages_list - " + error); }
});
this line is a button
$("#page_job_list_pages_list").append('<a onclick="()" data-role="button" data-theme="a">TEST</a>');
i want to call the jquery function to query the json again.
HOW to do that?
I've wrapped your query in a function. I am assuming this is what you want. I've also added the call in the click handlers of your buttons to query again.
Note:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). (Source: http://api.jquery.com/live/)
$('#page_job_list_pages').live('pageshow',function(){
queryJSON();
});
function queryJSON(){
try {
$.ajax({
url: "http://domain.com/json/" + encodeURIComponent(tid),
type: 'get',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('page_job_list_pages - failed to retrieve pages');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
$("#page_job_list_pages_list").html("");
$.each(data.nodes,function (node_index,node_value) {
console.log(JSON.stringify(node_value));
if(node_index != 0) {
var companyName = node_value.node.field_basic_info.match("Company:(.*)date");
$("#page_job_list_pages_list").append($("<li></li>",{"html":"<a href='#node_view' id='" + node_value.node.Nid + "' class='page_job_list_pages_list_title'>" + companyName[1] + "</a>"}));
}
});
$("#page_job_list_pages_list").listview("destroy").listview();
$("#page_job_list_pages_list").append('<a onclick="queryJSON();" data-role="button" data-theme="a">TEST</a>');
}
});
}
catch (error) { alert("page_job_list_pages_list - " + error); }
}
this line is a button
$("#page_job_list_pages_list").append('<a onclick="queryJSON();" data-role="button" data-theme="a">TEST</a>');