Ajax.Updater POST params not transmitted by Firefox - javascript

I am debugging code written by someone else - I am also a newbie at Ajax and JS. The code shown below uses Ajax (Prototype JavaScript framework, version 1.6.0.1) to submit a simple contact form and update the page with the response. It works perfectly with IE8 and fails with Firefox. I have traced the failure to the post parameters. The target file, mail.php, is not receiving any POST parameters when Firefox is the browser. Not just the values are missing - the params are not defined in the post. The URL is valid. The form, the Ajax JS files and the mail.php script are all on the same domain.
I have tried variations on defining var params as shown in several other Stack Overflow posts (inline, different assignment methods, etc). All produced the same results as the code below.
Any clue what is wrong?
FF results
Please try again. responseText='', url='http://domain.com/builder/mail.php',
form_name='dom', form_message='testing', form_email='dom#domain.com',
form_to='info#domain.com'
IE8 results
Message Sent!
JS function
function sendForm(F)
{
$("contact_form").hide();
$("ajax-loader").show();
var url = site_url+'mail.php';
var form_message = escape($("message").value);
var form_name = escape($("name").value);
var form_address = escape($("address").value);
var form_phone = escape($("phone").value);
var form_email = escape($("email").value);
var form_how_learn = escape($("how_learn").value);
var form_to = escape($("to").value);
var params = {message: form_message,
name: form_name,
address: form_address,
phone: form_phone,
email: form_email,
how_learn: form_how_learn,
to: form_to};
var ajax = new Ajax.Updater(
'contact_form',
url,
{
method: 'post',
parameters: params,
onComplete: function (response)
{
$("ajax-loader").hide();
if (response.responseText == "ok")
{
$("contact_form").innerHTML = "<p style=\"color:green;\">Message Sent!</p>";
$("contact_form").show();
}
else
{
// Debug code added
$("contact_form").innerHTML = "<p style=\"color:red;\">Please try again."+
" responseText='"+response.responseText+"',"+
" url='"+url+"',"+
" form_name='"+form_name+"',"+
" form_message='"+form_message+"',"+
" form_email='"+form_email+"',"+
" form_to='"+form_to+"'"+
"</p>";
$("contact_form").show();
}
},
onFailure: function ()
{
$("ajax-loader").hide();
$("contact_form").innerHTML = "<p style=\"color:red;\">Please try again.</p>";
$("contact_form").show();
}
}
);
return false;
}

Related

Is there some way I can create an html button that automatically sends an email when clicked? [duplicate]

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

How to ping ip address from java script [duplicate]

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...

Facebook email is returned as undefined from phonegap facebookConnect plugin

I am using the phonegap facebook Connect plugin to enable facebook login in my app.
However the facebook email is being returned as undefined.
Do I need to add something into my code?
I have looked up this issue on the internet and it seems my code should work. Everything else is returned except for the email address.
I would appreciate if you can help
Here is my javascript code:
facebookConnectPlugin.api('/me?fields=id, email, link, name, picture', ["public_profile"],function(data){
var fb_user_id = data.id;
var fb_email = data.email;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_email" + fb_email);
}); //end api call
Edit:
I tried a test user account with this code and the email address DID get returned. However for the real account I was testing with this doesn't work.
With more testing I tried adding in the email permission as follows however this did not work as the data that I got back stated "FACEBOOK_NON_JSON_RESULT"
facebookConnectPlugin.api('/me?fields=id, email, link, name, picture', ["public_profile", "email"],function(data){
var fb_user_id = data.id;
var fb_email = data.email;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_email" + fb_email);
}); //end api call
I find a workaround for this problem which was to do two separate api requests as follows:
facebookConnectPlugin.api('/me?fields=email', ["email"], function(apiResponse) {
//alert("api" + JSON.stringify(apiResponse));
fb_email = apiResponse.email;
alert("fb_email" +fb_email); //email being retrieved successfully
facebookConnectPlugin.api('/me?fields=id, name, link, picture', ["public_profile"],function(data) {
alert("data" + JSON.stringify(data));
var fb_user_id = data.id;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_user_id" + fb_user_id);
alert("fb_name" + fb_name);
alert("fb_picture_url" + fb_picture_url);
alert("fb_user_link" + fb_user_link);
//do stuff with facebook user data here
}
,function(error){
//api call failed
alert("api call Failed: " + JSON.stringify(error));
}); //end api
}
,function(error){
alert("email api call Failed: " + JSON.stringify(error));
}); //end api
This works perfect!

