Related
Ive been trying to implement the drive API in my angularjs app. I want to download a pdf file so I use this following code.
$scope.getFile = function(id) {
console.log(id);
//console.log(fileId);
if (id != null) {
var request = gapi.client.drive.files.get({
'fileId': id,
'alt': 'media'
});
request.execute(function(resp) {
console.log('response: ' + resp);
});
}
}
but my console.log prints 'false'. I dont know why its really making me crazy I checked the network tab in inspect element and found the response correctly as a base64 string.
I also called atob(resp) which says that the text to be decoded is not correctly encoded. but i used an online base64 decoder and it works perfectly the pdf is opening. please help me im stuck here
Simply use then instead of execute:
var request = gapi.client.drive.files.get({
'fileId': id,
'alt': 'media'
});
request.then(function(resp) {
console.log('response: ' + resp);
});
Okay so I am new to AngularJS, and am trying to get data from an external API. The end result of this is basically going to help me understand angularjs, using external data, some more as well as getting some stats for Call Of Duty Ghosts for my account or others that I search for.
I know that $http.jsonp is the way to go, but the API doesn't really support it as well as CORS... I have accounted for that. I have been able to use jquery to test to make sure I can do it, but am unable to figure it out with AngularJS.
One issue I am having using whateverorigin and anyorigin from https://stackoverflow.com/a/7910570/1888585 and https://stackoverflow.com/a/6104416/1888585 is that I am getting http error 500 (Internal server error)
Without them I am getting an error regarding the json I am getting (which is valid json, checked with json linter) -> 'Uncaught SyntaxError: Unexpected token : '
So here is what I have:
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-controller="GhostsCtrl">
<div id="text">
Data from site: {{getGhostData()}}
Data from site: {{info}}
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.15/angular.js"></script>
<script>
var myApp = angular.module('myApp', []);
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url="+url+"&callback=?";
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
//-----------
myApp.service('dataService', function($http) {
console.log("in service!!");
this.getData = function() {
console.log("http fn");
resp = "test";
// from here i get the syntax error
$http.jsonp("http://"+url+"&callback=JSON_CALLBACK")
.success(function(data) {
console.log("Data gotten");
console.log(data.contents.user);
resp = "Success";
}).error(function(data ) {
console.log("error");
resp = "error";
});
return resp;
}
});
myApp.controller('GhostsCtrl', function($scope, $http, dataService){
$scope.info = null;
$scope.info = dataService.getData();
$scope.getGhostData = function() {
// from here I get the 500 error
delete $http.defaults.headers.common['X-Requested-With'];
$http.jsonp(wrapURL4).success(function(data) {
console.log("success: "+data.contents);
$scope.info = data.contents.user;
}).error(function(data) {
console.log("error: " + data);
});
}
});
</script>
</body>
</html>
And for my jquery code that works just fine:
$.getJSON('http://anyorigin.com/dev/get?url=api.codcp.com/user_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=?', function(data){
$.each(data.contents.user, function(val, idx) {
$("#text span").append(val+" ");
})
console.log(data.contents.user);
});
The json that comes back is as follows:
{"user":{"profile":{"ucdid":"3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c","gamertag":"xNF6xVENGE","network":"xbl","image":"http://avatar.xboxlive.com/avatar/xNF6xVENGE/avatarpic-l.png","kdr":1.109316019930545,"winr":2.7632311977715878,"kill":14694,"deaths":13246,"wins":992,"losses":359,"hoursPlayed":147.32049180327868,"currentStreak":0,"preferredWeapon":"weapon.iw6_arx160"},"squadMember":{"gamertag":"Erskine","xp":1031872,"background":20,"patchbacking":0,"patch":"patch_590","level":57,"nextLevelXp":1070000,"nextLevel":58,"prevLevel":56,"prevLevelXp":1030000,"progress":0.0468,"prestige":6},"careerHistory":{"blackops2prestige":3,"mw3prestige":6,"nextreadblackops2":1405837382,"nextreadmw3":1405841587,"playedblackops2":true,"playedmw3":true},"accounts":["xbl","ucd"],"clan":{"teamId":34018,"name":"xATFWx","memberCount":24,"tag":"ATFW","motto":"Search & destroy ","mottoBg":22,"motd":"","stats":null,"entitlements":268435448,"cxp":1991990,"kdr":1.5,"winp":74,"chat_token":"a2236f048c2a5ab71473b6765909a7f88b8716782dff8fd7b1f9df43b4b2c00ad60ba1e1a47cbea0153f590b89b698de9b91e240a8427fae4a9d8d48ea10d4fe941ab40f62acca0497e3b9c39967621abb9d6c2863ac1935d4fc193b44e2bb19","clanLevel":25,"progress":1,"nextLevelXp":1991990,"cxpNeeded":0,"nextLevel":25,"membership":0,"invited":null}}}
If there is a way I can either call jquery from angularjs easily, or avoid either error I get would be great.
I created a fiddle to figure out what your problem may be and found out that your return statement was getting fired before parsing the data in the service. I have modified the service in order to return a callback and it will work fine.
Since I cannot mock your server request here is sample fiddle and code snippet
myApp.service('dataService', function($http) {
console.log("in service!!");
return {
getData: function(callback) {
console.log("http fn");
resp = "test";
// from here i get the syntax error
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data.found);
resp="success";
callback(resp);
});
}
}
});
Looks like there are 2 reasons the anyorigin URL is not working.
The URL parameter needs to be properly encoded.
The callback should be JSON_CALLBACK instead of ?
Try this...
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url=" + encodeURIComponent(url) +"&callback=JSON_CALLBACK";
This should build this URL which properly returns a JSONP response that can be consumed by angular:
http://anyorigin.com/get/?url=api.codcp.com%2Fuser_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=JSON_CALLBACK
See this Fiddle: Live Demo
The jQuery's $.getJSON() is not a jsonp, so if you are able to retrieve the data by $.getJSON(), you could also do it with a normal $http.get() (of course with the use of anyorigin.com).
It seems the api.codcp.com doesn't support JSONP, it response with a normal JSON regardless of a callback=? exists in a url or not.
Fix this for starters, as it is just mixing single and double quote strings in concatenation:
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
By the way watch out. He is out there to get you !
Motto:
Search & destroy
and he's armed!
If you have not figured out the jsonp callback in angularjs! here is something that helped me:
$http.jsonp("http://anywebsite.com/?json=get_recent_post&callback=JSON_CALLBACK")
I hope you find this helpful.
jv
Firstly, thanks so much in advance for any help you might be able to give me on this!
Right, what I want to do, is to call a php script to run server side, which takes in a single value (which will be an email) and write it to a text file.
This is the .php file that I want run. I haven't added any of the email functionality, but after hours of trying I can't even seem to get it to create a text file and directory. If I run it in the IDE, it runs perfectly, it creates the script and displays the "test me" text at the bottom. However, when It runs from the jquery call, all it does it read the text at the bottom of the file. This is where I call it in jquery:
$(document).ready(function()
{
$("#emailForm").submit(function()
{
alert("Beginning jquery");
$("#div1").load("handleEmailAddresses.php");
alert("Load called");
//$.post("handleEmailAddresses.php");
});
I've also tried the post function you can see commented out. Nothing works. Here is the php file that is called:
<html>
<?php
$dir = 'myDir';
if ( !file_exists($dir) )
{
mkdir ($dir, 0777);//This just gives me r/w access to the folder
}
file_put_contents ($dir.'/test.txt', 'Hello File');
?>
Test Text
</html>
Please help, its killing me! Thanks so much!
Try Ajax
$.ajax({
url : '/handleEmailAddresses.php',
});
and if you want to check also:
$.ajax({
url : '/handleEmailAddresses.php',
}).done(function() {
console.log('completed');
});
Use This Script and try
Jquery:
$(document).ready(function()
{
$("#emailForm").submit(function(e)
{
e.preventDefault();
alert("Beginning jquery");
$("#div1").load("handleEmailAddresses.php", function(response, status, xhr) {
if (status == "error")
{
var msg = "Sorry but there was an error: ";
alert(msg + xhr.status + " " + xhr.statusText);
}
else
{
alert("Load Compleated");
}
});
});
PHP :
<?php
$dir = 'myDir';
if ( !file_exists($dir) )
{
if (!mkdir($dir, 0)) {
echo('Failed to create folders...');
exit;
}
}
$r = file_put_contents ($dir.'/test.txt', 'Hello File');
if ($r)
echo "Success";
else
echo "Error";
?>
I want my website to have the ability to send an email without refreshing the page. So I want to use Javascript.
<form action="javascript:sendMail();" name="pmForm" id="pmForm" method="post">
Enter Friend's Email:
<input name="pmSubject" id="pmSubject" type="text" maxlength="64" style="width:98%;" />
<input name="pmSubmit" type="submit" value="Invite" />
Here is how I want to call the function, but I'm not sure what to put into the javascript function. From the research I've done I found an example that uses the mailto method, but my understanding is that doesn't actually send directly from the site.
So my question is where can I find what to put inside the JavaScript function to send an email directly from the website.
function sendMail() {
/* ...code here... */
}
You can't send an email directly with javascript.
You can, however, open the user's mail client:
window.open('mailto:test#example.com');
There are also some parameters to pre-fill the subject and the body:
window.open('mailto:test#example.com?subject=subject&body=body');
Another solution would be to do an ajax call to your server, so that the server sends the email. Be careful not to allow anyone to send any email through your server.
Indirect via Your Server - Calling 3rd Party API - secure and recommended
Your server can call the 3rd Party API. The API Keys are not exposed to client.
node.js
const axios = require('axios');
async function sendEmail(name, email, subject, message) {
const data = JSON.stringify({
"Messages": [{
"From": {"Email": "<YOUR EMAIL>", "Name": "<YOUR NAME>"},
"To": [{"Email": email, "Name": name}],
"Subject": subject,
"TextPart": message
}]
});
const config = {
method: 'post',
url: 'https://api.mailjet.com/v3.1/send',
data: data,
headers: {'Content-Type': 'application/json'},
auth: {username: '<API Key>', password: '<Secret Key>'},
};
return axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
}
// define your own email api which points to your server.
app.post('/api/sendemail/', function (req, res) {
const {name, email, subject, message} = req.body;
//implement your spam protection or checks.
sendEmail(name, email, subject, message);
});
and then use use fetch on client side to call your email API.
Use from email which you used to register on Mailjet. You can authenticate more addresses too. Mailjet offers a generous free tier.
Update 2023: As pointed out in the comments the method below does not work any more due to CORS
This can be only useful if you want to test sending email and to do this
visit https://api.mailjet.com/stats (yes a 404 page)
and run this code in the browser console (with the secrets populated)
Directly From Client - Calling 3rd Party API - not recommended
in short:
register for Mailjet to get an API key and Secret
use fetch to call API to send an email
Like this -
function sendMail(name, email, subject, message) {
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.set('Authorization', 'Basic ' + btoa('<API Key>'+":" +'<Secret Key>'));
const data = JSON.stringify({
"Messages": [{
"From": {"Email": "<YOUR EMAIL>", "Name": "<YOUR NAME>"},
"To": [{"Email": email, "Name": name}],
"Subject": subject,
"TextPart": message
}]
});
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: data,
};
fetch("https://api.mailjet.com/v3.1/send", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
sendMail('Test Name',"<YOUR EMAIL>",'Test Subject','Test Message')
Note: Keep in mind that your API key is visible to anyone, so any malicious user may use your key to send out emails that can eat up your quota.
I couldn't find an answer that really satisfied the original question.
Mandrill is not desirable due to it's new pricing policy, plus it required a backend service if you wanted to keep your credentials safe.
It's often preferable to hide your email so you don't end up on any lists (the mailto solution exposes this issue, and isn't convenient for most users).
It's a hassle to set up sendMail or require a backend at all just to send an email.
I put together a simple free service that allows you to make a standard HTTP POST request to send an email. It's called PostMail, and you can simply post a form, use JavaScript or jQuery. When you sign up, it provides you with code that you can copy & paste into your website. Here are some examples:
JavaScript:
<form id="javascript_form">
<input type="text" name="subject" placeholder="Subject" />
<textarea name="text" placeholder="Message"></textarea>
<input type="submit" id="js_send" value="Send" />
</form>
<script>
//update this with your js_form selector
var form_id_js = "javascript_form";
var data_js = {
"access_token": "{your access token}" // sent after you sign up
};
function js_onSuccess() {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+Successfully+Sent%21&isError=0";
}
function js_onError(error) {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+could+not+be+sent.&isError=1";
}
var sendButton = document.getElementById("js_send");
function js_send() {
sendButton.value='Sending…';
sendButton.disabled=true;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
js_onSuccess();
} else
if(request.readyState == 4) {
js_onError(request.response);
}
};
var subject = document.querySelector("#" + form_id_js + " [name='subject']").value;
var message = document.querySelector("#" + form_id_js + " [name='text']").value;
data_js['subject'] = subject;
data_js['text'] = message;
var params = toParams(data_js);
request.open("POST", "https://postmail.invotes.com/send", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(params);
return false;
}
sendButton.onclick = js_send;
function toParams(data_js) {
var form_data = [];
for ( var key in data_js ) {
form_data.push(encodeURIComponent(key) + "=" + encodeURIComponent(data_js[key]));
}
return form_data.join("&");
}
var js_form = document.getElementById(form_id_js);
js_form.addEventListener("submit", function (e) {
e.preventDefault();
});
</script>
jQuery:
<form id="jquery_form">
<input type="text" name="subject" placeholder="Subject" />
<textarea name="text" placeholder="Message" ></textarea>
<input type="submit" name="send" value="Send" />
</form>
<script>
//update this with your $form selector
var form_id = "jquery_form";
var data = {
"access_token": "{your access token}" // sent after you sign up
};
function onSuccess() {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+Successfully+Sent%21&isError=0";
}
function onError(error) {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+could+not+be+sent.&isError=1";
}
var sendButton = $("#" + form_id + " [name='send']");
function send() {
sendButton.val('Sending…');
sendButton.prop('disabled',true);
var subject = $("#" + form_id + " [name='subject']").val();
var message = $("#" + form_id + " [name='text']").val();
data['subject'] = subject;
data['text'] = message;
$.post('https://postmail.invotes.com/send',
data,
onSuccess
).fail(onError);
return false;
}
sendButton.on('click', send);
var $form = $("#" + form_id);
$form.submit(function( event ) {
event.preventDefault();
});
</script>
Again, in full disclosure, I created this service because I could not find a suitable answer.
I know I am wayyy too late to write an answer for this question but nevertheless I think this will be use for anybody who is thinking of sending emails out via javascript.
The first way I would suggest is using a callback to do this on the server. If you really want it to be handled using javascript folowing is what I recommend.
The easiest way I found was using smtpJs. A free library which can be used to send emails.
1.Include the script like below
<script src="https://smtpjs.com/v3/smtp.js"></script>
2. You can either send an email like this
Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : 'them#website.com',
From : "you#isp.com",
Subject : "This is the subject",
Body : "And this is the body"
}).then(
message => alert(message)
);
Which is not advisable as it will display your password on the client side.Thus you can do the following which encrypt your SMTP credentials, and lock it to a single domain, and pass a secure token instead of the credentials instead.
Email.send({
SecureToken : "C973D7AD-F097-4B95-91F4-40ABC5567812",
To : 'them#website.com',
From : "you#isp.com",
Subject : "This is the subject",
Body : "And this is the body"
}).then(
message => alert(message)
);
Finally if you do not have a SMTP server you use an smtp relay service such as Elastic Email
Also here is the link to the official SmtpJS.com website where you can find all the example you need and the place where you can create your secure token.
I hope someone find this details useful. Happy coding.
You can find what to put inside the JavaScript function in this post.
function getAjax() {
try {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (try_again) {
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
} catch (fail) {
return null;
}
}
function sendMail(to, subject) {
var rq = getAjax();
if (rq) {
// Success; attempt to use an Ajax request to a PHP script to send the e-mail
try {
rq.open('GET', 'sendmail.php?to=' + encodeURIComponent(to) + '&subject=' + encodeURIComponent(subject) + '&d=' + new Date().getTime().toString(), true);
rq.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 400) {
// The request failed; fall back to e-mail client
window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
}
}
};
rq.send(null);
} catch (fail) {
// Failed to open the request; fall back to e-mail client
window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
}
} else {
// Failed to create the request; fall back to e-mail client
window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
}
}
Provide your own PHP (or whatever language) script to send the e-mail.
I am breaking the news to you. You CAN'T send an email with JavaScript per se.
Based on the context of the OP's question, my answer above does not hold true anymore as pointed out by #KennyEvitt in the comments. Looks like you can use JavaScript as an SMTP client.
However, I have not digged deeper to find out if it's secure & cross-browser compatible enough. So, I can neither encourage nor discourage you to use it. Use at your own risk.
There seems to be a new solution at the horizon. It's called EmailJS. They claim that no server code is needed. You can request an invitation.
Update August 2016: EmailJS seems to be live already. You can send up to 200 emails per month for free and it offers subscriptions for higher volumes.
window.open('mailto:test#example.com'); as above
does nothing to hide the "test#example.com" email address from being harvested by spambots. I used to constantly run into this problem.
var recipient="test";
var at = String.fromCharCode(64);
var dotcom="example.com";
var mail="mailto:";
window.open(mail+recipient+at+dotcom);
In your sendMail() function, add an ajax call to your backend, where you can implement this on the server side.
Javascript is client-side, you cannot email with Javascript. Browser recognizes maybe only mailto: and starts your default mail client.
JavaScript can't send email from a web browser. However, stepping back from the solution you've already tried to implement, you can do something that meets the original requirement:
send an email without refreshing the page
You can use JavaScript to construct the values that the email will need and then make an AJAX request to a server resource that actually sends the email. (I don't know what server-side languages/technologies you're using, so that part is up to you.)
If you're not familiar with AJAX, a quick Google search will give you a lot of information. Generally you can get it up and running quickly with jQuery's $.ajax() function. You just need to have a page on the server that can be called in the request.
It seems like one 'answer' to this is to implement an SMPT client. See email.js for a JavaScript library with an SMTP client.
Here's the GitHub repo for the SMTP client. Based on the repo's README, it appears that various shims or polyfills may be required depending on the client browser, but overall it does certainly seem feasible (if not actually significantly accomplished), tho not in a way that's easily describable by even a reasonably-long answer here.
There is a combination service. You can combine the above listed solutions like mandrill with a service EmailJS, which can make the system more secure.
They have not yet started the service though.
Another way to send email from JavaScript, is to use directtomx.com as follows;
Email = {
Send : function (to,from,subject,body,apikey)
{
if (apikey == undefined)
{
apikey = Email.apikey;
}
var nocache= Math.floor((Math.random() * 1000000) + 1);
var strUrl = "http://directtomx.azurewebsites.net/mx.asmx/Send?";
strUrl += "apikey=" + apikey;
strUrl += "&from=" + from;
strUrl += "&to=" + to;
strUrl += "&subject=" + encodeURIComponent(subject);
strUrl += "&body=" + encodeURIComponent(body);
strUrl += "&cachebuster=" + nocache;
Email.addScript(strUrl);
},
apikey : "",
addScript : function(src){
var s = document.createElement( 'link' );
s.setAttribute( 'rel', 'stylesheet' );
s.setAttribute( 'type', 'text/xml' );
s.setAttribute( 'href', src);
document.body.appendChild( s );
}
};
Then call it from your page as follows;
window.onload = function(){
Email.apikey = "-- Your api key ---";
Email.Send("to#domain.com","from#domain.com","Sent","Worked!");
}
There is not a straight answer to your question as we can not send email only using javascript, but there are ways to use javascript to send emails for us:
1) using an api to and call the api via javascript to send the email for us, for example https://www.emailjs.com says that you can use such a code below to call their api after some setting:
var service_id = 'my_mandrill';
var template_id = 'feedback';
var template_params = {
name: 'John',
reply_email: 'john#doe.com',
message: 'This is awesome!'
};
emailjs.send(service_id,template_id,template_params);
2) create a backend code to send an email for you, you can use any backend framework to do it for you.
3) using something like:
window.open('mailto:me#http://stackoverflow.com/');
which will open your email application, this might get into blocked popup in your browser.
In general, sending an email is a server task, so should be done in backend languages, but we can use javascript to collect the data which is needed and send it to the server or api, also we can use third parities application and open them via the browser using javascript as mentioned above.
If and only if i had to use some js library, i would do that with SMTPJs library.It offers encryption to your credentials such as username, password etc.
The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:
Use Ajax to send request to the PHP script ,check that required field are not empty or incorrect using js also keep a record of mail send by whom from your server.
function sendMail() is good for doing that.
Check for any error caught while mailing from your script and take appropriate action.
For resolving it for example if the mail address is incorrect or mail is not send due to server problem or it's in queue in such condition report it to user immediately and prevent multi sending same email again and again.
Get response from your script Using jQuery GET and POST
$.get(URL,callback);
$.post(URL,callback);
Since these all are wonderful infos there's a little api called Mandrill to send mails from javascript and it works perfectly. You can give it a shot. Here's a little tutorial for the start.
Full AntiSpam version:
<div class="at">info<i class="fa fa-at"></i>google.com</div>
OR
<div class="at">info#google.com</div>
<style>
.at {
color: blue;
cursor: pointer;
}
.at:hover {
color: red;
}
</style>
<script>
const el33 = document.querySelector(".at");
el33.onclick = () => {
let recipient="info";
let at = String.fromCharCode(64);
let dotcom="google.com";
let mail="mailto:";
window.open(mail+recipient+at+dotcom);
}
</script>
Send an email using the JavaScript or jQuery
var ConvertedFileStream;
var g_recipient;
var g_subject;
var g_body;
var g_attachmentname;
function SendMailItem(p_recipient, p_subject, p_body, p_file, p_attachmentname, progressSymbol) {
// Email address of the recipient
g_recipient = p_recipient;
// Subject line of an email
g_subject = p_subject;
// Body description of an email
g_body = p_body;
// attachments of an email
g_attachmentname = p_attachmentname;
SendC360Email(g_recipient, g_subject, g_body, g_attachmentname);
}
function SendC360Email(g_recipient, g_subject, g_body, g_attachmentname) {
var flag = confirm('Would you like continue with email');
if (flag == true) {
try {
//p_file = g_attachmentname;
//var FileExtension = p_file.substring(p_file.lastIndexOf(".") + 1);
// FileExtension = FileExtension.toUpperCase();
//alert(FileExtension);
SendMailHere = true;
//if (FileExtension != "PDF") {
// if (confirm('Convert to PDF?')) {
// SendMailHere = false;
// }
//}
if (SendMailHere) {
var objO = new ActiveXObject('Outlook.Application');
var objNS = objO.GetNameSpace('MAPI');
var mItm = objO.CreateItem(0);
if (g_recipient.length > 0) {
mItm.To = g_recipient;
}
mItm.Subject = g_subject;
// if there is only one attachment
// p_file = g_attachmentname;
// mAts.add(p_file, 1, g_body.length + 1, g_attachmentname);
// If there are multiple attachment files
//Split the files names
var arrFileName = g_attachmentname.split(";");
// alert(g_attachmentname);
//alert(arrFileName.length);
var mAts = mItm.Attachments;
for (var i = 0; i < arrFileName.length; i++)
{
//alert(arrFileName[i]);
p_file = arrFileName[i];
if (p_file.length > 0)
{
//mAts.add(p_file, 1, g_body.length + 1, g_attachmentname);
mAts.add(p_file, i, g_body.length + 1, p_file);
}
}
mItm.Display();
mItm.Body = g_body;
mItm.GetInspector.WindowState = 2;
}
//hideProgressDiv();
} catch (e) {
//debugger;
//hideProgressDiv();
alert('Unable to send email. Please check the following: \n' +
'1. Microsoft Outlook is installed.\n' +
'2. In IE the SharePoint Site is trusted.\n' +
'3. In IE the setting for Initialize and Script ActiveX controls not marked as safe is Enabled in the Trusted zone.');
}
}
}
I'm making a web app that requires that I check to see if remote servers are online or not. When I run it from the command line, my page load goes up to a full 60s (for 8 entries, it will scale linearly with more).
I decided to go the route of pinging on the user's end. This way, I can load the page and just have them wait for the "server is online" data while browsing my content.
If anyone has the answer to the above question, or if they know a solution to keep my page loads fast, I'd definitely appreciate it.
I have found someone that accomplishes this with a very clever usage of the native Image object.
From their source, this is the main function (it has dependences on other parts of the source but you get the idea).
function Pinger_ping(ip, callback) {
if(!this.inUse) {
this.inUse = true;
this.callback = callback
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function() {_that.good();};
this.img.onerror = function() {_that.good();};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function() { _that.bad();}, 1500);
}
}
This works on all types of servers that I've tested (web servers, ftp servers, and game servers). It also works with ports. If anyone encounters a use case that fails, please post in the comments and I will update my answer.
Update: Previous link has been removed. If anyone finds or implements the above, please comment and I'll add it into the answer.
Update 2: #trante was nice enough to provide a jsFiddle.
http://jsfiddle.net/GSSCD/203/
Update 3: #Jonathon created a GitHub repo with the implementation.
https://github.com/jdfreder/pingjs
Update 4: It looks as if this implementation is no longer reliable. People are also reporting that Chrome no longer supports it all, throwing a net::ERR_NAME_NOT_RESOLVED error. If someone can verify an alternate solution I will put that as the accepted answer.
Ping is ICMP, but if there is any open TCP port on the remote server it could be achieved like this:
function ping(host, port, pong) {
var started = new Date().getTime();
var http = new XMLHttpRequest();
http.open("GET", "http://" + host + ":" + port, /*async*/true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
var ended = new Date().getTime();
var milliseconds = ended - started;
if (pong != null) {
pong(milliseconds);
}
}
};
try {
http.send(null);
} catch(exception) {
// this is expected
}
}
you can try this:
put ping.html on the server with or without any content, on the javascript do same as below:
<script>
function ping(){
$.ajax({
url: 'ping.html',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
You can't directly "ping" in javascript.
There may be a few other ways:
Ajax
Using a java applet with isReachable
Writing a serverside script which pings and using AJAX to communicate to your serversidescript
You might also be able to ping in flash (actionscript)
You can't do regular ping in browser Javascript, but you can find out if remote server is alive by for example loading an image from the remote server. If loading fails -> server down.
You can even calculate the loading time by using onload-event. Here's an example how to use onload event.
Pitching in with a websocket solution...
function ping(ip, isUp, isDown) {
var ws = new WebSocket("ws://" + ip);
ws.onerror = function(e){
isUp();
ws = null;
};
setTimeout(function() {
if(ws != null) {
ws.close();
ws = null;
isDown();
}
},2000);
}
Update: this solution does not work anymore on major browsers, since the onerror callback is executed even if the host is a non-existent IP address.
To keep your requests fast, cache the server side results of the ping and update the ping file or database every couple of minutes(or however accurate you want it to be). You can use cron to run a shell command with your 8 pings and write the output into a file, the webserver will include this file into your view.
The problem with standard pings is they're ICMP, which a lot of places don't let through for security and traffic reasons. That might explain the failure.
Ruby prior to 1.9 had a TCP-based ping.rb, which will run with Ruby 1.9+. All you have to do is copy it from the 1.8.7 installation to somewhere else. I just confirmed that it would run by pinging my home router.
There are many crazy answers here and especially about CORS -
You could do an http HEAD request (like GET but without payload).
See https://ochronus.com/http-head-request-good-uses/
It does NOT need a preflight check, the confusion is because of an old version of the specification, see
Why does a cross-origin HEAD request need a preflight check?
So you could use the answer above which is using the jQuery library (didn't say it) but with
type: 'HEAD'
--->
<script>
function ping(){
$.ajax({
url: 'ping.html',
type: 'HEAD',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
Off course you can also use vanilla js or dojo or whatever ...
If what you are trying to see is whether the server "exists", you can use the following:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
This will return a true/false indication whether the server exists.
If you want response time, a slight modification will do:
function ping(url) {
var encodedURL = encodeURIComponent(url);
var startDate = new Date();
var endDate = null;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
if (data.query.results != null) {
endDate = new Date();
} else {
endDate = null;
}
},
error: function(){
endDate = null;
}
});
if (endDate == null) {
throw "Not responsive...";
}
return endDate.getTime() - startDate.getTime();
}
The usage is then trivial:
var isValid = isValidURL("http://example.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Or:
var responseInMillis = ping("example.com");
alert(responseInMillis);
const ping = (url, timeout = 6000) => {
return new Promise((resolve, reject) => {
const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&##/%?=~_|!:,.;]+[-A-Za-z0-9+&##/%=~_|]');
if (!urlRule.test(url)) reject('invalid url');
try {
fetch(url)
.then(() => resolve(true))
.catch(() => resolve(false));
setTimeout(() => {
resolve(false);
}, timeout);
} catch (e) {
reject(e);
}
});
};
use like this:
ping('https://stackoverflow.com/')
.then(res=>console.log(res))
.catch(e=>console.log(e))
I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/
let webSite = 'https://google.com/'
https.get(webSite, function (res) {
// If you get here, you have a response.
// If you want, you can check the status code here to verify that it's `200` or some other `2xx`.
console.log(webSite + ' ' + res.statusCode)
}).on('error', function(e) {
// Here, an error occurred. Check `e` for the error.
console.log(e.code)
});;
if you run this with node it would console log 200 as long as google is not down.
You can run the DOS ping.exe command from javaScript using the folowing:
function ping(ip)
{
var input = "";
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("c:/windows/system32/ping.exe " + ip);
while (!oExec.StdOut.AtEndOfStream)
{
input += oExec.StdOut.ReadLine() + "<br />";
}
return input;
}
Is this what was asked for, or am i missing something?
just replace
file_get_contents
with
$ip = $_SERVER['xxx.xxx.xxx.xxx'];
exec("ping -n 4 $ip 2>&1", $output, $retval);
if ($retval != 0) {
echo "no!";
}
else{
echo "yes!";
}
It might be a lot easier than all that. If you want your page to load then check on the availability or content of some foreign page to trigger other web page activity, you could do it using only javascript and php like this.
yourpage.php
<?php
if (isset($_GET['urlget'])){
if ($_GET['urlget']!=''){
$foreignpage= file_get_contents('http://www.foreignpage.html');
// you could also use curl for more fancy internet queries or if http wrappers aren't active in your php.ini
// parse $foreignpage for data that indicates your page should proceed
echo $foreignpage; // or a portion of it as you parsed
exit(); // this is very important otherwise you'll get the contents of your own page returned back to you on each call
}
}
?>
<html>
mypage html content
...
<script>
var stopmelater= setInterval("getforeignurl('?urlget=doesntmatter')", 2000);
function getforeignurl(url){
var handle= browserspec();
handle.open('GET', url, false);
handle.send();
var returnedPageContents= handle.responseText;
// parse page contents for what your looking and trigger javascript events accordingly.
// use handle.open('GET', url, true) to allow javascript to continue executing. must provide a callback function to accept the page contents with handle.onreadystatechange()
}
function browserspec(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}else{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
</script>
That should do it.
The triggered javascript should include clearInterval(stopmelater)
Let me know if that works for you
Jerry
You could try using PHP in your web page...something like this:
<html><body>
<form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Host to ping:</h1>
<input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br>
<input type="submit" name="submit" value="Submit" >
</form></body>
</html>
<?php
$tgt_host = $_POST['tgt_host'];
$output = shell_exec('ping -c 10 '. $tgt_host.');
echo "<html><body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script>
</body></html>";
?>
This is not tested so it may have typos etc...but I am confident it would work. Could be improved too...