how do i submit data from HTML using jquery - javascript

The question might not be clear, so i will explain further.
I saw some page like wordpress new post tag, they have something like
[input]
x tag | x tag | x tag
or Facebook Notes when you post a image...
the when you input a tag and press enter, a new tag is insert in to element in the page...
I don't quite understand how can you parse that out and then submit to the form.
if anyone know please give me an idea.
Thanks

If I am getting it right, you are talking about sending AJAX-based post requests "under the hood" and get "dynamic reflections" back on the same page.
Well, if this is the case, there are actually more than just submitting data to the server.
Here is the big picture:
You need a javascript which is loaded in the page that has the form to submit.
Inside that script, you need to define the event which will trigger the AJAX-based post request. Basically you would love trigger such an event when the content in that particular field has been just changed (an onChange event, that is).
Then you can use script like the following:
$.ajax
({
type: 'POST',
cache: false,
async: false,
timeout: 10000,
url : '/path/to/your/serverside/function',
dataType : 'json',
data:
{
'tag' : //whatever you want to be used as the tag
},
success : function(message)
{
//this will be called when this post was successfully been carried out.
//you should update the view (the same page) here using some jQuery script.
//such as : $('#tag').html(message.tag);
},
error : function(message)
{
//this is for displaying error messages (perhaps due to networking problems?)
}
});
Since there are really a lot to write about. I suggest you post whatever you have finished up here so we can give it a check.
At least from my consideration, this scenario require the following knowledge to get everything right(though you can always choose to use less tech):
onChange event triggered
|
|
jQuery =====sending JSON formatted tag info ======> serverside function
|
|
decode JSON tag info
|
|
process(saving it into database?)
|
|
encode feedback info
|
jQuery callback function <===== JSON info==================
|
|
update the view(the same page)
.
.
.
.
.
aforementioned process is before form is submitted via normal POST/GET.

One way is to keep track of the tags you add in a hidden form field, but actually display using divs or spans or whatever UI you want. In the case of facebook, I'd imagine they're doing something somewhat similar, though I guess they could actually be adding form elements dynamically. Forgive the nasty code/css - just tossed it together. If you add tags and then hit submit, you'll see the querystring that all the values are there.
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btnSuggest").click(function(){
var $tagSuggest = $("#tagSuggest");
if($tagSuggest.val() != "")
AddTag($tagSuggest.val());
});
$("#tagSuggest").keyup(function(e){
if(e.keyCode == 13 && $(this).val() != "")
AddTag($(this).val());
});
});
function AddTag(tag){
$("<div>").text(tag).appendTo("#tags").click(function(){
$(this).remove();
UpdateTags();
}).hover(function(){
$(this).addClass("over");
},function(){
$(this).removeClass("over");
});
UpdateTags();
}
function UpdateTags(){
var allTags = "";
$("#tags div").each(function(){
allTags += "," + $(this).text();
});
$("#hidTags").val(allTags.substring(1));
$("#tagSuggest").val("");
}
</script>
<style type="text/css">
.main
{
width: 400px;
padding: 10px;
margin: auto;
border: 1px solid black;
background-color: #e6e6e6;
height: 600px;
}
#tags div
{
padding: 3px;
border: 1px solid black;
background-color: #e6e6e6;
margin: 3px;
height: 15px;
width: auto;
float: left;
cursor: pointer;
}
#tags div.over
{
background-color: red;
}
</style>
</head>
<body>
<div class="main">
<form action="" method="get">
<input type="hidden" name="hidTags" id="hidTags">
<textarea name="Wallpost" style="width: 390px; height: 100px;"></textarea>
<br />
<input type="text" id="tagSuggest" style="width: 280px;" />
<input type="button" id="btnSuggest" value="Add Tag" style="float: right;"/>
<br />
<input type="Submit" name="cmdSubmit" value="Share" style="float: right;"/>
</form>
<div id="tags">
</div>
</div>
</body>
</html>

Related

Calling JavaScript from component template

