How can I get data using jQuery from golang code (server)? - javascript

Users will submit data using the text editor given on the website. My golang server will capture it , process it and then display result below the text editor on the website.
I am able to get the user input and process it, but I'm unable to send it back to website for displaying results.
main function:
http.Handle("/", http.FileServer(http.Dir("./codemirror")))
http.HandleFunc("/getRules", getRules)
...
getRules function:
//capture form data
//do some processing on captured data
js, _ := json.Marshal(resp)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
index.html:
<!DOCTYPE html>
<html>
<head>
<title>nvrule playground</title>
<link rel="stylesheet" type="text/css" href="plugin/codemirror/lib/codemirror.css">
<link rel="stylesheet" type="text/css" href="plugin/codemirror/theme/the-matrix.css">
<style>
.button {
padding: 15px 25px;
font-size: 24px;
text-align: center;
cursor: pointer;
outline: none;
color: #fff;
background-color: #4CAF50;
border: none;
border-radius: 15px;
box-shadow: 0 9px #999;
}
.button:hover {background-color: #3e8e41}
.button:active {
background-color: #3e8e41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
</style>
</head>
<body>
<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>
<form action="/getRules" method="post" id="ruleForm" target="hiddenFrame">
<textarea id="codemirror-textarea" name="rule"></textarea>
<input class="button" type="submit" value="Send" />
</form>
<!-- javascript -->
<script type="text/javascript" src="plugin/codemirror/lib/codemirror.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/default.js"></script>
</body>
</html>
default.js:
var editor = CodeMirror.fromTextArea(document.getElementById("codemirror-textarea"), {
lineNumbers : true,
theme : "the-matrix",
value: "Enter rules here"
});

I figured it out. You can use ajax.
$('#ruleForm').submit(function(e){
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(json){
console.log(json)
var templateHtml = $('#resultsArea').html(),
template = Handlebars.compile(templateHtml);
$('#ajaxResponse').html(template(json));
}
});
});
useful link:stackoverflow (question contains my answer)

You can have an endpoint to get the status of the processing that you can poll using setTimeout, something like:
/rule/:id/status
It can return a status code such as (apart of the typical 404, 500, etc.):
{ status: "processing | idle | finished" }
Once the status is finished then GET the result.
/rule/:id
Hope it helps.

Related

Iframe runner with inputable URL