How to login in Instagram using casperjs

I am beginner in CasperJs, i wrote the following code:
'use strict';
var casper = require('casper').create();
var username = "XXXXXXXX";
var password = "XXXXXXXX";
casper.start('https://instagram.com/accounts/login/', function() {
this.echo(this.getTitle());
console.log('Starting location is ' + this.getCurrentUrl());
});
casper.then(function() {
/*this.fill('form[data-reactid=".0.0.1.0.1"]', {
username: username,
password: password
}, true); i tried this*/
/*this.fill('form[data-reactid=".0.0.1.0.1"]', {
'input[id="lfFieldInputUsername"]': username,
'input[id="lfFieldInputPassword"]': password
}, true); i tried this too*/
//i am trying this too because the page have only one form element
this.fill('form', {
username: username,
password: password
}, true);
});
casper.then(function() {
console.log('Authentication ok, new location is ' + this.getCurrentUrl());
});
casper.run(function() {
this.echo('end');
});
I found that it couldn't able to find the form element in the page loaded by CasperJs. In the Instagram form login, it does not have name/id/class/action of the form. while it works with twitter login when i used following snippet
this.fillSelectors('form.signin', {
'input[name="session[username_or_email]"]': email,
'input[name="session[password]"]': auth
}, true);
And when i use this.fillSelectors then it shows the following error:
TypeError: 'undefined' is not a function (evaluating 'this.fillSelectors') for this context.
When i use this.fill then it shows following error:
CasperError: Errors encountered while filling form: form not found
Any suggestions would be appreciated.
I had the exact same issue. In the end I gave up looking for the form element. Instead of using this.fill('form', ...), I used standard javascript to fill each of the fields separately:
var username_field = document.getElementById('lfFieldInputUsername');
username_field.value = "XXXXXX";
var password_field = document.getElementById('lfFieldInputPassword');
password_field.value = "XXXXXX";
And instead of submitting the form, I sent a click event on the button element.
The following code is actually for PhantomJS, but you can probably convert it to the CasperJS API.
// Create a page object
var page = require('webpage').create();
// Open the page
page.open('https://instagram.com/accounts/login/', ...
// do other stuff like filling the form fields
// Send the click event
var point = page.evaluate(function () {
var element = document.getElementsByTagName('button')[0];
var rect = element.getBoundingClientRect();
return {
x: rect.left + Math.floor(rect.width / 2),
y: rect.top + Math.floor(rect.height / 2)
};
});
page.sendEvent('click', point.x, point.y);
The bad news is, after that I get a "password incorrect" error even though I'm sure the password is correct. I still haven't been able to fix that.
Maybe you'll have better luck than me using CasperJS.
You can see my full code here.
here is my code :
casper.then(function ()
{
this.sendKeys('input[name="username"]', userName);
this.sendKeys('input[name="password"]', pass);
this.clickLabel('Log in','button');
});

Transposh plugin to translate Ajax loaded content

I'm trying to get the transposh plugin to translate everytime the cart is updated dynamically. Currently, the plugin will translate and then woocommerce would update the cart thus the translations disappear.
I found the following code in WooCommerce's checkout.js:
// Event for updating the checkout
$('body').bind('update_checkout', function() {
clearTimeout(updateTimer);
update_checkout();
});
I believe this is the code (I can only find the minified version of it) for how transposh gets the translations going in transposh.js:
(function(c){function D(b,a){if(0!==c.trim(a).length){var d=function(){var b=c(this).attr("id").substr(c(this).attr("id").lastIndexOf("_")+1),a=c("#"+e+"img_"+b);c("#"+e+b).attr("data-source",1);a.removeClass("tr-icon-yellow").removeClass("tr-icon-green").addClass("tr-icon-yellow")};c("*[data-token='"+b+"'][data-hidden!='y']").html(a).each(d);c("*[data-token='"+b+"'][data-hidden='y']").attr("data-trans",a).each(d)}}function E(b,a){clearTimeout(v);h.push(b);r.push(a);D(b,a);v=setTimeout(function(){var b=
{ln0:t_jp.lang,sr0:s,action:"tp_translation",items:h.length},a;for(a=0;a<h.length;a+=1)b["tk"+a]=h[a],b["tr"+a]=r[a],t+=c("*[data-token='"+h[a]+"']").size();c.ajax({type:"POST",url:t_jp.ajaxurl,data:b,success:function(){var b=t/k*100;t_jp.progress&&c("#"+m).progressbar("value",b)}});r=[];h=[]},200)}function l(b,a){E(b,c("<div>"+c.trim(a)+"</div>").text());var d=(k-c("."+e+'[data-source=""]').size())/k*100;t_jp.progress&&c("#"+n).progressbar("value",d)}function w(b,a,d){c.ajax({url:t_jp.ajaxurl,dataType:"json",
type:"GET",data:{action:"tp_gp",tl:d,q:b},success:a})}function x(b,a){w(a,function(a){c(a.results).each(function(a){l(b[a],this)})},t_jp.lang)}function y(b,a,d){c.ajax({url:"https://www.googleapis.com/language/translate/v2",dataType:"jsonp",data:{key:t_jp.google_key,q:b,target:d,source:t_jp.olang},traditional:!0,success:a})}function F(b,a){y(a,function(d){"undefined"!==typeof d.error?x(b,a):c(d.data.translations).each(function(a){l(b[a],this.translatedText)})},t_jp.lang)}function p(b,a,d){if(t_jp.msn_key){var f=
"[";c(b).each(function(a){f+='"'+encodeURIComponent(b[a].replace(/[\\"]/g,"\\$&").replace(/(\r\n|\n|\r)/gm," "))+'",'});f=f.slice(0,-1)+"]";c.ajax({url:"//api.microsofttranslator.com/V2/Ajax.svc/TranslateArray?appId="+t_jp.msn_key+"&to="+d+"&texts="+f,dataType:"jsonp",jsonp:"oncomplete",success:a})}else 1===z?setTimeout(function(){p(b,a,d)},500):(z=1,c.getScript("//www.microsofttranslator.com/ajax/v2/toolkit.ashx?loc=en&toolbar=none",function(){t_jp.msn_key=_mstConfig.appId;p(b,a,d)}))}function G(b,
a){s=2;p(a,function(a){c(a).each(function(a){l(b[a],this.TranslatedText)})},t_jp.binglang)}function A(b,a,d){c.ajax({url:"http://api.apertium.org/json/translate",data:{q:b,langpair:t_jp.olang+"|"+d,markUnknown:"no"},dataType:"jsonp",traditional:!0,success:a})}function H(b,a){s=3;A(a,function(a){200<=a.responseStatus&&300>a.responseStatus&&(void 0!==a.responseData.translatedText?l(b[0],a.responseData.translatedText):c(a.responseData).each(function(a){200===this.responseStatus&&l(b[a],this.responseData.translatedText)}))},
t_jp.lang)}function B(b,a){!t_jp.msn||"2"!==t_jp.preferred&&void 0!==t_jp.google?!t_jp.apertium||"en"!==t_jp.olang&&"es"!==t_jp.olang?t_jp.google_key?F(b,a):x(b,a):H(b,a):G(b,a)}function u(){var b=[],a=0,d=[],f=[];c("."+e+'[data-source=""]').each(function(){var e=c(this).attr("data-token"),g=c(this).attr("data-orig");void 0===g&&(g=c(this).html());1!==b[g]&&(b[g]=1,a+encodeURIComponent(g).length>I&&(B(f,d),a=0,d=[],f=[]),a+=encodeURIComponent(g).length,f.push(e),d.push(g))});B(f,d)}function C(b){"function"===
typeof c.xLazyLoader?b():(t_jp.$=c,c.getScript(t_jp.plugin_url+"/js/lazy.js",b))}function q(b){q.hit?b():(q.hit=!0,C(function(){c.fn.propAttr=c.fn.prop||c.fn.attr;c.xLazyLoader({js:t_jp.jQueryUI+"jquery-ui.min.js",css:t_jp.jQueryUI+"themes/"+t_jp.theme+"/jquery-ui.css",success:b})}))}var I=1024,k,e=t_jp.prefix,n=e+"pbar",m=n+"_s",s=1,t=0,v,h=[],r=[],z=0;t_jp.dgpt=w;t_jp.dgt=y;t_jp.dmt=p;t_jp.dat=A;t_jp.tfl=C;t_jp.tfju=q;t_jp.at=u;c(function(){t_jp.msn&&(t_jp.binglang=t_jp.lang,"zh"===t_jp.binglang?
t_jp.binglang="zh-chs":"zh-tw"===t_jp.binglang?t_jp.binglang="zh-cht":"mw"===t_jp.binglang&&(t_jp.binglang="mww"));c("."+e+"setdeflang").click(function(){c.ajax({url:t_jp.ajaxurl,data:{action:"tp_cookie"},cache:!1});c("."+e+"setdeflang").hide("slow");return!1});k=c("."+e+'[data-source=""]').size();c.ajaxSetup({cache:!0});k&&!t_jp.noauto&&(t_jp.google||t_jp.msn||t_jp.apertium)&&(t_jp.progress?q(function(){c("#"+e+"credit").css({overflow:"auto"}).append('<div style="float: left;width: 90%;height: 10px" id="'+
n+'"/><div style="margin-bottom:10px;float:left;width: 90%;height: 10px" id="'+m+'"/>');c("#"+n).progressbar({value:0});c("#"+m).progressbar({value:0});c("#"+m+" > div").css({background:"#28F828",border:"#08A908 1px solid"});u()}):u());t_jp.edit&&c.getScript(t_jp.plugin_url+"/js/transposhedit.js")})})(jQuery);
What should I add in the checkout.js to fire the translations everytime the cart is updated?
Let me know what other details I should provide.
EDIT: I should note that I was told that the cart is being updated via AJAX. Upon research, the plugin creator of transposh had suggested users to look at the on_init function in transposh.php
This is the on_init function:
/**
* Setup a buffer that will contain the contents of the html page.
* Once processing is completed the buffer will go into the translation process.
*/
function on_init() {
tp_logger('init ' . $_SERVER['REQUEST_URI'], 4);
// the wp_rewrite is not available earlier so we can only set the enable_permalinks here
if (is_object($GLOBALS['wp_rewrite'])) {
if ($GLOBALS['wp_rewrite']->using_permalinks() && $this->options->enable_permalinks) {
tp_logger("enabling permalinks");
$this->enable_permalinks_rewrite = TRUE;
}
}
// this is an ajax special case, currently crafted and tested on buddy press, lets hope this won't make hell break loose.
// it basically sets language based on referred when accessing wp-load.php (which is the way bp does ajax)
tp_logger(substr($_SERVER['SCRIPT_FILENAME'], -11), 5);
if (substr($_SERVER['SCRIPT_FILENAME'], -11) == 'wp-load.php') {
$this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
$this->attempt_json = true;
}
//buddypress old activity
if (#$_POST['action'] == 'activity_get_older_updates') {
$this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
$this->attempt_json = true;
}
tp_logger($_SERVER['REQUEST_URI'], 5);
if (strpos($_SERVER['REQUEST_URI'], '/wpv-ajax-pagination/') === true) {
tp_logger('wpv pagination', 5);
$this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
}
// load translation files for transposh
load_plugin_textdomain(TRANSPOSH_TEXT_DOMAIN, false, dirname(plugin_basename(__FILE__)) . '/langs');
//set the callback for translating the page when it's done
ob_start(array(&$this, "process_page"));
}
Here is the function for update_checkout()
function update_checkout() {
if (xhr) xhr.abort();
if ( $('select#shipping_method').size() > 0 || $('input#shipping_method').size() > 0 )
var method = $('#shipping_method').val();
else
var method = $('input[name=shipping_method]:checked').val();
var payment_method = $('#order_review input[name=payment_method]:checked').val();
var country = $('#billing_country').val();
var state = $('#billing_state').val();
var postcode = $('input#billing_postcode').val();
var city = $('input#billing_city').val();
var address = $('input#billing_address_1').val();
var address_2 = $('input#billing_address_2').val();
if ( $('#shiptobilling input').is(':checked') || $('#shiptobilling input').size() == 0 ) {
var s_country = country;
var s_state = state;
var s_postcode = postcode;
var s_city = city;
var s_address = address;
var s_address_2 = address_2;
} else {
var s_country = $('#shipping_country').val();
var s_state = $('#shipping_state').val();
var s_postcode = $('input#shipping_postcode').val();
var s_city = $('input#shipping_city').val();
var s_address = $('input#shipping_address_1').val();
var s_address_2 = $('input#shipping_address_2').val();
}
$('#order_methods, #order_review').block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url + ') no-repeat center', backgroundSize: '16px 16px', opacity: 0.6}});
var data = {
action: 'woocommerce_update_order_review',
security: woocommerce_params.update_order_review_nonce,
shipping_method: method,
payment_method: payment_method,
country: country,
state: state,
postcode: postcode,
city: city,
address: address,
address_2: address_2,
s_country: s_country,
s_state: s_state,
s_postcode: s_postcode,
s_city: s_city,
s_address: s_address,
s_address_2: s_address_2,
post_data: $('form.checkout').serialize()
};
xhr = $.ajax({
type: 'POST',
url: woocommerce_params.ajax_url,
data: data,
success: function( response ) {
if ( response ) {
var order_output = $(response);
$('#order_review').html(order_output.html());
$('body').trigger('updated_checkout');
}
}
});
}
After a bit of digging , and because im not php expert neither wp expert , but i can tell where the issue is.
First of all you should understand what add_action is , it is well explained here
If you needed to create an AJAX handler for an "add_foobar" request, you would create a hook like this:
add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );
function prefix_ajax_add_foobar() {
// Handle request then generate response using WP_Ajax_Response
}
Using the above example, any time an AJAX request is sent to WordPress, and the request's 'action' property is set to 'add_foobar', this hook will be automatically executed. For example, the following code would execute the above hook.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
so now you got how actions works , then you have to get how the transposh.php ajax part works , from the transposh.php file ( i recommend you open the file in a good text editor like sublime text ) , in line 437 :
//buddypress old activity
if (#$_POST['action'] == 'activity_get_older_updates') {
$this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
$this->attempt_json = true;
}
this simply tells our script to fire translation when this action is called, what you have to do is customizing this line a bit so it fires upon you ajax request (update_checkout()).
if you check update_checkout() function you will find the corresponding action : 'woocommerce_update_order_review'
Solution:
1. Add you wp actions
add_action( 'wp_woocommerce_update_order_review', 'woocommerce_update_order_review' );
//preferably add this to line 207 in transposh.php with other add actions.
2. Instead of adding your own function , just modify the current buddypress example.
if (#$_POST['action'] == 'activity_get_older_updates')
to be
if (#$_POST['action'] == 'activity_get_older_updates' || #$_POST['action'] == 'woocommerce_update_order_review' )
//fire translation if action is equal to buddypress activity get older updates or action is equal to woocommerce update checkout.
3. this guy recommends adding following condition to line 352 in transposh.php
if ($this->is_special_page($_SERVER['REQUEST_URI']))
to be
if ($this->is_special_page($_SERVER['REQUEST_URI'])&& !$this->attempt_json)
found here : http://cl.ly/Shdn/o
I hope i had a link to your page where you are using this , but you could not provide an example , so i hope this solution will work as it was meant to be.

Categories