I'm working on integrating payment forms from a third party, by using the Link to Javascript they provide.
when I place the code in the index.html page its works just fine, but when I move the code to the component template is not working, below is part of the code:
this is the script code to initialize the payment form:
<script>
var tokenpay = TokenPay('tokenpay123');
tokenpay.initialize({
dataElement: 'card',
errorElement: 'errorMessage',
amountElement: 'amount',
useACH: false,
//if displaying all 4 fields then useStyles=false, disableZip=false, disableCvv=false
//if displaying 3 out of 4 fields then useStyles=false, and set disableZip or disableCvv equal to true
//if displaying 2 out of 4 fields then useStyles=true, disableZip=true, disableCvv=true
useStyles: false,
disableZip: true,
disableCvv: false
});
var form = document.getElementById('paymentForm');
form.addEventListener('submit', function(event) {
event.preventDefault();
tokenpay.createToken(function(result) {
alert(result.token)
}, function(result) {
console.log("error: " + result);
});
});
</script>
<script type="text/javascript" src="http://xxx/tokenPay.js"></script>
<form id="paymentForm" action="xxx" method="post" style="margin: 10%;">
<div id="card" style="border: solid 1px lightgray; height: 100px; width: 500px; padding: 20px 10px; border-radius: 10px; margin: 10px 0px;">
</div>
<div id="errorMessage" style="margin-bottom: 10px; color: #c0392b;"></div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
when I'm using these three-part together on the index page is working fine when I'm trying to work from a component template that is not
Put the script tag <script type="text/javascript" src="http://xxx/tokenPay.js"></script> inside the head tag within index.html
Then put the var tokenpay = TokenPay('tokenpay123'); etc block inside ngAfterViewInit within the relevant component (i.e. the component hosting the form). Then it should work fine.
Note that because tokenPay is a global variable, the TypeScript compiler will not recognise it so you will need to add:
declare const tokenPay: any
inside the .ts file of the relevant component.
It's not clear on what problem you're facing, but I think you have to call the <script type="text/javascript" src="http://xxx/tokenPay.js"></script> after your form. By doing so early, the form may not exist yet

Text area with upload attachments options HTML/JQuery

I have created text area that allows user to type in their text as shown below:
<!DOCTYPE html>
<html>
<body>
<textarea rows="4" cols="50">
Please type your favourite foods here and upload attachments if you want!</textarea>
</body>
</html>
I want to allow the user to allow be able to drag/drop or upload file attachments to the textarea but I am not quite sure how I can achieve this. I am quite new to web development and I am not sure what such feature would even be called. I have created a screenshot of what I would like, see below - something along the lines of gmail compose window. Please can someone help me, thanks.
Once the user has written and uploaded the files, I will be saving them to a database.
I suggest using the DropzoneJS library.
Create Dropzone object with the options you need and use the sending event to add textarea text to the POST request.
Change the default template and add your HTML inside div with template-container id. Then add previewTemplate property to myDropzone options
with value
document.querySelector('#template-container').innerHTML
Dropzone.autoDiscover = false;
$(document).ready(function() {
Dropzone.options.myDropzone = {
url: $('#my-dropzone').attr('action'),
paramName: "file",
maxFiles: 5,
maxFilesize: 20,
uploadMultiple: true,
thumbnailHeight: 30,
thumbnailWidth: 30,
init: function() {
this.on('sending', function(file, xhr, formData) {
formData.append('favouriteFoodText', document.getElementById('favourite-food-text').value);
}),
this.on("success", function(file, response) {
console.log(response);
})
}
}
$('#my-dropzone').dropzone();
});
#b-dropzone-wrapper {
border: 1px solid black;
}
#b-dropzone-wrapper .full-width {
width: 100%
}
#b-dropzone-wrapper textarea {
resize: none;
border: none;
width: 99%;
}
#my-dropzone {
top: -5px;
position: relative;
border: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.0/min/dropzone.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.0/min/dropzone.min.css" rel="stylesheet" />
<div id="b-dropzone-wrapper">
<textarea rows=5 id="favourite-food-text" placeholder="please write some text here"></textarea>
<form action="file-upload.php" id="my-dropzone" class="dropzone full-widht" method="post" enctype="multipart/form-data"></form>
<input type="submit" value="Submit your entry" class="full-width" />
</div>
After submitting the form on the server side the transferred data will be parsed by PHP and saved in $_POST and $_FILES super global arrays.

can't make a jfiddle example work

