Send both POST and GET in HTML form - javascript

I'm trying to make a form that sends submitted data to both email and a .txt file when pressing Submit.
After some research here on Stack Overflow I'm now a bit stuck.
I made a new action in the tag and if the "send-email.php" file name is correct in "new_action.php" only the email function works.
If I have the "send-email.php" incorrect or delete it, the "get-data.php" (using $_GET) works fine.
So yeah, I want both to work.
I guess there's something wrong with the Javascript?
Here's the whole chain:
HTML
<form name="form-name" method="Post" action="new_action.php" id="form-one" onsubmit="process()">
NEW_ACTION.PHP
<?php
include('send-email.php');
include('get-data.php');
?>
JAVASCRIPT
function process() {
var form = document.getElementById('form-one');
var elements = form.elements;
var values = [];
for (var i = 0; i < elements.length; i++)
values.push(encodeURIComponent(elements[i].name) + '=' +
encodeURIComponent(elements[i].value));
form.action += '?' + values.join('&');
}

Related

Resetting/Clearing Form Upon Button Click w/ Firebase

I'm having trouble actually clearing the content of a form upon button click with Firebase. I'm able to use type="reset"on another form I have that just has one text field, however, the second form has two text fields and when I try the following:
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
or I try this (something just using reset()):
function clearFields() {
document.getElementById(userCityEmail).reset();
document.getElementById(cityTextField).reset();
}
The page will reload but nothing is sent to the Firebase. If I don't use the above functions and leave the text within the text field, it sends the content to Firebase. Where am I going wrong? Thanks in advance!
Here's my HTML form:
<form id="myform" method="post">
<input type="email" class="contactUsEmail" id="userCityEmail" placeholder="Enter email" name="contactUsEmail">
<input type="text" class="contactUsEmail" id="cityTextField" placeholder="City" name="contactUsCity">
<button type="submit" id="citySubmitButton" onclick="submitCityClick(); clearFields(); return false;" class="btn btn-primary contactUsButton">Submit</button>
</form>
Javascript:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
var citySubmitButton = document.getElementById('citySubmitButton');
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push().set(userEmail);
}
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
Figured out what happened now.
The problem you had was that you were calling
firebaseRef.child("potentialCities").push().set(userEmail);
This doesnt make sense. Either use just push(userEmail) or set(userEmail).
The difference between these two things is that push will create a random ID under the potentialCities tree node, and set will put user email data right under the same object. It probably will be overwritten. Push is recomended for this case.
To explain the field clearing, still have the clearfields method in the submit click method. Code beneath
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push(userEmail);
clearFields()
}
This also expects that you have the right firebase ref, have you checked the url you are using?
Another thing you are doing wrong is that you are declaring these variables:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
Then trying to get the elementById, with that variable, in clearFields:
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
This doesnt work, you have to either get it by string in clearFields or just use the variable you declared:
userCityEmail.value = "";
or
document.getElementById('userCityEmail').value = "";
I would not recommend to just pull in jQuery just for that reason. It's a big library, and if you can suffice with vanilla javascript, do that!

passing value to a different webpage form