*Note I am using google app scripts
I am attempting to code a simple program as proof of concept, the concept being a Iframe that responds to the input of a html text box. So far I have looked into the triggers for the form element (I decided to use onsubmit) and researched the changing of an Iframe src. It starts out working, when I load it up it looks like this:
After that though, I type the url in the text box and click submit. It reloads, than displays a completely blank screen. Here is my code:
code.gs
function doGet() {
return HtmlService.createTemplateFromFile('Index')
.evaluate();
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
Index.HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include ('Css'); ?>
</head>
<body>
<form>
<input type="text" id="uri" name="uri"><br><br>
<input type="button" value="Submit" onclick="frameS">
<form>
<script>
function frameS() {
var urv = document.getElementById('uri');
var ura = urv.value;
url1 = trim(ura);
}
function trim(str){
return str.replace (/^\s+|\s+$/g, '');
}
</script>
<iframe allowfullscreen="true" width="600" height="400" id="abc" src="https://www.google.com/webhp?igu=1">sorry, couldn't load</iframe>
<?!= include ('javascript'); ?>
</body>
</html>
javascript.html
<script>
Logger.log('hit')
</script>
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
Css.html *please note that the style sheet is not currently doing anything, I'm just including it for future development
<style>
/* CSS reset */
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td {
margin:0;
padding:0;
}
html, body {
margin: 0;
padding: 0;
}
body {
font-family: 'Roboto', sans-serif;
font-weight: 100;
}
fieldset {
border: 1px solid white;
color: white;
text-align: center;
width: 200px;
}
legend {
padding: 0 10px;
}
</style>
Thanks for your time and would appreciate any feedback on my code, related to the question or not.

My code will run in code pen, but not in the browser when I open a .html file?

when I run this code in codepen it works fine.
But when I open it through a .html file it doesn't work.
When I opened the developer tool it had an error with the jQuery.
I am new at javascript so I'm not sure what is wrong here. Any help is appreciated.
It's definitely the JQuery that is getting me in trouble.
My error messages.First one: Failed to load resource: net::ERR_FILE_NOT_FOUND jquery.js Second Error: Uncaught ReferenceError: $ is not defined on line 74 which is at the end of the code where my comments are // run nextPrompt function when button is clicked.
Code:
<!DOCTYPE html>
<head>
<link href='https://fonts.googleapis.com/css?family=Fjalla+One' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>
<script src="/assets/jquery.js"></script>
<style>
body {
text-align: center;
font-family: 'Fjalla One';
font-size: 20px;
background: #e6eaf0;
}
button {
margin: 40px;
}
input {
font-size: 24px;
}
.fill {
background: white;
color: red;
border-bottom: 2px black solid;
font-family: 'Shadows Into Light';
padding: 0 6px;
margin: 4px;
}
</style>
</head>
<body>
<div class="prompt"></div>
<button>Next</button>
<script>
// List of prompts for the user
var prompts = [
'Type your name',
'Type an adjective',
'Type a noun'
];
var answers=[];
// Keep track of current prompt we're on
var currentPrompt = 0;
// A function that will call the next prompt
var nextPrompt = function() {
//if there's no answer in the form
if (currentPrompt != 0){
answers.push($('input').val());
}
// if there is a next prompt
if (currentPrompt < prompts.length) {
// put first prompt in all html elements with class
$('.prompt').html(prompts[currentPrompt] +'<br><input type="text">');
// move the next prompt into variable currentPrompt
currentPrompt = currentPrompt + 1;
}
//or else if we're at the end of the array
else {
// put a new message into the html.
showFinal();
}
}
//puts user answers into HTML
var showFinal = function() {
$('.prompt').html('This is the story of <span class="fill">'+answers[0]+'</span> and the <span class="fill">'+answers[1]+'</span> <span class="fill">'+answers[2]+'</span>.');
//and then hide the button
$('button').hide();
}
// run nextPrompt function when button is clicked
$('button').click(function() {
nextPrompt();
});
// Show the first prompt as soon as js loads
nextPrompt();
</script>
</body>
</html>
you get this error because <script src="/assets/jquery.js"></script> is failed to load the jquery. both errors are related to this.
remove <script src="/assets/jquery.js"></script> and add
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
it will load a jquery from cdn.
it will removed your error.
checkout the refactored code below
<head>
<link href='https://fonts.googleapis.com/css?family=Fjalla+One' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>
<!-- <script src="/assets/jquery.js"></script> -->
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script><style>
body {
text-align: center;
font-family: 'Fjalla One';
font-size: 20px;
background: #e6eaf0;
}
button {
margin: 40px;
}
input {
font-size: 24px;
}
.fill {
background: white;
color: red;
border-bottom: 2px black solid;
font-family: 'Shadows Into Light';
padding: 0 6px;
margin: 4px;
}
</style>
</head>
<body>
<div class="prompt"></div>
<button>Next</button>
<script>
// List of prompts for the user
var prompts = [
'Type your name',
'Type an adjective',
'Type a noun'
];
var answers=[];
// Keep track of current prompt we're on
var currentPrompt = 0;
// A function that will call the next prompt
var nextPrompt = function() {
//if there's no answer in the form
if (currentPrompt != 0){
answers.push($('input').val());
}
// if there is a next prompt
if (currentPrompt < prompts.length) {
// put first prompt in all html elements with class
$('.prompt').html(prompts[currentPrompt] +'<br><input type="text">');
// move the next prompt into variable currentPrompt
currentPrompt = currentPrompt + 1;
}
//or else if we're at the end of the array
else {
// put a new message into the html.
showFinal();
}
}
//puts user answers into HTML
var showFinal = function() {
$('.prompt').html('This is the story of <span class="fill">'+answers[0]+'</span> and the <span class="fill">'+answers[1]+'</span> <span class="fill">'+answers[2]+'</span>.');
//and then hide the button
$('button').hide();
}
// run nextPrompt function when button is clicked
$('button').click(function() {
nextPrompt();
});
// Show the first prompt as soon as js loads
nextPrompt();
</script>
</body>
</html>

jQuery Ajax Json Parsing in HTML File Not Working with Google Cloud Service

I have been working with jQuery/JavaScript and ajax for the first time and I am trying to work with the weather underground API to display some weather information on a web-page hosted on google cloud.
I have been reading the weather underground code example and I am trying to work with that which is why the code will look so familiar but I am just trying to get it to work so I can move forward. I have also looked at other stack overflow where similar code questions were asked but I am still not getting anywhere. I apologize for the redundancy but I am unsure why it is not working.
Everything seems to be making sense but when the HTML is suppose to "alert" when the page is loaded I am getting nothing. I would really appreciate some input even if I am doing something stupid just want to get this chunk working in order to move forward.
Below is my HTML file that is a mix of JavaScript and HTML.
<!DOCTYPE html>
<html>
<head>
<title>Hello, The Cloud!</title>
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
<body>
<h1>Hello, The Cloud!</h1>
<p> Lets Check the Weather! </p>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
</html>
My simple CSS file is shown below.
h1 {
color: #000000;
text-align: center;
font-size: 60px;
text-decoration: underline;
}
body {
background-color: LavenderBlush;
font-size: 20px;
}
div {
background-color: lightgrey;
color: #FF0000;
id: "clockbox";
font-size: 20px;
font-family: "Times New Roman", Times, Serif;
width: 420px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
.alert {
padding: 20px;
background-color: #f44336; /* Red */
color: white;
margin-bottom: 15px;
}
I appreciate any feedback!
Thank you
Thanks to some great advice from #GAEfan and yuriy636 I was able to figure out that Google Cloud does not play well with HTTP requests thus it was just a simple change from HTTP to HTTPS in the URL's as you can see in the code below.
<!DOCTYPE html>
<html>
<head>
<title>Hello, The Cloud!</title>
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
<body>
<h1>Hello, The Cloud!</h1>
<p> Lets Check the Weather! </p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
url : "https://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
success : function(parsed_json) {
console.log(parsed_json);
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
</body>
</html>
Here is a link to more info on Google Cloud and HTTP/HTTPS: https://cloud.google.com/compute/docs/load-balancing/http/
Thank you for everyone's help!
The problem is that you don't have <script> tags inside your <body> tag.
This is what I mean:
<!DOCTYPE html>
<html>
<head>
<title>Hello, The Cloud!</title>
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
<body>
<h1>Hello, The Cloud!</h1>
<p> Lets Check the Weather! </p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
</body>
</html>
If you hit an error first, you won't get to the alert. Try adding this logging, to make sure you aren't getting a key error:
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
console.log(parsed_json);
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});

Multiple Submit Actions

I have a script given to me by another developer to send push messages to my Apps.
I want to be able to send them from one page to both App types but cannot figure how.
Problem is I do not have any control over the pages on the server they are sent to.
If you look at the code the only differences in the two critical pieces of code are the Form action to send them to each Server page and the name of the App Id's...the other info remains the same.
I also found a piece of javascript to submit to two places from one button but could not get it working with both...
I know from reading that I probably need an array...Could someone please show me some code with these in an array with a submit button to send them to their respective pages.
Thanks in advance...
EDITED
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../../ScriptLibrary/jquery-latest.pack.js"></script>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<form name="push" method="post" >
<input name="pushmessage" type="hidden" value="HAIR EXTENSIONS ">
<p align="center">Notification Message:<br />
<textarea style="width: 280px; height: 150px; margin-bottom: 30px; font-family: Verdana, Geneva, sans-serif; border-color: #000; border- width: 1px; resize: none;" name="pushmessage" id="push-message"> </textarea><br />
<input type='button' class="inputbtn" name='Submit' value='Push' onclick='sendFormData()' />
<form/>
<script type="text/javascript">
function sendFormData() {
var formURL1 = 'http://apple/iPhone-message';
var formURL2 = 'http://google/android-message';
var postData1 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','appid':' CommunityApp-i','topics':'test'};
var postData2 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','ap pid':'CommunityApp','topics':'test'};
submitForm(formURL1, postData1);
submitForm(formURL2, postData2);
};
function submitForm(formURL, postData) {
$('#push-message').append('sending data to url : '+formURL+'\n');
$.ajax(
{
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$('#push-message').text('success');
},
error: function (jqXHR, textStatus, errorThrown) {
$('#push-message').append('oops:error occured'+errorThrown+'\n');
}
});
}
</script>
</body>
</html>
You should not use native submit button (that triggers a page change) but use a ajax submit method using XHR object.
You can take a look to this jquery plugin: http://jquery.malsup.com/form/
you dont need to html form tag, you can do that with this piece of this code:
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<form name="push" method="post" >
<input name="pushmessage" type="hidden" value="HAIR EXTENSIONS ">
<p align="center">Notification Message:<br />
<textarea style="width: 280px; height: 150px; margin-bottom: 30px; font-family: Verdana, Geneva, sans-serif; border-color: #000; border- width: 1px; resize: none;" name="pushmessage" id="push-message"> </textarea><br />
<input type='button' class="inputbtn" name='Submit' value='Push' onclick='sendFormData()' />
<script type="text/javascript">
function sendFormData() {
var formURL1 = 'http://apple/iPhone-message';
var formURL2 = 'http://google/android-message';
var postData1 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','appid':' CommunityApp-i','topics':'test'};
var postData2 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','ap pid':'CommunityApp','topics':'test'};
submitForm(formURL1, postData1);
submitForm(formURL2, postData2);
};
function submitForm(formURL, postData) {
$('#push-message').append('sending data to url : '+formURL+'\n');
$.ajax(
{
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$('#push-message').text('success');
},
error: function (jqXHR, textStatus, errorThrown) {
$('#push-message').append('oops:error occured'+errorThrown+'\n');
}
});
}
</script>