I'm new to AJAX programming, but I found an example on jfiddle that is very close to what I'm trying to accomplish. I can't make it work, however. I put a reference to the same version of jquery in the header, but the page doesn't do anything when I hit the submit button on 'my version'. Also, the animated loading cursor spins forever. Here is the jfiddle reference:
http://jsfiddle.net/clickthelink/Uwcuz/1/
Here is what I think is the same version. I must be doing something wrong, but I'm really not sure what. I can't seem to make it work in StackOverflow either.
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#result").html(returnhtml);
$("#loadingimg").hide();
}
});
});
});
body{
font-family: 'Open Sans', 'Helvetica Neue', 'Arial', sans-serif;
font-size: 13px;
}
form span{
display: block;
margin: 10px;
}
label{
display: inline-block;
width: 100px;
}
input[type="text"]{
border: 1px soild #ccc;
width: 200px;
padding: 5px;
}
input[type="submit"]{
padding: 5px 15px;
}
span#result{
padding: 5px;
background: #ff9;
}
img#loadingimg{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form method="post" action="/echo/html/" ajax="true">
<span id="result">jQuery + AJAX form submit script.</span>
<span>
<label>Message: </label>
<input type="text" name="html" placeholder="Howdy..." />
</span>
<span>
<label><img id="loadingimg" src="http://dev.cloudcell.co.uk/bin/loading.gif"/> </label>
<input type="submit" value="Submit" />
</span>
</form>
SO is sandboxed and will not allow the ajax to go through.
As for the original example, jsFiddle has a "fauxjax" kind of setup that will simulate ajax responses when you use action="/echo/html/" which is why the original example appears to work (though it is just simulated):
See the Jsfiddle Docs for more info on this feature
If you are trying to run this example on your own server etc, make sure to update the action attribute in <form method="post" action="/echo/html/" ajax="true"> to point to the file, on your server or elsewhere, that will receive and respond to your ajax call (like a php script)
Since you're new to Ajax, it may also be helpful to learn about CORRS (Cross Origin Resource Sharing) which will apply if you are ever trying to send an ajax request from one domain and have it received and/or responded to from another domain.
it doesn't work here because http://stackoverflow.com cannot make cross origin requests to http://stacksnippets.net/echo/html/
it probably doesn't work for you because you don't have /echo/html service in your backend

Printing global variables in body in Javascript

I'm working with a piece of code I'm designing in my free time, which is a bit unorthodox so bear with me here. The page is set to run a variety of pages based on which "" tag the html is being read from. I was just looking for a way to condense a number of pages into a single one, and this seemed like it might be interesting to mess with. If you guys know of better ways to do that, any information would be appreciated.
So far I'd managed to get everything working until I hit a part where I was trying to obtain a form value, assign it to a global variable, and then use a script to print the global variable in the text. In this case, it is asking the user's name, the goal being to reproduce the name in various places throughout the website for a more user-friendly feel. I figure understanding this will be useful in the future. Eventually I'll want to figure out how to create a database of usernames and passwords and all that good stuff, but for now, I'm just looking for a simple fix. I'm probably missing something elementary. Here's the code:
<head>
<style>
body {
margin: 0 auto;
background-image: URL('http://fc04.deviantart.net/fs9/i/2006/033/2/c/Matrix_code_by_phi_AU.jpg');
background-attachment: fixed;
background-repeat: repeat-y;
}
</style>
<meta charset="utf-8">
<title>MasterCode</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
var name = "";
//user is "finished typing," collect input
function doneTyping() {
name = document.getElementById('nameid').value;
closeElement('welcomepage');
closeElement('namepage');
showElement('homepage');
}
function closeElement(myelement) {
document.getElementById(myelement).style.display = "none";
}
function showElement(myelement) {
document.getElementById(myelement).style.display = 'block';
}
function enterWebsite() {
closeElement('namepage');
closeElement('homepage');
$("#dialog").dialog({
autoOpen: false
}, {
title: "Change"
}, {
resizable: false
});
$("#opener").click(function () {
$("#dialog").dialog("open");
closeElement('welcomepage');
showElement('namepage');
})
}
function writeName() {
document.write(name);
}
</script>
</head>
<body onload="enterWebsite()">
<div id="welcomepage">
<button id="opener" style='background: url("http://4.bp.blogspot.com/-fDgJmT5rzlM/Tq8SpW3ZcbI/AAAAAAAAA1I/l02iiclqKkA/s1600/tracking%2Bclub%2Bmeet%2B%2526%2BMisty%2BAlgonquin%2Bshots%2B106.jpg") no-repeat top left; color: #FFFFFF; height: 685px; width: 1350px; font: 75px helvetica, cursive'>Enter MasterCode</button>
</div>
<div id="namepage">
<form id='name_input'>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<center>
<input style="background-image:URL('https://waypointprod.blob.core.windows.net/blogfilestore/storage/blogs/headlines/2013/12/5/image.jpg');background-repeat:no-repeat;background-position: ; border: 50px solid black ; height:50px; width:350px; color: #FFFFFF; font: 45px helvetica, cursive;"
id='nameid' type="text" value="Enter your name.">
<br/>
<button id='submit_name' onclick='doneTyping(); return false;'>I Accept The Risks</button>
</form>
</div>
<div id="homepage">
<font size="25" color="white">
Welcome, <script> writeName(); </script>
</font>
</div>
</body>
</html>
Thoughts?
(Edit: Resolved using localStorage as suggested by tewathia)
Not sure if you're using any sort of RESTful API or even nodejs.
If you are, something I do to prevent storing this data in cookie or in sessionStorage is that I utilize server-side to store. Then you wouldn't need to add as much logic on client-side. This user data could be
{
"name": "Don Jon",
"favorite_color": "blue"
}
you could even display different parts of the page in blue to be super user friendly

