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>
Related
I am trying below snippet of code for face identify of azure samples with proper Subscription-Key. I get bad request 400 - can any one please help me how to send request body to work for this ajax call.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
};
$.ajax({
url: "https://api.cognitive.azure.cn/face/v1.0/identify?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","MY_ACCESS_KEY");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
The url seems to be bad here. Two things: 1) You need to append location before api.cognitive.microsoft.com and 2). .cn should be .com. Your url may look like this, depending on your location:
url: "https://westus.api.cognitive.azure.com/face/v1.0/identify?"
More locations and details are here: https://eastasia.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395239
Try
data: JSON.stringify({name: "Test"})
This question is a followup of this one. I have created a simple example to check how code is executed within the handler. For the form
<form id="calendar_id" method="post">
Insert date: <input id="date_id" type="text" name="l_date" required>
</form>
I'm trying to retrieve the fields using the following javascript:
function get_form_data_uid($form) {
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function (n, i) {
indexed_array[n['name']] = n['value'];
});
indexed_array['uid'] = 'badbfadbbfi';
return indexed_array;
}
$("#calendar_id").submit(function (e) {
var uri, method, formId, $form, form_data;
// Prevent default submit
e.preventDefault();
e.stopImmediatePropagation();
uri = "/";
method = "POST";
formId = "#calendar_id";
$form = $(formId);
form_data = get_form_data_uid($form);
alert("form_data " + form_data);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
// Setting async to false to give enough time to initialize the local storage with the "token" key
async: false,
dataType: "json",
data: form_data
};
// Make the request
$.ajax(request).done(function (data) { // Handle the response
// Attributes are retrieved as object.attribute_name
console.log("Data from change password from server: " + data);
alert(data.message);
}).fail(function (jqXHR, textStatus, errorThrown) { // Handle failure
console.log(JSON.stringify(jqXHR));
console.log("AJAX error on changing password: " + textStatus + ' : ' + errorThrown);
});
});
However, the code within the handler is not executed (the alert is not shown). Why?
Edit:
The code works jsfiddle but not in firefox.
At least, you are calling a function get_form_data_with_token() which is not defined anywhere in your posted code. Perhaps you meant to call your get_form_data_uid().
Would have just made this a comment, but apparently cannot.
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!
Here is a code to POST JSON data. It should work . But I am not sure where I did the mistake . probably a silly one, but unable to detect
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script language="javascript" type="text/javascript">
<!--
function greeter() {
var accx = 5;
var accy = 6;
var accz = 7;
var output = [];
output[0] = {
name: "Accel_X",
value: accx.toString(), // retrieve x
};
output[1] = {
name: "Accel_Y",
value: accy.toString(), // retrieve y
};
output[2] = {
name: "Accel_Z",
value: accz.toString() // retrieve z
};
var fromData = {};
fromData.output = output;
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
$.ajax({
url: "http://posttestserver.com/post.php",
type: "POST",
headers: {
"content-type": "application/json"
},
data: fromDatan,
dataType: "JSON",
success: function(fromDatan, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
}
//-->
</script>
</head>
<body>
<button onclick="greeter();">Click me</button>
</body>
</html>
I am unable to POST. I tried with POSTman chrome extension to POST data. It was working. WHy it is not working here I am not able to detect.
Your code worked for me when I removed the headers parameter from the $.ajax() call.
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.