I am trying to make an offline HTML5 application that submits a form containing a image and a text input for a email address, when a internet connection is avaiable
This is what I have tried:
<body>
<script type='text/javascript'>
window.onload = function () {
function submit() {
setInterval(function () {
if (navigator.onLine) {
//if internet is avaiable do:
document.getElementById("upload").submit();
}else {
//if no internet
var theDiv = document.getElementById("message");
var content = document.createTextNode("No internet");
theDiv.appendChild(content);
}
}, 1000);
}
}
</script>
<form action="post.php" method="post" enctype="multipart/form-data" id="upload">
<input type="file" name="uploaded" accept="image/*" capture><br>
<p>Skriv inn din epost: <input type="text" name="email"></p>
<input type="submit" value="Send ditt bilde!" name="sendimg" onclick="this.value='Submitting ..';this.disabled='disabled'; submit();">
<div class="message"></div>
Does someone have any suggestions? Thanks :)
Thee two ways to check this
This solution requires jQuery
$.ajaxSetup({
timeout: 1, // Microseconds, for the laughs. Guaranteed timeout.
error: function(request, status, maybe_an_exception_object) {
if(status == 'timeout')
alert("Internet connection is down!");
}
});
And
window.navigator.onLine -- it will be false if the user is offline.
You need to use above in your code with some tweaking as per requirement.
Sorry, but i cant comment yet. Will this work?
<script type='text/javascript'>
window.onload = function () {
function submit() {
setInterval(function () {
if (window.navigator.onLine == "true") {
//if internet is avaiable do:
document.getElementById("upload").submit();
}else {
//if no internet
var theDiv = document.getElementById("message");
var content = document.createTextNode("No internet");
theDiv.appendChild(content);
}
}, 1000);
}
}
</script>
Instead of continuous checking for Internet connection, you can use online and offline events. For reference see this https://developer.mozilla.org/en/docs/Online_and_offline_events. If the user is offline, save the data in local storage and then resend the data once the online event is again detected.
Related
I wanted to have an error message for the button and then redirect to the url. I'm not sure on how to do that. I wanted to put it into JQuery. I'm new to JQuery. It's like the user have to upload a file then click on Submit. "The submit button will redirect user to the url from the QRCode which will be displayed on the text.
Submit Button:
<div id="form1">
<input type=text placeholder="Tracking Code" class=qrcode-text id="url">
<label class=qrcodeBtn>
<input type=file accept="image/*" capture="environment" onchange="openCamera(this);">
</label>
<input type=button value="Submit" onclick = "windowLocate()" class="btnQRCode" id="submitButton">
Javascript for Redirect:
function windowLocate() {
var url = document.getElementById("url").value;
document.write("Redirecting to the url in few seconds...");
setTimeout(function () { window.location = url; }, 3000);
}
Here's how you'd do it:
function windowLocate() {
if (document.querySelector("input[type='file']").value) {
var url = document.getElementById("url").value;
document.write("Redirecting to the url in few seconds...");
setTimeout(function () {
window.open(url);
}, 3000);
}
else {
alert("Error message");
}
}
Try this if you want to check if users already uploaded the file or not.
Add id to the input tag.
<label class=qrcodeBtn>
<input type=file accept="image/*" capture="environment" id="uploadImage" onchange="openCamera(this);">
</label>
Then change the windowLocate code with this.
function windowLocate() {
if (document.getElementById("uploadImage").files.length != 0) {
var url = document.getElementById("url").value;
document.write("Redirecting to the url in few seconds...");
setTimeout(function () {
window.open(url);
}, 3000);
}
else {
alert("Please upload the file first."); //you can change the error message
}
}
I have a situation where I have two different sites, siteA.com and siteB.com, which need to share a common piece of information when a visitor navigates from siteA to siteB. I don't have access to the server-side code or navigation links from siteA, only limitied customizations and javascript. In order to share the information I have built a new page that is fully under my control at siteC.com, and then added this page as an iframe to both siteA and siteB. I am using the postMessage method to get and set the cookie from within the iframe which is working fine from each site, however I actually end up with two different cookies, one for each siteA and siteB even though the cookie belongs to siteC because it was set by the page in the iframe, confirmed through F12 debugger. I would have expected to have a single cookie and both sites could share the same cookie via the iframe, am I missing something here, should this be possible or is there another way to do this?
This is the code for my page at siteC that gets loaded into the iframe
<!DOCTYPE html>
<html>
<head>
<title>iframe source</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
var ck = document.cookie;
var expDate = new Date();
expDate.setFullYear(expDate.getFullYear() + 20)
$("#auditlog").append("iframe loaded<br/>");
if (ck) {
$("#auditlog").append("cookie exists<br/>");
} else {
$("#auditlog").append("cookie not set<br/>");
}
// Assign handler to message event
if (window.addEventListener) {
window.addEventListener('message', messageHandler, false);
} else if (window.attachEvent) { // ie8
window.attachEvent('onmessage', messageHandler);
}
})
function messageHandler(e) {
var msg = {};
var response;
// Check origin
if (e.origin === 'http://siteA' || e.origin === 'http://siteB') {
// Retrieve data sent in postMessage
msg = JSON.parse(e.data);
if (msg.action == "getCookie") {
response = getCookie();
} else if (msg.action == "setCookie") {
setCookie(msg.payload);
response = "cookie set";
} else {
response = "action not supported";
}
// Send reply to source of message
e.source.postMessage(response, e.origin);
}
}
function setCookie(cookieVal) {
var expDate = new Date();
expDate.setFullYear(expDate.getFullYear() + 20)
document.cookie = cookieVal + "; expires=" + expDate.toUTCString();
}
function getCookie() {
return document.cookie;
}
</script>
</head>
<body>
<div id="auditlog"></div>
<div id="cookieinfo"></div>
</body>
</html>
And this is code for my pages at siteA and siteB, both are using this same code, this is a sample I set up in order to test the set and get cookie functions in the iframe
<!DOCTYPE html>
<html>
<head>
<title>Main content page</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
// Assign handler to message event
if (window.addEventListener) {
window.addEventListener('message', messageHandler, false);
} else if (window.attachEvent) { // ie8
window.attachEvent('onmessage', messageHandler);
}
$("#btnGetIframeCookie").click(function () {
var postMsg = {
action:"getCookie"
}
// get reference to window inside the iframe
var wn = document.getElementById('cookieiframe').contentWindow;
// postMessage arguments: data to send, target origin
wn.postMessage(JSON.stringify(postMsg), 'http://siteC');
})
$("#btnSetIframeCookie").click(function () {
var cookieVal = $("#txtCookieValue").val();
var postMsg = {
action: "setCookie",
payload: cookieVal
}
var wn = document.getElementById('cookieiframe').contentWindow;
// postMessage arguments: data to send, target origin
wn.postMessage(JSON.stringify(postMsg), 'http://siteC');
})
})
function messageHandler(e) {
if (e.origin === 'http://siteC') {
$("#divMessages").append("response from iframe: <br/>" + e.data + "<br/>");
}
}
</script>
</head>
<body>
<div>
This is the iframe container
</div>
<div>
<input type="button" id="btnGetIframeCookie" value="Get iframe cookie" />
</div>
<div>
<input type="text" size="60" id="txtCookieValue" />
<input type="button" id="btnSetIframeCookie" value="Set iframe cookie" />
</div>
<iframe id="cookieiframe" src="http://siteC/iframe/index.html" style="width: 300px; height: 300px; border:1px solid black;"></iframe>
<div id="divMessages"></div>
</body>
</html>
Using this setup, if I set a cookie from siteA via the iframe with a value of "keyabc=value123" for example, I can then read that same cookie back, but when I go to siteB which has the same page in the iframe there, I don't have a cookie until I set one there, for example "keyabc=value456". Now if I look at my actual cookie files at C:\Users\aakoehle\AppData\Local\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\AC\#!001\MicrosoftEdge\Cookies I see two files, one with each of the values I set and both have the path of siteC. I also launched the F12 tools for each browser tab, each tab shows it's own cookie belonging to siteC.
-- UPDATE --
With the current version of my code posted here I am now only seeing the cookie issue in the Edge browser. Chrome and IE are sharing a single cookie between siteA and siteB as expected.
Here's an example for sharing data between cross origin sites, using localStorage and postMessage.
site1 : localhost:9091
<html>
<body>
<h1>site 1</h1>
<button id='postBtn'>Post message</button>
<br/>
<iframe id='commonSite' src='http://localhost:9093/commonSite.html' style='height:150px'></iframe>
<script>
(function () {
var commonSite = document.querySelector('#commonSite').contentWindow;
var postCounter = localStorage.getItem('postCounter');
postCounter = postCounter != null ? +postCounter : 1;
var commonOrigin = 'http://localhost:9093';
document.querySelector('#postBtn').onclick = function () {
commonSite.postMessage(postCounter++, commonOrigin);
localStorage.setItem('postCounter', postCounter);
console.log('site 1 posted');
}
})();
</script>
</body>
</html>
site2: localhost:9092
<html>
<body>
<h1>site 2</h1>
<button id='postBtn'>Post message</button>
<br/>
<iframe id='commonSite' src='http://localhost:9093/commonSite.html' style='height:150px'></iframe>
<script>
(function () {
var commonSite = document.querySelector('#commonSite').contentWindow;
var postCounter = localStorage.getItem('postCounter');
postCounter = postCounter != null ? +postCounter : 1;
var commonOrigin = 'http://localhost:9093';
document.querySelector('#postBtn').onclick = function () {
commonSite.postMessage(postCounter++, commonOrigin);
localStorage.setItem('postCounter', postCounter);
console.log('site 2 posted');
}
})();
</script>
</body>
</html>
commonSite: localhost:9093
<html>
<body>
<h3>Common site</h1>
<h4> Site 1 count: <span id='count1'></span></h3>
<h4> Site 2 count: <span id='count2'></span></h3>
<script>
(function () {
console.log('Adding message listener');
var origin1 = 'http://localhost:9091';
var origin2 = 'http://localhost:9092';
var count1 = document.querySelector('#count1');
var count2 = document.querySelector('#count2');
if(localStorage.getItem('count1')) {
count1.textContent = localStorage.getItem('count1');
}
if(localStorage.getItem('count2')) {
count2.textContent = localStorage.getItem('count2');
}
window.addEventListener('message', function (event) {
var origin = event.origin;
var data = event.data;
if(origin === origin1) {
localStorage.setItem('count1', data);
count1.textContent = localStorage.getItem('count1');
} else if(origin === origin2) {
localStorage.setItem('count2', data);
count2.textContent = localStorage.getItem('count2');
}
console.log('received (' + data + ') from ' + origin);
}, false);
})();
</script>
</body>
</html>
I have been trying to submit an embedded Mailchimp form with AJAX but without using jQuery. Clearly, I am not doing this properly, as I keep ending up on the "Come, Watson, come! The game is afoot." page :(
Any help with this would be greatly appreciate.
The form action has been altered to replace post?u= with post-json?u= and &c=? has been added to the end of the action string. Here is my js:
document.addEventListener('DOMContentLoaded', function() {
function formMailchimp() {
var elForm = document.getElementById('mc-embedded-subscribe-form'),
elInputName = document.getElementById('mce-NAME'),
elInputEmail = document.getElementById('mce-EMAIL'),
strFormAction = elForm.getAttribute('action');
elForm.addEventListener('submit', function(e) {
var request = new XMLHttpRequest();
request.open('GET', strFormAction, true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var resp = JSON.parse(request.responseText);
request.send(resp);
} else {
console.log('We reached our target server, but it returned an error');
}
};
request.onerror = function() {
console.log('There was a connection error of some sort');
};
});
}
formMailchimp();
});
Also, I anticipate the inevitable "why don't you just use jQuery" comment. Without going into the specifics of this project, jQuery is not something I am able to introduce into the code. Sorry, but this HAS to be vanilla javascript. Compatibility is for very modern browsers only.
Thanks so much for any help you can provide!
A few days back I've had the exact same problem and as it turns out the MailChimp documentation on native JavaScript is pretty sparse. I can share with you my code I came up with. Hope you can build from here!
The simplified HTML form: I've got the from action from the MailChimp form builder and added "post-json"
<div id="newsletter">
<form action="NAME.us1.list-manage.com/subscribe/post-json?u=XXXXXX&id=XXXXXXX">
<input class="email" type="email" value="Enter your email" required />
<input class="submit" type="submit" value="Subscribe" />
</form>
</div>
The JavaScript: The only way to avoid the cross-origin problem is to create a script and append it to the header. The callback occurs then on the ācā parameter. (Please note there is no email address validation on it yet)
function newsletterSubmitted(event) {
event.preventDefault();
this._form = this.querySelector("form");
this._action = this._form.getAttribute("action");
this._input = this._form.querySelector("input.email").value;
document.MC_callback = function(response) {
if(response.result == "success") {
// show success meassage
} else {
// show error message
}
}
// generate script
this._script = document.createElement("script");
this._script.type = "text/javascript";
this._script.src = this._action + "&c=document.MC_callback&EMAIL=" + this._input;
// append script to head
document.getElementsByTagName("head")[0].appendChild(this._script);
}
var newsletter = document.querySelector("#newsletter")
newsletter.addEventListener("submit", newsletterSubmitted);
I have a very small page being managed by some javascript. When I load the page into the browswer the link after the form (id=login_linker) works fine.
However, when I load it into a div the same link wont work. Does anyone have any ideas.
Here is the body of the page that is being included.
<body>
<p>Forgot your password?</>
<form name="forgotpassform" id="forgotpassform" onsubmit="return false;">
<label for="email">Email: </label>
<input id="email" type="text" class="searchbox" onfocus="emptyElement('status')" maxlength="35">
<input type="button" style="margin-top: 15px; position:relative; left:50px;" id="forgotpassbtn" onclick="forgotpass()" value="Send me a new password">
<br>
</form>
<span id="emailstatus"> </span>
<span id="status"></span>
Log In
</body>
The javascript:
function forgotpass(){
var e = _("email").value;
var status = _("status");
var forgotpassform = _("forgotpassform");
if(e != ""){
_("forgotpassbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "forgotpass.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "no_user"){
status.innerHTML = 'There was no matching email in the system.';
_("forgotpassbtn").style.display = "block";
} else if(ajax.responseText =="email_not_sent"){
status.innerHTML = 'There was a problem sending your temporary password.';
} else {
//status.innerHTML = ajax.responseText;
forgotpassform.innerHTML = "You have sent a temporary password to your email address. Please check your email.";
}
}
}
ajax.send("e="+e);
} else {
status.innerHTML = "Please enter your email address.";
}
}
function emptyElement(x){
_(x).innerHTML = "";
}
function loadlogin(){
$('#loginwindow').toggle(400);
$('#loginwindow').load("forgotpass.php");
$('#loginwindow').toggle(400);
}
$(document).ready(function(){
$(document).on('click', '#login_linker', function(){
alert('ok');
showlogin();
});
});
function showlogin(){
$('#loginwindow').load("login.php");
$('#loginwindow').toggle(400);
}
Here is the script to load the forgot password page ie the HTML above
function forgotpass(){
$('#loginwindow').toggle(400);
$('#loginwindow').load("forgotpass.php");
$('#loginwindow').toggle(400);
}
I don't know how your code to load the link using js is (it would be better if you post it too), but I guess the problem is you try to bind the event just after document is ready, and at that moment, the link isn't loaded yet. Bind it after loading it.
Suppose i have EXTERNAL URL(not from my website) and i want to verify it to make sure this url is one from these files:- jpg, jpeg, gif, png and also is a correct image file (not any script file or php). Also if this is possible:- Check if the url of the image is working or not.
#jfriend00 ok so here is what i'am trying to do. I had maded html form and when people submit it, it will call to a javascript function which will verify if the url is an image. So here is my code. But it's not working. Please tell me what should i do from here?
<script type="text/javascript">
function vrfyImgURL() {
var x = document.forms["submitIMGurl"].elements["img_url"].value;
if(x.match('^http://.*/(.*?).(jpe?g|gif|png)$')){
var imgsrc = x;
var img = new Image();
img.onerror = function(){
alert("Can't Be Loaded");
return false;
}
img.onload = function(){
alert("Loaded Successfully");
return true;
}
img.src = imgsrc;
}else{
alert("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.");
return false;
}
}
</script>
<form action="http://www.example.com/current_page" enctype='multipart/form-data' method="post" onsubmit="return vrfyImgURL();" name="submitIMGurl">
<input type="text" value="http://" name="img_url" />
<input type="submit" value="Submit" />
</form>
Your code in this post is not a correct implementation of the function I gave you in the previous post and will not work for a number of reasons. You cannot return true/false from the onload, onerror handlers. Those are asychronous events and your vrfyImgURL function has already returned.
You really HAVE to use the code I put in that previous post. It works. Just use it. Don't modify it. You pass in a callback and that callback gets called with the validation check results. You have to use asynchronous programming to use this where the callback gets called with the result. You can't use straight sequential programming like you are trying to do. It is your modifications to my code that have made it stop working.
You can see the code I gave you previously work here:http://jsfiddle.net/jfriend00/qKtra/ and in the example, it's working with images from a variety of domains. It is not sensitive to the domain of the image and <img> tags are not restricted by domain.
To hook it up to your form submit, you can do this:
<form action="http://www.example.com/current_page" enctype='multipart/form-data' method="post" onsubmit="return formSubmit();" name="submitIMGurl">
<input type="text" value="http://" name="img_url" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
function formSubmit() {
var url = document.forms["submitIMGurl"].elements["img_url"].value;
if (!checkURL(url)) {
alert("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.");
return(false);
}
testImage(url, function(testURL, result) {
if (result == "success") {
// you can submit the form now
document.forms["submitIMGurl"].submit();
} else if (result == "error") {
alert("The image URL does not point to an image or the correct type of image.");
} else {
alert("The image URL was not reachable. Check that the URL is correct.");
}
});
return(false); // can't submit the form yet, it will get sumbitted in the callback
}
function checkURL(url) {
return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
}
function testImage(url, callback, timeout) {
timeout = timeout || 5000;
var timedOut = false, timer;
var img = new Image();
img.onerror = img.onabort = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "error");
}
};
img.onload = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "success");
}
};
img.src = url;
timer = setTimeout(function() {
timedOut = true;
callback(url, "timeout");
}, timeout);
}
</script>
If this were my interface, I would disable the form and put up a note that the image URL is being checked starting when testImage is called and ending when the callback is called.