How to remove "no file selected" from type=file inputs?

I can't seem to figure out any way to remove the "No file selected" text that shows up next to inputs of type "file".
Do you guys know any way how to remove this text?
input[type='file'] {
color: transparent;
}
Enjoy
There is no cross-browser way to do this. The "no file selected" text is in the implementation-defined part of the widget, and I don't believe that most browsers offer much in the way of browser-specific customization. On the other hand, you could simply use CSS to cover the text with something when the value attribute is empty.
You can do this by defining a width to the input and hiding the exceeding content (the undesired "No file selected" text).
input {
width: 132px;
overflow:hidden;
}
Here is the demonstration on jsfiddle.
Beware: each language has its own default text and it may render different input sizes. In brazilian portuguese that 132px width is fine!
My answer was based on this similar question on stackoverflow.
You can replace the file field with a button with the answer to this question: file upload button without input field?
CSS
<style>
#image_file{
position: relative;
width: 188px;
border: 1px solid #BBB;
margin: 1px;
cursor: pointer;
float: left;
}
</style>
HTML
<input id="image_file" onclick="getFile()" onfocus="this.blur()" value=""/>
<div style='height: 0px;width: 0px; overflow:hidden;'>
<input type="file" id="PinSpot_file">
</div>
<input type="button" onclick="getFile()" style="background-color: #DDD;" value="Browser" >
JAVASCRIPT
function getFile(){
document.getElementById("PinSpot_file").click();
}
// Event when change fields
$('#PinSpot_file').live('change', function(e) {
var file = this.value;
var fileName = file.split("\\");
document.getElementById("image_file").value = fileName[fileName.length-1];
//AJAX
}
This is a really good hack and its a lot cleaner.
HTML
<div id="file_info' style='display:inline;'>Browse</div>
<input type="file" name='file[]' multiple style='opacity: 0;' onchange='displayFileName()'/>
JS
function displayFileName() {
var files = $('input[type="file"]')[0].files;
document.getElementById('file_info').innerHTML = files.length + " images to upload";`
}
Well, since there is no way to completely disable the text, I'd suggest either placing an element over the text or try the following solution..
CSS
input[type="file"] {
width: 90px; /* Keep it under 100px in order to hide the unwanted text. */
}
and add an html inline-title attribute to the element to hide the "No File Chosen" hover text.
HTML
<input type="file" id="FileId" title="">
or, you could do it all with JavaScript.
JS
document.addEventListener('DOMContentLoad', myFunction);
function myFunction() {
const FilePicker = document.getElementById('FileId');
FilePicker.style.width = "90px";
FilePicker.title = ""; // Leave This Empty
}
You can try this. Its work for me firefox browser
<style type="">
input[type='file'] {
color: transparent;
}
</style>

Categories

Resources