I'm trying to learn to make a webapp using JavaScript along side with nodejs. I'm all out of ideas and have no clue if im doing this correctly. So what im trying to do is when a user clicks on a row of a the dynamically created table it opens up a new html page with a bunch of form inputs already filled in with the values in a json. Right now I have it that when I click on the table row I can get the Id chosen and as a test i want to load it in to a input field but im getting it as undefined
a good portion of the table creating function with the fillform function
for (i = 0; i < attendee.length; i++) {
var tr = document.createElement('TR');
if(i % 2 == 0)
{
tr.bgColor = '#E9F2F5';
}
for (var j = 0; j < attendee[i].length; j++) {
var td = document.createElement('TD');
/* if (j != 0) {
td.setAttribute('contenteditable', 'true');
}*/
td.appendChild(document.createTextNode(attendee[i][j]));
tr.appendChild(td);
var currentRow = table.rows[i];
var createClickHandler =
function(tr)
{
return function() {
var cell = tr.getElementsByTagName("td")[0];
var id = cell.innerHTML;
fillForm(id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
tableBody.appendChild(tr);
}
myTableDiv.innerHTML = "";
myTableDiv.appendChild(table);
}
// this function is included in the html page as a onload function
function fillForm(id)
{
window.open("/populatedForm.html");
document.getElementById("id").value = id;
console.log(id);
}
Part of the html input I want to fill out.
<div class=container2>
<form method="PUT" action="/process-form" enctype="multipart/form-data" autocomplete="off">
<fieldset>
<label>
ID<br/>
<input id="id" name="id" type="text" value=" " required/>
</label>
<br/>
This is how my table looks like
And this is how the input looks like when I click on a row in the table. It opens the new html page but the input is set to undefined. I havent done the rest since I cant get id to work.
Any advice would be great! Thank you!
I am going to further answer this down here as it is too long for me to post in the comments.
Once you figure out how to do routing you won't want to do it another way, here is a great resource http://expressjs.com/en/guide/routing.html . Look at the route parameters section.
So what I would do is have a route like /populatedForm/:id. In express it will look something like this.
app.get('/populatedForm/:id', function(req, res) {
res.send(req.params);
});
req.params will grab the id you want to grab, and then where it says res.send() is where you can handle all the business logic from that route. That is where I'd make a call out to the database to grab all the information for that ID, and then send it as a json, then handle the JSON on your front end.
it'd look something like this
app.get('/populatedForm/:id', function(req, res) {
var myJson = getIdAndOtherInfoFromDatabase(req.params);
res.send(myJson);
});
Then you can handle all of it on the front end via JSON. I would google around a bit about this stuff if you get confused or stuck.

How to read <input type="hidden"...> in JavaScript on subsequent page?

One first page:
A form SUBMIT goes to a subsequent page.
VBscript can see the hidden value with ... Request("myName") ...
How do I do the same thing in JavaScript.
alert(window.location.search);
or
alert(window.top.location.search.substring(1));
return nothing.
Well, you dont. When you submit a form it sends the values to a server, and the "server-side" reads that in vbscript as Request (Requested). If you want to let the requested value accessible to the Javascript, your server-side (subsequent) page must write that Request data back to the client-side, in other worlds, you have to write the requested value directily in the HTML that will be send back to the client browser.
Ex: In your ASP (Server-Side Subsequent VBScript file) you should write
Response.Write ("<script type=""text/javascript"">alert('" & Request("Data") & "')</script>")
<input type='hidden' id='hiddenId'/>
jQuery:
var value = $('#hiddenId').val();
alert(value);
Or
var value = document.getElementById('hiddenId').value;
alert(value);
In your form, you have to have the method set to GET.
<form method="GET" action="somepage">
<input type=hidden name=myHiddenValue />
</form>
Then on the next page, you can parse the search part of the url with a function like this.
function parseSearch(search, key) {
search = search.substring(1), items=search.split("&");
for (var i=0; i<items.length; i++) {
var item = items[i], parts = item.split("=");
if (parts[0] === key) {
return parts[1] || true;
}
}
}
parseSearch(location.search, "myHiddenValue"); // returns the hidden value
live demo

Appending an Array and String in javascript into a variable

How can you run a getelementbyid on an Array and a String in Javascript and set it as a variable that is not null for example foo["dog"] x = getelementbyid(foo[0]+"food") and now x = dogfood
<script>
var myrows = new Array();
$(function() {
$("#check").click(function(){
myrows=[]
$(".head input:checked").not("#selectall").each(function(){
myrows.push($(this).parent().attr("id"));
}).value;
alert(myrows);
});
$("#subbut").click(function(){
var x;
var r=confirm("Are you sure you?");
if (r==true){
x="You pressed OK!";
}else{
Object.cancel;
}
**alert( myrows[0]+"servername" + " before" );
for(var i =0; i< myrows.length; i++){
alert(myrows[i] +"rootname" +" in loop" );
var j= document.getElementById(xmyrows[i] +"rootname" );
alert(j+" after call" );
var y = document.getElementById(myrows[i]+"servername");
document.getElementById("id_rootname").value= j.textContent;
document.getElementById("id_servername").value= y.textContent ;**
$.post($("#forms").attr("action"), $("#forms").serialize(), function(data) {
});
}
});
});
</script>
I don't really understand what the array/string problem is, but from the comments it seems you're looking for a way to do dynamic form submission: Dan Davis has provided the nuts and bolts of the solution in his comment — for each form you need to submit dynamically (without a refresh), create an iframe, then set the respective form's target attribute to that iframe's ID:
<form id="form1" target="#form1Response">
...
</form>
<form id="form2" target="#form2Response">
...
</form>
<iframe id="#form1Response"></iframe>
<iframe id="#form2Response"></iframe>
You will then need to attach your server response callbacks to the various iframes' load events. Beware though: even an empty iframe fires a load event, so you will need to filter false positives (empty iframe contents) in your callback.
Another caveat: if your server responds with JSON, IE will prompt the user to save the response to the filesystem before your script can intercept — so make sure the MIME type heading is set to text/plain or text/html to make sure the response is loaded into the iframe's DOM.
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = myrows[i]+"rootname";
str = str.replace(/^\s+|\s+$/g,"");
var str1 = myrows[i]+"servername";
str1 = str1.replace(/^\s+|\s+$/g,"");
var j= document.getElementById(str);
var y = document.getElementById(str1);
document.getElementById("id_rootname").value= j.textContent;
document.getElementById("id_servername").value= y.textContent ;
}

Dynamically loaded form won't update correctly

I have a form which is loaded into the page using .load(). I want to update the form with the HTML I compute in str, but my code isn't updating the form correctly. Why?
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
});
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
}
You have to put the form modification in the load completion function like this:
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
});
}
The way you were doing it, your code to modify the form was running before the form finished loading so it wouldn't find the content and thus couldn't modify it.
Sorry, I figured i couldnt nest a form within a form. I think thats why it didnt work

Categories

Resources