Ive been using geolocation and HTML recently, i want to try to show an iframe when the submit button is pressed, i keep getting stuck on what to do.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="text" />
<input type="button" id="btn" value="Submit" onClick="javascript: window.open('https://api.ipdata.co/' + document.getElementById('text').value);" />
</body>
</html>
Oh and here’s my iframe
The IPadress is the ipadress of a device i am testing this out on. I want to put this in where the “javascript: window.open” is
I'm not sure why You'd want to show an iframe with a JSON response...
var text = document.getElementById("text"),
btn = document.getElementById("btn"),
iframe = document.getElementById("iframe");
function text2iframe() {
iframe.src = "https://api.ipdata.co/" + text.value;
}
btn.addEventListener("click", text2iframe);
<input type="text" id="text" value="47.91.202.22"><br>
<input type="button" id="btn" value="Submit"><br>
<iframe id="iframe"></iframe>
When you can go for the JSON directly!
var text = document.getElementById("text"),
btn = document.getElementById("btn"),
pre = document.getElementById("pre");
function ipdata() {
var request = new XMLHttpRequest();
request.open('GET', "https://api.ipdata.co/" + text.value, true);
request.addEventListener("load", function() {
if (request.status >= 200 && request.status < 400) {
pre.textContent = request.responseText
var responseObj = JSON.parse(request.responseText);
console.log( responseObj.country_name )
console.dir( responseObj );
} else {
// error
}
});
request.addEventListener("error", function() {
// connection error
});
request.send();
}
btn.addEventListener("click", ipdata);
<input type="text" id="text" value="47.91.202.22"><br>
<input type="button" id="btn" value="Submit"><br>
<pre id="pre"></pre>
Related
like in this picture, if I try to send a message it can come out but if try to submit a file or image it won't come out. this is my code below
enter image description here
<p id="demo"></p>
<div id="messages">
<div id="time"></div>
</div>
<form>
<input type="" placeholder="write a message">
<input type="file" id="myfile" name="myfile">
<button type="submit" class="submit">Send</button>
</form>
<script>
var date = new Date();
var time = date.getHours() + ":" + date.getMinutes() ;
function showMessage(text,isMine = false) {
document.getElementById("messages").innerHTML += `
<div class="message-row ${isMine?'mine':'theirs'}">
<div class="bubble">${text}</div>
<div class="time">${time}</div>
</div>
`;
}
const ws = new WebSocket('ws://localhost:8080');
ws.addEventListener('message', ev => {
ev.data.text().then(showMessage);
});
document.querySelector('form').onsubmit = ev => {
ev.preventDefault();
const input = document.querySelector('input');
ws.send(input.value);
showMessage(input.value, true);
input.value = '';
}
I have a form in modal dialogue box, once the form is submitted I have to update the sidebar with the form data. How can it be achieved? I have tried by polling the form data at some specific time interval. Is there any other work around?
Communicating between Dialog and Sidebar
Well here's an example of something that's reasonably close to what you are talking about. It's something I made up just to learn how to deal with the PropertiesService. It's not complete but some of it works and you can pass information from the dialog to sidebar via the PropertiesService storage. There is a limit to how much you can store there though. I don't the exact number but I know 26KB is too much.
So anyway once it's running you can use one of the Sender Text Boxes to write a message and press the sender button and the message will go to the PropertiesService and and then back to the Dialog or Sidebar which ever one your sending with via the onSuccessHandler and it will be written in the conversation text box. And if you press refresh on the other dialog or sidebar then it's conversation will be updated as well.
I'm guessing you might be able to find a way to perform the refresh automatically.
Anyway this example covers a lot of the same ground that you might want to cover. Of course realize that I'm not a Google Guru so don't assume that the way I do things is the best way or even a good way. But it does work.
code.gs
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('My Handler Tools')
.addItem('Show MyDialog1','MyDialog1')
.addSeparator()
.addItem('Show MyDialog2','MyDialog2')
.addSeparator()
.addItem('Show SideBar3','SideBar3')
.addSeparator()
.addItem('Log Settings','logSettings')
.addItem('Delete Conversation','delConversation')
.addToUi();
};
function delConversation()
{
PropertiesService.getDocumentProperties().deleteAllProperties();
}
function savConversation(conversation)
{
PropertiesService.getDocumentProperties().setProperties(conversation);
return(conversation);
}
function getConversation()
{
var conversation = PropertiesService.getDocumentProperties().getProperties();
if(typeof(conversation.active) == 'undefined')
{
conversation = {'thread': '***** Start a new thread *****', 'active': true};
}
return conversation;
}
function MyDialog1()
{
var ui = HtmlService.createHtmlOutputFromFile('ModeLessDialog')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(420)
.setHeight(600);
SpreadsheetApp.getUi().showModelessDialog(ui,'MyDialog1');
}
function MyDialog2()
{
var msg = '<html><head><link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">\
<style>\
#my_block{border:5px solid green;padding:10px 10px 10px 0px;}\
</style></head><body><div id="my_block">\
<input type="button" value="Button1" name="Button1" id="My_Button_1" class="My_Tools" />\
<br /><div style="margin-bottom:5px;"><input type="text" value="This is text" id="My_Text_1" class="My_Tools" name="Text1" />\
<br /><input type="button" value="Button2" name="Button2" id="My_Button_2" class="My_Tools" />\
<br /><input type="text" value="This is text" id="My_Text_2" class="My_Tools" name="Text2" />\
<br /><input type="button" value="Exit" onClick="google.script.host.close();" />\
</div></body></html>';
var title = 'MyDialog2';
dispStatus(title,msg);
}
function SideBar3()
{
var ui = HtmlService.createHtmlOutputFromFile('ModeLessDialog').setTitle('Handler Communications');
SpreadsheetApp.getUi().showSidebar(ui);
}
function logSettings(show)
{
var show = typeof(show) !== 'undefined' ? show : true;
var settings = PropertiesService.getDocumentProperties().getProperties();
var html = '<html><head><link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">\
<style>.branding-below{bottom:54px;top:0;}\
.branding-text{left:7px;position:relative;top:3px;}\
.logo{vertical-align:middle;}\
.width-100{width:100%;box-sizing:border-box;-webkit-box-sizing:border-box;?-moz-box-sizing:border-box;}\
label{font-weight:bold;}\
#creator-options,#respondent-options{background-color:#eee;border-color:#eee;border-width:5px;border-style:solid;display:none;}\
#creator-email,#respondent-email,#button-bar,#submit-subject{margin-bottom:10px;}\
#response-step{display:inline;}</style></head>\
<body><div class="sidebar branding-below"><form><h3>Conversation Settings</h3><div class="block" style="border:2px solid black;padding:10px 5px 10px 5px;">';
Logger.clear();
for(var key in settings)
{
html += '<br />' + key + ' = ' + settings[key];
Logger.log(key + ' = ' + settings[key]);
}
html += '<br /><div class="block blockgroup"><input type="button" class="action" value="Exit" onclick="google.script.host.close();" /></div>';
html += '</div></div></form></body></html>';
if(show)dispStatus('Document Properties',html,400,400);
}
function dispStatus(title,html,width,height)
{
// Display a modeless dialog box with custom HtmlService content.
var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
var width = typeof(width) !== 'undefined' ? width : 250;
var height = typeof(height) !== 'undefined' ? height : 300;
var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
var htmlOutput = HtmlService
.createHtmlOutput(html)
.setWidth(width)
.setHeight(height);
SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
}
ModeLessDialog.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<style>
#my_block{border:2px solid black;background-color:rgba(0,150,255,0.2);padding:10px 10px 10px 10px;}
#conv_block{border: 1px solid black;padding:10px 10px 10px 10px;}
.bttn_block{padding:5px 0px 10px 0px;}
.sndr_block {border:1px solid rgba(0,150,0,0.5);background-color:rgba(150,150,0,0.2);margin-bottom:2px;}
</style>
</head>
<body>
<form>
<div id="my_block" class="block form-group">
<div class="sndr_block">
<strong>Sender 1</strong>
<br /><input type="text" size="30"value="" id="sender1msg" class="action" />
<br /><div class="bttn_block"><input type="button" value="Send" name="Sender1" id="sender1" class="action" /></div>
</div>
<div class="sndr_block">
<strong>Sender 2</strong>
<br /><input type="text" size="30" value="" id="sender2msg" class="action" />
<br /><div class="bttn_block"><input type="button" value="Send" name="Sender2" id="sender2" class="action" /></div>
</div>
<div id="conv_block">
<strong>Conversation</strong>
<br /><textarea id="conversation" rows="10" cols="35"></textarea>
<br /><input type="button" value="Save" name="Save" id="save-msg" class="action" />
<input type="button" value="Delete" name="Delete" id="del-msg" class="action" />
<input type="button" class="action" id="disp-log-setting" value="Settings" onClick="google.script.run.logSettings();" />
<input type="button" value="Refresh" class="action" id="refresh" />
</div>
<div id="btn-bar">
<br /><input type="button" value="Exit" onClick="google.script.host.close();" class="green" />
</div>
</div>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(function() {
$('#sender1').click(sendMessage1);
$('#sender2').click(sendMessage2);
$('#del-msg').click(deleteConversation);
$('#save-msg').click(saveConversation);
$('#refresh').click(refreshConversation);
google.script.run
.withSuccessHandler(updateConversation)
.withFailureHandler(showStatus)
.getConversation();
});
function sendMessage1()
{
var message = $('#conversation').val() + '\nSender1:\n' + $('#sender1msg').val();
var newconversation = {'thread': message, 'active': true};
$('#sender1msg').val('');
$('#conversation').css("background-color", "#ffe866");
google.script.run
.withSuccessHandler(updateConversation)
.withFailureHandler(showStatus)
.savConversation(newconversation);
}
function sendMessage2()
{
var message = $('#conversation').val() + '\nSender2:\n' + $('#sender2msg').val();
var newconversation = {'thread': message, 'active': true};
$('#sender2msg').val('');
$('#conversation').css("background-color", "#ffe866");
google.script.run
.withSuccessHandler(updateConversation)
.withFailureHandler(showStatus)
.savConversation(newconversation);
}
function deleteConversation()
{
var conversation = {'thread': '***** Start a new thread *****', 'active': true};
$('#conversation').css("background-color", "#ffe866");
google.script.run
.withSuccessHandler(updateConversation)
.withFailureHandler(showStatus)
.savConversation(conversation);
}
function saveConversation()
{
var message = $('#conversation').val();
var newconversation = {'thread': message, 'active': true};
$('#conversation').css("background-color", "#ffe866");
google.script.run
.withSuccessHandler(updateConversation)
.withFailureHandler(showStatus)
.savConversation(newconversation);
}
function updateConversation(conversation)
{
$('#conversation').val(conversation.thread);
$('#conversation').css("background-color", "white");
}
function refreshConversation()
{
$('#conversation').css("background-color", "#ffe866");
google.script.run
.withSuccessHandler(updateConversation)
.withFailureHandler(showStatus)
.getConversation();
}
function showStatus()
{
dispStatus('showStatus','This is status');
$('#conversation').css("background-color", "#ffb3b3");
}
console.log('ModeLessDialogJavaScript');
</script>
</body>
</html>
Please I need help. I have the same need of this post. I followed the instructions but I can't find my error. I'm frustratred.
When I submit with null fields, the script shows me a blank page.
When I submit with complete fields, the script shows me a blank page also and never upload the file.
This is my final code:
code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "NHD Papers";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName + ", Division: " + form.myDivision + ", School: " + form.mySchool + ", State: " + form.myState);
return "<h2>File uploaded successfully!</h2><p>Copy and paste the following URL into registration:<br /><br /><strong>" + file.getUrl() + '</strong></p>';
} catch (error) {
return error.toString();
}
}
form.html
<p>
<form id="myForm" onsubmit="validateForm();">
<h1>NHD Paper Upload</h1>
<label>Name</label>
<input type="text" name="myName" class="required" placeholder="Enter your full name..">
<label>Division</label>
<input type="text" name="myDivision" class="required" placeholder="(ex. Junior or Senior)">
<label>School</label>
<input type="text" name="mySchool" class="required" placeholder="Enter your school..">
<label>Affiliate</label>
<input type="text" name="myAffiliate" class="required" placeholder="Enter your affiliate..">
<label>Select file to upload. </label>
<input type="file" name="myFile">
<input type="submit" value="Submit File" >
<br />
</form>
</p>
<div id="output"></div>
<script>
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
this.value='Please be patient while your paper is uploading..';
var myFormObject = document.getElementById('myForm');
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(myFormObject);
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 15px; }
p {margin-left:20px;}
</style>
Regards,
In the IFRAME mode HTML forms are allowed to submit, but if the form has no action attribute it will submit to a blank page.
The solution suggested by the official documentation is to add the following JavaScript code to prevent all form submitions on load:
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
</script>
You can also add a return false; or event.preventDefault() at the end of your validateForm() function.
I'm basically having the same issue addressed in a previous question (Django request.POST does not contain the name of the button that submitted the form) but the fix described there does not work.
I am using ajax so that, after submission, I stay on the same page. My page has two forms. The first form has three buttons and I correctly pass the "name" of the button in the GET request. My second form has two buttons but I am unable to pass the "name" of either button in the GET request (the "name" of the input field, however, is in the GET request). I don't know why it's not working. Any ideas?
JS SOLUTION:
$(document).ready(function(){
console.log("hello from email.js");
$('.email_citations').submit(function(event){
console.log("submit email");
var whichButton = $(".form_button[clicked=true]")[0].value
console.log("WHICH BUTTON: ");
console.log(whichButton);
var email_address = $(this).val();
var data = $(this).serialize();
data += "&" + whichButton;
console.log(data);
$.ajax({
data: data,
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(data){
console.log("DATA: ");
console.log(data);
$('.email_sent_message').html(JSON.parse(data).submit_message);
}
});
return false;
});
$(".form_button").click(function() {
$(".form_button").removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
html forms:
<!-- This form works! -->
<form action="export_options" method="get">
<button type="submit" name="plain" class="button inline large hover" id="exportButton2">Download Plain Text</button>
<button type="submit" name="ris" class="button inline large hover" id="exportButton1">Download RIS File</button>
<button type="submit" name="bibtex" class="button inline large hover" id="exportButton3">Download BibTeX File</button>
</form>
<form class="email_citations" id="EmailCitationsForm" action="email_it" method="get">
<input class="input-text" type="text" size="75" maxlength="75" style="width: 40%; font-size: 16px; margin-right: 5px; height: 50px" name="email_address" placeholder="email address">
<button type="submit" value="selected" name="which_citations" class="form_button button inline large hover" id="exportButton4" >Send My Selected Citations</button>
<button type="submit" value="all" name="which_citations" class="form_button button inline large hover" id="exportButton5">Send All Citations</button>
</form>
<div class="email_sent_message" style="float: left; color: #9e1d2a; font-size: 20px; font-weight: bold">{{ submit_message }}</div>
My javascript/ajax in an email.js file:
$(document).ready(function(){
console.log("hello from email.js");
$('.email_citations').submit(function(event){
console.log("submit email");
var clicked_button = $(".form_button[clicked=true]")[0].name;
console.log(clicked_button);
clicked_button.push($(".form_button[clicked=true]")[0].value);
console.log(clicked_button);
var email_address = $(this).val();
var data = $(this).serialize();
data += "&" + clicked_button;
console.log(data);
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(data){
$('.email_sent_message').html(JSON.parse(data).submit_message);
}
});
return false;
});
$(".form_button").click(function() {
$(".form_button").removeAttr("clicked");
$(this).attr("clicked", "true");
});
});`
My view:
def email_it(request):
context = RequestContext(request)
if request.method == 'GET':
getdict = request.GET.dict()
form = EmailCitationsForm(request.GET)
if form.is_valid():
context = request.session.get('All_Citations_Context')
if ('which_citations') in getdict.keys():
if 'all' in getdict.values():
text_template = 'email_allCitations.txt'
html_template = 'email_allCitations.html'
text_content = render_to_string(text_template, context, context_instance=RequestContext(request))
html_content = render_to_string(html_template, context, context_instance=RequestContext(request))
msg = EmailMultiAlternatives(subject, text_content, from_email, to)
#msg.attach()
msg.attach_alternative(html_content, "text/html")
msg.send()
submit_message = "Thank you. Your citations have been sent via email."
return http.HttpResponse(json.dumps({'submit_message': submit_message}))
if 'selected' in getdict.values():
text_template = 'email_selectedCitations.txt'
html_template = 'email_selectedCitations.html'
text_content = render_to_string(text_template, context, context_instance=RequestContext(request))
html_content = render_to_string(html_template, context, context_instance=RequestContext(request))
msg = EmailMultiAlternatives(subject, text_content, from_email, to)
msg.attach_alternative(html_content, "text/html")
msg.send()
submit_message = "Your citations have been sent via email."
return http.HttpResponse(json.dumps({'submit_message': submit_message}))
else:
submit_message = "Something went wrong. Sorry, your email did not send."
else:
submit_message = form.errors['email_address']
else:
form = EmailCitationsForm()
submit_message = ""
return http.HttpResponse(json.dumps({'submit_message': submit_message}))
Ok, this is more of an HTML/jQuery problem than a Django one.
First, your first form works because presumably you let the browser handle the submit. If you use a similar code to the one provided, it does not work.
If you log $(this).serialize() you get precisely what you get on the backend. Check out this answer jQuery: how to get which button was clicked upon form submission?
<form class="email_citations" id="EmailCitationsForm" action="email_it" method="get">
<input class="input-text" type="text" size="75" maxlength="75" style="width: 40%; font-size: 16px; margin-right: 5px; height: 50px" name="email_address" placeholder="email address">
<button type="submit" value="selected_citations" name="selected_citations" class="form_button button inline large hover" id="exportButton4" >Send My Selected Citations</button>
<button type="submit" value="all_citations" name="all_citations" class="form_buttonbutton inline large hover" id="exportButton5">Send All Citations</button>
</form>
Notice I've removed the django bits.
$(document).ready(function(){
console.log("hello from email.js");
$('.email_citations').submit(function(event){
console.log("submit email");
var clicked_button = $(".form_button[clicked=true]")[0].name;
console.log(clicked_button);
var email_address = $(this).val();
var data = $(this).serialize();
data += "&" + clicked_button;
console.log(data);
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(data){
$('.email_sent_message').html(JSON.parse(data).submit_message);
}
});
return false;
});
$(".form_button").click(function() {
$(".form_button").removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
Or see in plunker http://plnkr.co/edit/CxPGmxQfeHhtsWiANDJ1
I'm busying with passing some values of hidden input with an ajax form. I've tried may ways but it looks like the values didn't go through.
HTML
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="hidden" name="sid" value="$rec_sStdi[std_sid]" />
<input type="hidden" name="stid" value="$rec_sStdi[stdi_sid]" />
<input type="text" name="title" class="form-control" size="50" maxlength="128" autocomplete="off" placeholder="ชื่อไฟล์ เช่น แบบประเมินครู เป็นต้น"/>
<progress id="progressBar" value="0" max="100" style="width:100%;"></progress>
<button class="btn btn-primary btn-xs pull-right" type="button" value="Upload File" onclick="uploadFile()"><i class="glyphicon glyphicon-upload"></i> อัพโหลด</button>
<input type="file" name="file1" id="file1" class="btn btn-danger btn-xs pull-right">
<b id="status"></b>
<p id="loaded_n_total"></p>
</form>
Javascript
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
//alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "inc/eval_file_upload.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
PHP (eval_file_upload.php)
<?
$sid=$_POST['sid'];
$stid=$_POST['stid'];
$title=$_POST['title'];
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "../files/$fileName")){
echo "\"$fileName\" upload is complete (sid:$sid , stid:$stid, title:$title)";
} else {
echo "move_uploaded_file function failed";
}
?>
I tried to test the passing by echoing the hidden values. But nothing shows up.
ref : http://www.developphp.com/view.php?tid=1351
Try to add the params in your ajax call:
sid = document.getElementById("sid").value;
stid = document.getElementById("stid").value;
formdata.append("sid", sid);
formdata.append("stid", stid);
And adds an id to your input type hidden.
<input type="hidden" id="sid" name="sid" value="$rec_sStdi[std_sid]" />
<input type="hidden" id="stid" name="stid" value="$rec_sStdi[stdi_sid]" />