Heres my email sending function:
function send() {
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe";
var message_name = "defender_send_message";
var data = {};
data.value1 = document.getElementById('textBox').value;
data.value2 = localStorage.getItem("AdminsEmail");
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log("Message Sent");
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.responseType = 'json';
xmlhttp.send(new FormData(data));
}
I wanted to create an email sending function with only pure js, not jquery or anything. I get the following errors when i click send:
(ignore the first error i fixed that already)
I had a jquery function that worked (but i had to get rid of it):
var message = localStorage.getItem("Message");
console.log(message + localStorage.getItem("AdminsEmail"));
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe"; // << YOUR KEY HERE
var message_name = "defender_send_message"; // << YOUR MESSAGE NAME HERE
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
$.ajax({
url: url,
data: {value1: message,
value2: localStorage.getItem("AdminsEmail")},
dataType: "jsonp",
complete: function(jqXHR, textStatus) {
console.log("Message Sent");
}
});
why would this work and my other function not?
EDIT 2 : Since it seems the endpoint doesn't actually return JSON, I think your original jQuery code wasn't correct either. You need to do more research into this iftt.com platform and how to use it. From what I can tell, it's meant to be used in a mobile app, not in the browser- it would be a normal POST XHR then, and CORS doesn't apply to mobile apps. They have this page for testing the endpoint- notice that it gives you an example using curl, a command-line tool, where again CORS doesn't apply. So I think you need to rethink things, this service is not designed to be used from a browser, like you are trying to do.
EDIT: since it turns out you are actually trying to use JSONP and not a plain XHR, all you need to do is implement that without jQuery- create a script tag with the server's URL and add a URL parameter to define your callback function to handle the data. This answer should give you the solution.
In your case the code might look like this :
http://www.codeply.com/go/bp/VRCwId81Vr
function foo(data)
{
// do stuff with JSON
console.log(data)
}
var script = document.createElement('script');
script.src = "https://maker.ifttt.com/trigger/defender_send_message/with/key/"+
"dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe?callback=foo";
document.getElementsByTagName('head')[0].appendChild(script);
Note that this doesn't work for me(but with your code, you would get Message sent printed to the console, so maybe you thought it was working?)- the response isn't JSON. Most likely the endpoint isn't actually meant to be used for JSONP?
My answer below only applies if you are trying to do a regular XHR in a browser without JSONP.
This happens because of the Cross Origin Resource Sharing policy of your browser. Your code is hosted at localhost, and it is trying to access a resource hosted at maker.ifttt.com through an XmlHttpRequest. In order to allow this to happen, the server at maker.ifttt.com would need to be configured to allow access from the localhost origin. Presumably you can not make that change as you don't control that server.
In your case, the best solution would be to make the request to maker.ifttt.com through your own server- CORS doesn't apply for server-to-server requests. Send the XmlHttpRequest to your server, take the data regarding the email from the request URL parameters, and then make the request to maker.ifttt.com using that data.
Related
I have a JSON script loaded from an external website. In its simplest form, the code has been like this (and working):
jQuery.getJSON("http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?",
function(data){
document.querySelector("output").textContent = data.postal_codes[0].city;
});
However, the website owner don't want jQuery if it's not crucial, so I recoded .getJSON to the request = new XMLHttpRequest(); model:
request = new XMLHttpRequest();
request.open("GET", "http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?", true);
request.onload = function() {
var data = JSON.parse(request.responseText);
document.querySelector("output").textContent = data.postal_codes[0].city;
};
request.onerror = function() { /* this gets called every time */ };
I've modified my code many times, read documentations over and over again, yet the .onerror function is the only one always displaying. This is the console:
Which in Norwegian says that this script requested CORS, that it can't find the origin in the head of Access-Control-Allow-Origin, and that the XMLHttpRequest had a network error, and says "no access".
There could be several reasons as to why this occurs:
1: There's something wrong with the new code
2: There's something in the .getJSON jQuery function (a hack?) that prevents the error from happening
3: There's something crucial in the new code that I have forgot adding
4: There's something with my browser (IE 11 at the moment)
5: Something else?
It would be lovely with some help on this.
DEMO: http://jsbin.com/muxigulegi/1/
That isn't a network error. It's a cross origin error. The request is successful but the browser is denying access to the response to your JavaScript.
Since you have callback=? in the URL, jQuery will generate a JSONP request instead of an XMLHttpRequest request. This executes the response as a script instead of reading the raw data.
You are manually creating an XMLHttpRequest, so it fails due to the Same Origin Policy.
Create a JSONP request instead.
From http://api.jquery.com/jquery.getjson/:
JSONP
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
You do have a callback. Which means that the JQuery function can request data from another domain, unlike your XHR call.
I need to call OpenMRS REST API from Java script to get data from OpenMRS. Below is my java script code:
function myfunction(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8081/openmrs-standalone/ws/rest/v1/person?q=John", false);
xhr.setRequestHeader("Authorization: Basic YWRtaW46QWRtaW4xMjM");
xhr.send("");
alert(xhr.status);
}
Where YWRtaW46QWRtaW4xMjM is my base64 coded username:password as explained here. If I do not put the authorization line in the code and check the web app using Firebug, it returns 401 unauthorized status that is expected. But if I put the authorization, nothing is returned and in firebug I do not see any response as well. If I check the URL directly on browser, the page asks for username and password and after giving correct credential, it returns the data normaly. So I am getting some problem of providing the http authentication right from the java script of the app. I have also considered the methods explained here but no luck. Can anyone please help me to authorize the http request right from the javascript?
Here is another similar but different example of how to set the header for authorization purposes, but instead using JQuery and AJAX.
var token = "xyz"
var url = "http://localhost:8081/openmrs-standalone/ws/rest/v1/person?q=John"
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + token)
},
})
.done(function (data) {
$.each(data, function (key, value) {
// Do Something
})
})
.fail(function (jqXHR, textStatus) {
alert("Error: " + textStatus);
})
Below is also an example of how you might get an access token using xhr instead of AJAX.
var data = "grant_type=password&username=myusername#website.com&password=MyPassword";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://somewebsite.net/token");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("client_id", "4444-4444-44de-4444");
xhr.send(data);
Beware of cross-site domain requests(if you're requesting a token that's not on localhost or within the domain that you are currently working in), as you'll need CORS for that. If you do run into a cross-domain issue, see this tutorial for help, and be sure you have enabled CORS requests from the API as well.
I am developing a GIS Map Java web application using jsp, javascript/ajax/jQuery which is deployed in tomcat server. I need to implement cross-domain access here to get response from google api which return response in json format. But since cross domain access is not possible with xmlhttp, I cant get a response.
I have seen some posts suggesting the use of proxy.php in client side. But I am not using php and I would like to know if there is anyway to implement this using jsp/javascript alone. Is there any special configuration to be set in tomcat?? Kindly help.
Here is what i try to do:
var url = "http://maps.googleapis.com/maps/api/directions/json?origin=26.849307092121,75.781290279188&destination=26.932491611988,75.805420139913&alternatives=true&sensor=false";
xmlhttp.open("GET",url,false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send();
function AJAX_addShortestRoute() {
// if(xmlhttp.readyState == 4) {
var response=xmlhttp.responseText;
// document.write(response);
alert(response);
}`
But the request is never processed, since cross-domain access is not possible. Kindly help
Thanks and Regards
Ginger.
I resolved the issue. The only solution for cross domain (which I think) is use cross domain access through proxy server..
Here is how it is done.
var mapsUrl = 'http://maps.googleapis.com/maps/api/directions/json?origin='+source_y+','+source_x+'&destination='+dest_y+','+dest_x+'&alternatives=true&sensor=true';
var encodedUrl = encodeURIComponent(mapsUrl);
var proxyUrl = 'http://jsonp.guffa.com/Proxy.ashx?url=' + encodedUrl;
$.ajax({
url: proxyUrl,
dataType: 'jsonp',
cache: false,
success: function (result) {
//Your code goes here
}
});
I have browsed most CORS and JSON request topics, and cannot understand why this first script works, but not the second. I would love to be educated in the ways of CORS and Javascript and XMLHTTPRequest2 and AJAX.
This works:
function wfs() {
var url = 'http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles&callback=getRoute';
var script = document.createElement('script');
script.type="text/javascript";
script.src=url;
document.getElementsByTagName('head')[0].appendChild(script);
}
function getRoute(response) {
console.log(response);
}
This does not work:
function wfs() {
var url = 'http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function(e) {
if (this.status == 200) {
var json = this.response;
console.log(json);
}
};
xhr.send();
}
Firebug shows a Red 200 Null Response.
However, the second script does work when I use a different url:
var url = 'http://ip.jsontest.com/?mime=2';
The first domain, http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles, does not implement CORS (i.e. does not send a usable Access-Control-Allow-Origin header). http://ip.jsontest.com/?mime=2 does. There is nothing you can do about this -- it depends on the server.
The first block of code uses JSONP. What this actually does is inject a script tag into the document. Script tags can have external sources (if they are not of the same scheme, they may be blocked for security reasons). This allows the server to essentially send you javascript code that you insert into a <script> that gets run immediately.
I developed a small Javascript/jQuery program to access a collection of pdf files for internal use. And I wanted to have the information div of a pdf file highlighted if the file actually exist.
Is there a way to programmatically determine if a link to a file is broken? If so, How?
Any guide or suggestion is appropriated.
If the files are on the same domain, then you can use AJAX to test for their existence as Alex Sexton said; however, you should not use the GET method, just HEAD and then check the HTTP status for the expect value (200, or just less than 400).
Here's a simple method provided from a related question:
function urlExists(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.status < 400);
}
};
xhr.open('HEAD', url);
xhr.send();
}
urlExists(someUrl, function(exists) {
console.log('"%s" exists?', someUrl, exists);
});
Issue is that JavaScript has the same origin policy so you can not grab content from another domain. This won't change by upvoting it (wondering about the 17 votes).
I think you need it for external links, so it is impossible just with .js ...
If the files are not on an external website, you could try making an ajax request for each file. If it comes back as a failure, then you know it doesn't exist, otherwise, if it completes and/or takes longer than a given threshold to return, you can guess that it exists. It's not always perfect, but generally 'filenotfound' requests are quick.
var threshold = 500,
successFunc = function(){ console.log('It exists!'); };
var myXHR = $.ajax({
url: $('#checkme').attr('href'),
type: 'text',
method: 'get',
error: function() {
console.log('file does not exist');
},
success: successFunc
});
setTimeout(function(){
myXHR.abort();
successFunc();
}, threshold);
You can $.ajax to it. If file does not exist you will get 404 error and then you can do whatever you need (UI-wise) in the error callback. It's up to you how to trigger the request (timer?) Of course if you also have ability to do some server-side coding you can do a single AJAX request - scan the directory and then return results as say JSON.
Like Sebastian says it is not possible due to the same origin policy. If the site can be published (temporarily) on a public domain you could use one of the link checker services out there. I am behind checkerr.org
As others have mentioned, because of JavaScript's same origin policy, simply using the function from the accepted answer does not work. A workaround to this is to use a proxy server. You don't have to use your own proxy for this, you can use this service for example: https://cors-escape.herokuapp.com (code here).
The code looks like this:
var proxyUrl = "https://cors-anywhere.herokuapp.com/";
function urlExists(url, callback) {
var sameOriginURL = proxyUrl + url;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.status < 400);
}
};
xhr.open('HEAD', sameOriginURL);
xhr.send();
}
urlExists(someUrl, function(exists) {
console.log('"%s" exists?', someUrl, exists);
});