TypeError: contactList3 is undefined in soy compilation

I'm passing data to closure template(soy) via Javascript (json) but getting the about error in firebug.
// Simple html that starts the whole process
<html lang="en">
<head>
<title>Gigya Social Demo - getContacs</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.lightbox_me.js"></script>
<!-- add the soy js here-->
<script type="text/javascript" src="emailcontacts.js"></script>
<script type="text/javascript" src="invite_emailcontacts_view.js"></script>
<script type="text/javascript">
function openLightbox() {
var data = [{"provider":"Yahoo","firstName":"myname","lastName":"mysurname","nickname":"mynick","email":"email#hotmail.com","photoURL":"http://l.yimg.com/dh/ap/social/profile/profile_b10.png"}];
var invite = new InviteContactEmailView();
console.log(invite);
invite.open(data);
return this;
}
</script>
<style>
#contactsOverlay {
-moz-border-radius: 6px;
background: #eef2f7;
-webkit-border-radius: 6px;
border: 1px solid #536376;
-webkit-box-shadow: rgba(0,0,0,.6) 0px 2px 12px;
-moz-box-shadow: rgba(0,0,0,.6) 0px 2px 12px;;
padding: 14px 22px;
width: 400px;
position: relative;
display: none;
}
</head>
<body onLoad="openLightbox()">
<div id="contactsOverlay">
</body>
</html>
// soy invoker in file invite_emailcontacts_view.js
function InviteContactEmailView() {
this.template = {};
this.template.element = $('#contactsOverlay');
this.elementSelector = this.template.element;
}
InviteContactEmailView.prototype.open = function(contacts) {
this.elementSelector.lightbox_me({destroyOnClose: true, centered: true, onLoad: testme(this.elementSelector, contacts) });
return this;
};
var testme = function(ele, contacts) {
ele.append(jive.invite.emailcontacts.create(contacts));
$('fieldset div').bind('click', function() {
var checkbox = $(this).find(':checkbox');
checkbox.attr('checked', !checkbox.attr('checked'));
});
}
// soy template (on compile resides in file: emailcontacts.js)
{namespace jive.invite.emailcontacts}
/**
* #param contacts
* #depends path=/var/www/statics/js/invite_emailcontacts_view.js
**/
{template .create}
{foreach $contact in $contacts}
<fieldset>
<div>
<div class="data"></div>
<input type="checkbox" id="checkbox">
</div>
</fieldset>
{/foreach}
{/template}
Any kind of help is greatly appreciated.
REgards
Where is the compiled template? Putting a breakpoint in there will tell you more. I suspect you are not passing a hash to the template when you invoke it with a key contacts. Basically the template you declared should get a data set which looks something like this:
{contacts: [....]}
this obviously assumes you are not compiling in advanced mode.

Categories