I have this http://localhost/resume/Template/index.html?msg=Message%20Sent%20Successfully
how do I extract the message "Message Sent Successfully and display it in this form
<form action="send_form_email.php" name="contactForm" method="post">
//I want to display the message here
<h4>E-mail</h4>
<div class="border-stripes">
<input type="email" class="textfield" name="email" placeholder="Your e-mail address" />
</div>
<h4>Message</h4>
<div class="border-stripes">
<textarea class="textarea" name="message" rows="3" placeholder="Your message"></textarea>
</div>
<br />
<br />
<input id="submit" name="submit" type="submit" value="Submit">
</form>
This should echo the GET variable:
<?php echo urldecode($_GET['msg']); ?>
If you want to do this in javascript then you can try to parse query string:
var query = (function() {
function decode(string) {
return decodeURIComponent(string.replace(/\+/g, " "));
}
var result = {};
if (location.search) {
location.search.substring(1).split('&').forEach(function(pair) {
pair = pair.split('=');
result[decode(pair[0])] = decode(pair[1]);
});
}
return result;
})();
$('form[name=contactForm]').prepend('<p>' + query['msg'] + '</p>');
Javascript:
I have write down the function for same using that you can access any parameter of URL.
Example:
function getParamValue(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(location.href);
if (results == null)
return "";
else
return decodeURI(results[1]);
}
alert(getParamValue('param'));
Your solution:
http://jsfiddle.net/tb8cetLy/1/
If you need to do it in php (note that there is no security check for XSS)
<form action="send_form_email.php" name = "contactForm" method="post">
<?php echo urldecode($_GET['msg']); ?>
<h4>E-mail</h4>
<div class="border-stripes"><input type="email" class="textfield" name="email" placeholder="Your e-mail address" /></div>
<h4>Message</h4>
<div class="border-stripes"><textarea class="textarea" name="message" rows="3" placeholder="Your message"></textarea></div><br /><br />
<input id="submit" name="submit" type="submit" value="Submit">
</form>
else in js
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var msg = getParameterByName('msg');
$( "form" ).prepend( "<p>"+msg+"</p>" );
The function getParameterByName is taken from here
I guess you are doing something like this in send_form_email.php
// process form data
// redirect to index.html with $_GET['msg'] variable
If you want pretty URLs, use a function like this below, include it on top of your common file
session_start();
function flash_set($k,$v)
{
$_SESSION['flash'][$k] = $v;
}
function flash_get($k)
{
if(isset($_SESSION['flash'][$k]))
{
$msg = $_SESSION['flash'][$k];
unset($_SESSION['flash'][$k]);
return $msg;
}
return '';
}
change the send_form_email.php to redirect without $_GET parameters, after you process your form put this,
// process form data
flash_set('form','Message Sent Successfully');
// redirect here
Now, use this in your form like,
<form action="send_form_email.php" name="contactForm" method="post">
<?php echo flash_get('form')?> // I want to display the message here
<h4>E-mail</h4>
The flash message will only show up single time after being redirected, if user refreshes the page, it disappears!!
In HTML/PHP only, you would use urldecode($_GET['msg'])
You can also do it with javascript with a function like :
function getQuerystring(key, default_) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
This function will allow you to get msg with var msg = getQuerystring("msg"); and you can mix it with unescape functions ( http://www.w3schools.com/jsref/jsref_unescape.asp ).
Related
I am trying to pass data from a form into a Google Apps Script but when I press submit I am greeted by I blank screen.
Form:
<div id="nameDiv">
<form action="https://script.google.com/a/umbc.edu/macros/s/AKfycbztum1ImJZeXXYt0fFhwOAMUsB5zCsJQohrum4W7qiH/dev">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="google.script.run.nameSearch()">
</form>
</div>
Script:
function nameSearch(){
try {
var firstName = document.getElementById("fname").value
var lastName = document.getElementById("lname").value
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15]
}
}
document.getElementById('nameDiv').innerHTML =
"<center>Last Name:" + lastName + "</center>" +
"</br><center>First Name:" + firstName + "</center>"
} catch(e) {
alert(e)
}
}
I am trying to pass this data to the script so that it can use it to search a google sheet so I cannot just place the script in the html as a client side script. Any thought?
All the HTML-related methods (getElementById, innerHTML, etc.) should be in client-side script, and Apps Script methods should be in the server-side.
If I understand you correctly, you want to do the following:
When this form gets submitted, look for the row whose columns K and L match the inputted fields (indexes 10 and 11 from inputData array).
For this row, return data from columns O and P (indexes 14 and 15 from inputData array).
Write this returned data to the HTML.
If all this is correct, then you could do this:
Add an onclick event in the submit input that will fire a client-side function (a function that is declared inside the tags in the HTML). There is no need to use a for this. The HTML body could be something like this:
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
From this client-side function called clientNameSearch(), retrieve the values from fname and lname, and use these as parameters when you call a server-side function called nameSearch):
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
This server-side function iterates through all rows with content in the spreadsheet, and returns the result for the first row whose columns K and L match the inputted data:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
This result is then passed as a parameter to a client-side function called onSuccess via a success handler. This is necessary since server-side functions called by google.script.run don't return anything directly, as specified here. Then onSuccess writes the result to the HTML:
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
Full code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
</body>
<script>
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
</script>
</html>
And the Code.gs would be like:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
function doGet(e) {
return HtmlService.createHtmlOutputFromFile("your-html-name");
}
I'm not sure you want to write the result to the HTML, but in any case, at this point it shouldn't be difficult to modify this so that it writes exactly what you want and where you want.
Reference:
google.script.run.myFunction(...) (any server-side function)
withSuccessHandler(function)
I hope this is of any help.
Try this:
Launch the dialog fill the text boxes and click submit. The view logs and see the next dialog.
function launchADialog() {
var html='<form><br /><input type="text" name="Name" /> Name: <br /><input type="text" name="Age" /> Age: <br />';
html+='<select name="Children" ><option value="0">None</option><option value="1">One</option><option value="2">Two</option></select> Children:<br />';
html+='<input type="button" value="Submit" onClick="google.script.run.processForm(this.parentNode);" /></form>';
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "The Form");
}
function processForm(form) {
Logger.log(JSON.stringify(form));
var s=Utilities.formatString('<br />Name: %s <br />Age:%s <br />Number Of Children: %s', form.Name, form.Age, form.Children);
s+='<br /><input type="button" value="Close" onClick="google.script.host.close();" />';
var userInterface=HtmlService.createHtmlOutput(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "Form Data")
}
struggling to understand why the append element doesn't work in my JS.
Here's the JavaScript file and the HTML file is below.
JS file.
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate(form){
var name = form.name.value;
var email = form.email.value;
var username = form.username.value;
var password = form.password.value;
var errors = [];
if (!ck_name.test(name)) {
errors[errors.length] = "You valid Name .";
}
if (!ck_email.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (!ck_username.test(username)) {
errors[errors.length] = "You valid UserName no special char .";
}
if (!ck_password.test(password)) {
errors[errors.length] = "You must enter a valid Password ";
}
if (errors.length > 0) {
errors.forEach(function(entry){
$('#errors').append("<li>" + entry +"</li>")
});
}
}
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="main.css">
</head>
<body>
<form name="form" action="#" onSubmit="validate(this)" method="post">
<input type="text" name="name" />
<input type="text" name="email" />
<input type="text" name="username" />
<input type="password" name="password" />
<ul id="errors"></ul>
</form><body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="form-validator.js"></script>
</body>
</html>
Any help would be greatly appreciated. The error messages appear for awhile before the form redirects to '#'.
I assume that if there are errors, you don't want the form to submit. You should then return false when there are errors.
Change these lines in the validate() function:
if (errors.length > 0) {
errors.forEach(function(entry){
$('#errors').append("<li>" + entry +"</li>")
});
return false;
}
return true;
And change this on the <form> element:
onSubmit="return validate(this);"
Try a separate validation button:
function validate() {
var valid = true;
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate(form) {
var name = form.name.value;
var email = form.email.value;
var username = form.username.value;
var password = form.password.value;
var errors = [];
if (!ck_name.test(name)) {
errors[errors.length] = "You invalid Name .";
valid = false;
}
if (!ck_email.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
valid = false;
}
if (!ck_username.test(username)) {
errors[errors.length] = "You valid UserName no special char .";
valid = false;
}
if (!ck_password.test(password)) {
errors[errors.length] = "You must enter a valid Password ";
valid = false;
}
if (errors.length > 0) {
errors.forEach(function(entry) {
$('#errors').append("<li>" + entry + "</li>")
});
}
if (valid) {
$('#realSubmit').click();
} else {
alert('Please fill out all fields!');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" action="#" onSubmit="validate(this)" method="post">
<input type="text" name="name" />
<input type="text" name="email" />
<input type="text" name="username" />
<input type="password" name="password" />
<ul id="errors"></ul>
<button type="button" onclick="validate()">Submit</button>
<button type="submit" id="realSubmit" style="display:none"></button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Hint. The page should NOT refresh. Your validations errors will stick if the page doesn't refresh. Instead of a submit button, use a regular button, bind a click event on it and handle the validation in there.
This is a common pitfall for beginning JS programmers, unless you do want the whole page to reload, don't make it reload via the regular form submit action.
Steps
Use a regular button for submission, like so...
<input type='button' id='submitMe' value='Submit' />
and in your jquery code, do something like so...
$(document).on('click', 'button#submitMe', function() {
// your validation code goes here...
...
return false; // do not make it bubble up the DOM
});
i am using the following form:
<form id="dataForm" method="post">
<h2 id="formheader"> Update Product Description</h2>
<div>
<label>Product Name:</label>
<input class="inputForm" id="orginalName" type="text" name="Name">
</div>
<div>
<label>New Description:</label>
<input class="inputForm" id="newDescription" type="text" name="newDescription">
</div>
<div id="theSubmit">
<button id="editDescription">Submit</button>
</div>
</form>
and using the following simple php, which when used with action=editProductDes.php works...
$Name = $_POST['Name'];
$Description = $_POST['newDescription'];
if($Name !="" && $Description !=""){
$sql = "UPDATE PRODUCTS SET P_Description = '$Description' WHERE P_NAME = '$Name'";
$conn->exec($sql);
and then when i use the following java script the data is not passed through and I cannot see why as I have a similar function and form where the JavaScript works fine, can anyone see why the data is not passing through?
function editDescription(){
xmlhttp = new XMLHttpRequest();
var name = document.getElementById("orginalName");
var Description = document.getElementById("newDescription");
var data_seen = false;
// this is a flag to record whether any data has been seen. Used in the guard ofthe alert statement.
if (name.value !="" && Description.value !="" ){
data_seen = true;
xmlhttp.open("POST","editDescription.PHP",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("Name=" + name.value + "&Description=" + Description.value);
}
if (!data_seen) {
alert("please enter some data");
}
}
submitButton = document.getElementById("editDescription");
submitButton.addEventListener("click", editDescription);
You are posting to editDescription.PHP instead of editProductDes.php
Change the following:
xmlhttp.open("POST","editProductDes.php",true);
You are also sending the data in your post under another name than you expect it to be in your PHP code (Description instead of newDescription) - change:
xmlhttp.send("Name=" + name.value + "&newDescription=" + Description.value);
I am trying to send a JavaScript variable to PHP but not exactly sure how to do it, a few things have said Ajax but I've never used it before and can't get my head around it. Does anyone know what the easiest way to do this would be? The column which I am attempting to populate in my DB is called 'cogs'.
I have the following JavaScript code:
<script>
$(document).ready(function() {
$('#duration-select').change(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#request').removeClass('hidden');
$('#duration-value').text('Total cost for this duration = ' + (y) + ' cogs');
if($(this).val() !== '') {
} else {
$('#duration-value').text('');
}
});
$('#request').click(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#total').text(y);
});
});
</script>
And the following HTML code:
<label id="total"></label>
Here is where I am trying to post the data, everything else is posting except for the $cost:
<form name="form" method="post">
<div class="modal-footer">
<?php
if ($row3['availability'] === 'Available') {
if (isset($_POST['request'])) {
$to_id = $row3['customerid'];
$from_id = $_SESSION['customerid'];
$time_sent = date('Y-m-d H:i:s');
$subject = 'Request for ' . $row3['title'];
$title = $row3['title'];
$listingid = $listingid;
$cost = $_POST['total']; //posting 0
$message = $customer_data['first_name'] . ' ' . $customer_data['last_name']
$request = mysql_query("INSERT INTO messages (to_id, from_id, listing_id, time_sent, subject, message, cogs, messagenumber, title, msgrand) VALUES ('$to_id', '$from_id', '$listingid', '$time_sent', '$subject', '$message', '$cost', '1', '$title', '$randomString')") or die(mysql_error());
}
}
?>
<input type="submit" class="btn btn-success" name="request" value="Yes" />
<input type="submit" class="btn btn-danger" data-dismiss="modal" value="No" />
</div>
</form>
Then I am trying to post the value of the label id=total to my db or the JavaScript variable (y). The problem is that 0 is always being sent to the DB when it should instead be the value that is in the label where the id is total.
Use name parameter for hidden variable and it will be automatically passed to PHP .
<label id="total"></label>
<input type="hidden" name="total" id="nameID"/>
in javascript below $('#total').text(y); write $('#nameID').val(y); . Everything will work properly.
You used total label , but $_POST recognizes only input type so use input type=.... instead of a label,divs etc.
IF YOU REAllY NEED ANSWER REPLY HERE
you have make an input type and its value is to be set by that javascript and then you'll be able to get that $cost value in php code
<input type="hidden" value="" name="total" id="total">
..................
$("#total").val(y);
You can use this to send the variables....
<input type="text" id="name" class="name" placevalue="Enter you name" required /><br><br>
<input type="text" id="email" class="email" placevalue="Enter you name" required /><br><br>
<button id= "det_submit" onclick="submit_det()"> Submit </button>
<script>
function submit_det() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(name != "" && email != "") {
$.post(
'xx.php',
{
name : document.getElementById("name").value,
email1 : document.getElementById("email").value,
},
function(data){
alert(data);
});
} else {
alert("empty");
}
}
</script>
here is xx.php
<?php
if(isset($_POST['name']) && isset($_POST['email1'])) {
$name = $_POST['name'];
$email = $_POST['email1'];
//code to insert into your database......
}
?>
Use a ID and Name for hidden parameter like this
<label id="total"></label
<input type="hidden" name="name" id="name"/>
and in jQuery edit the code like this
$('#total').text(y);
$('#nameID').val(y);
hope that it will work
I use a form to submit some data to an API. Further, I use a recaptcha to avoid bots.
My Problem:
If the user inputs a wrong sum, he gets an error alert. But after the error alert, the script always performs "action="www.test.de", so the user doesn´t get a chance to correct the input.
return false also doesn´t work.
Can someone point out the error?
The Script:
<script type="text/javascript">
var a = Math.ceil(Math.random() * 10);
var b = Math.ceil(Math.random() * 10);
var c = a + b
function DrawBotBoot() {
document.write("Was ergibt " + a + " + " + b + "? ");
document.write("<br/><input id='BotBootInput' type='text' maxlength='2' size='2'/><br/>");
}
function ValidBotBoot() {
var d = document.getElementById('BotBootInput').value;
if(d == c)
$('#test_form').submit(function(evt) {
evt.preventDefault();
var uvSubdomain = "test";
var uvKey = "xxxxxxxxxxxxxx";
var message = $('#message').val();
var subject = $('#subject').val();
var name = $('#name').val();
var email = $('#email').val();
$.jsonp({
url : 'https://' + uvSubdomain + '.test/tickets/create_via_jsonp.json?callback=?',
data : {
client : uvKey,
ticket : {
message : message,
subject : ("Anfrage via Landingpage test.de")
},
name : name,
email : email
},
success : function(data) {
alert('Herzlichen Dank für Ihre Mitteilung! Wir werden uns umgehend bei Ihnen melden.');
window.open('index.html', '_self', false)
},
error : function(d, msg) {
alert("Leider konnte die Mitteilung nicht übermittelt werden.");
}
});
return false;
});
else
alert('Falsches Ergebnis')
document.contact.BotBootInput.focus();
return false;
}
</script>
The HTML:
<div id="contact_form">
<form id="test_form" name="contact" method="post" action="https://www.test.de">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="" class="span3" />
<label for="email">E-Mail</label>
<input type="email" name="email" id="email" value="" class="span3" />
<label for="message">Mittteilung</label>
<textarea name="message" id="message"></textarea>
<div>
<script type="text/javascript">DrawBotBoot()</script>
<button class="btn btn-primary" onclick="ValidBotBoot()">
Senden
</button>
</div>
</form>
</div>
Try this:
else {
alert('Falsches Ergebnis')
document.contact.BotBootInput.focus();
return false;
}
When you want to simply discard the event:
1. return false and from called function and
2. use return keyword just before function name.
So, finally value of onclick attribute should be:
onclick="return ValidBotBoot()"