I am having difficulties to implement JavaScript into my html form.
I am using alot of PHP throughout. The code I am about to post, is included in a seperate page the user accesses. It is a php page.
The form currently does not include action=, which would submit it to formposts.php. I took it out to see if my JavaScript just got ignored and the form was sent before checkign JavaScript. But even without action, my form does not respond to the JavaScript.
I have used simple forms of JS, just to check if it works, before getting down to details. I really need some help pls on how to make this work, I dont know where the problem is !!
I have included the script call when opening the form, and when closing. onsubmit // onclick I have also tried including a label to show text. The JS is at the end off the code. You can ignore some of the text / script. I guess the opening of the form, first three input types, the closing of the form and JS is included. I have taken some out, as it is a long form.
<p><?php echo $session->getText("profileInfo",$language); ?></p>
<table width="530" border="0">
<tr>
<th scope="col" width="40%"><form enctype="multipart/form-data" method="POST" onsubmit="return checkForm()" name="registration">
<img src="<?php echo $userDetails['picUrl']; ?>" border="none"> ;</th>
<th scope="col" width="60%"><h3><?php echo $session->getText("profileMenuPersonal",$language); ?></h3></th>
</tr>
<tr>
<td><h4><?php echo $session->getText("regPic",$language); ?></h4></td>
<td><input type="file" name="uploaded" id="uploaded" onblur="checkType()" /> <label id="picMSG"></label> </td>
</tr>
<tr>
<td><h4><?php echo $session->getText("regFname",$language); ?></h4></td>
<td><input type="text" id="firstName" name="firstName" value="<?php echo $userDetails['firstName']; ?>" /></td>
</tr>
<tr>
<td><h4><?php echo $session->getText("regLname",$language); ?></h4></td>
<td><input type="text" id="lastName" name="lastName" value="<?php echo $userDetails['lastName']; ?>" /></td>
</tr>
<tr> <!-- I have taken some code out for readability of this post -->
<td><input type="hidden" id="reqtype" name="reqtype" value="personalDetails" />
<input type="hidden" id="realUserId" name="realUserId" value="<?php echo $realUserId; ?>" /></td>
<td><input type="submit" name="submit" value="update / save" class="button" onclick="return checkForm()" />
</form>
</td>
</tr>
</table>
<script type="text/javascript">
function checkForm()
{
var picture = document.getElementById('uploaded').value;
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var email = document.getElementById('email').value;
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
var postCode = document.getElementById('postCode').value;
var email = document.getElementById('email').value;
// files types that r not allowed
// And are considered harming -
// someone purposfully trying to harm the system
var str1 = ".php";
var str2 = ".js";
var str3 = ".html";
if(!document.registration.firstName.value)
{
alert('please enter name');
return false;
}
if(picture.indexOf(str1) != -1 || picture.indexOf(str2) != -1 || picture.indexOf(str3) != -1)
{
alert("You have tried to upload content that may harm our system. The admin has been contacted and your account flagged. You may be deleted.");
return false;
}
// allowed file types
var str1 = ".jpeg";
var str2 = ".gif";
var str3 = ".png";
if(picture.indexOf(str1) != -1 || picture.indexOf(str1) != -1 || picture.indexOf(str1) != -1 )
{
return true;
}else{
alert("We only allow jpeg, gif and png files to be uploaded.");
return false;
}
}
function checkType()
{
var picture = document.getElementById('uploaded').value;
var element = document.getElementById('picMSG').value
// files types that r not allowed
// And are considered harming -
// someone purposfully trying to harm the system
var str1 = ".php";
var str2 = ".js";
var str3 = ".html";
if(picture.indexOf(str1) != -1 || picture.indexOf(str2) != -1 || picture.indexOf(str3) != -1)
{
element.innerHTML = "invalid type";
element.style.color = "red";
}
// allowed file types
var str1 = ".jpeg";
var str2 = ".gif";
var str3 = ".png";
if(picture.indexOf(str1) != -1 || picture.indexOf(str1) != -1 || picture.indexOf(str1) != -1 )
{
return true;
}else{
}
}
</script>
Does anyone have an idea why my "simple" JS is being ignored ??
I am new to PHP and JS. but wiould have thought this was a simple task. What am I doing worng ?
this is my wild guess... after i stripped your code to bits... http://jsfiddle.net/VVYR3/15/
change your submit button to:
onclick="checkForm()" instead of onsubmit="return checkForm()" (you can experiment further once you get this bit working)
and most importantly your script shouldn't be AFTER your form, instead place it in <HEAD>
It's kind of hard to debug it for you since you removed part of the code but I tried anyway and checkForm was called on submit allright. It fails on
var email = document.getElementById('email').value;
since there is no element with the id of "email" on which to find a value.
Your validation is somewhat sloppy though, what about a file called jpg.exe. It would pass as the code is now.
Have you considered not reinventing the wheel and use a tested framework instead? There are plenty of them out there, and they even have nice fancy ajax functionality. Like this: http://valums.com/ajax-upload/
i assume that you have to do this
<input type="submit" name="submit" value="update / save" class="button" onclick="checkForm()" />
instead of
<input type="submit" name="submit" value="update / save" class="button" onclick="return checkForm()" />
try changing
if(!document.registration.firstName.value)
into
if(firstName == "")
and(every)
picture.indexOf(str1) != -1
into
picture.search(str1) == -1
and check whether it works or not >.>
Related
I have a form on a simple page.
When submitting it passes data of the "first name, last name, email" to the "real" join form of my customer and enables the user to continue to fill in the form with the data.
When my customer is running it on some android mobile phones he get this error:
This page cannot be loaded using Chrome Data Saver. Try reloading the
page.
Debug info: POST CISmtuKa5MwCFUIEYgodMxIGmQ==
On every mobile phone I tested it - it works fine.
The customer tested it on 2 different mobile phones and he (only) got these errors. This doesn't happen on desktops as far as I tested it.
I tested it on some different browsers on my android too and it works fine.
This is the form I have:
<form id="preregistrationForm" action="" onsubmit="return get_action();" method="post">
<div>
<input type="text" name="FirstName" id="FirstName" placeholder="First Name">
</div>
<div>
<input type="text" name="LastName" id="LastName" placeholder="Last Name">
</div>
<div>
<input type="text" name="EMail" maxlength="50" id="EMail" placeholder="Email">
</div>
<input type="hidden" id="maleGengler" class="genderRadio" name="Gendler" value="M" checked="">
<input type="hidden" id="femaleGengler" class="genderRadio" name="Gendler" value="F">
<select name="birthDateMonth" id="birthDateMonth" style="display: none;">
</select>
<select name="birthDateDay" id="birthDateDay" style="display: none;">
</select>
<select name="birthDateYear" id="birthDateYear" style="display: none;">
</select>
<input type="hidden" name="btag" id="btag" value="">
<input type="hidden" name="affid" id="affid" value="">
<button class="join-sub" onclick="chgAction()"></button>
</form>
And this is the JS code. The last function chgAction() is the one that needs to be interesting. I just pasted all the code, just incase =] :
var Adp = {
getBtag: function() {
// split url and retrieve btag
var aPath = window.location.href.split("?");
var sbtag = aPath[aPath.length - 1];
return sbtag;
},
persistAffiliateData: function() {
// get the affiliate data from the url
var bTag = Adp.getBtag();
if (!bTag) { return false; }
// get all the links on the page
var aLinks = document.getElementsByTagName("a");
if (!aLinks) { return false; }
// add the affiliate data to the links to exampleurl
for (var i = 0; i < aLinks.length; i++) {
if (aLinks[i].href.indexOf("exampleurl") > 0 || aLinks[i].href.indexOf("localhost") > 0) {
aLinks[i].href = aLinks[i].href + "?&" + bTag;
}
}
}
};
function addLoadEvent(func){
// appends unlimited functions to the onload event
var oldonload = window.onload;
if(typeof window.onload != 'function'){
window.onload = func;
}else{
window.onload = function(){
oldonload();
func();
}
}
}
addLoadEvent(Adp.persistAffiliateData);
/*Function used of the pre-signup form of the sites*/
function getQueryStringByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function chgAction()
{
var btag = getQueryStringByName("btag");
var affid = getQueryStringByName("affid");
var isIncomeAccess = "false";
if (btag !="" && affid != "")
{
isIncomeAccess = "true";
$("#btag")[0].value=btag;
$("#affid")[0].value=affid;
}
var feObj=$("#femaleGengler")[0];
if (feObj.checked){
Gendler="F";
}else
{Gendler="M";}
var _action = "//www.exampleurl.com/preregistration?Gendler="+Gendler+"&FirstName="+$("#FirstName")[0].value+"&LastName="+$("#LastName")[0].value+"&EMail="+$("#EMail")[0].value+"&birthDateMonth="+$("#birthDateMonth")[0].value+"&birthDateDay="+$("#birthDateDay")[0].value+"&birthDateYear="+$("#birthDateYear")[0].value;
if(isIncomeAccess=="true")
_action += "&btag="+btag+"&affid="+affid;
document.getElementById("preregistrationForm").action = _action;
document.getElementById("preregistrationForm").submit();
document.getElementById("preregistrationForm").action = _action;
}
I'm the tech lead on the Chrome Data Saver team. This will occur if the user has the Data Saver feature enabled in Chrome (either desktop or mobile) and our proxy can't talk to the backend server that you are doing the POST to. Is this because the server is behind an intranet?
The short-term workaround is to ask people to turn off Data Saver, but that is not ideal -- we should be able to avoid this being a problem for you in the first place. Any details you can provide on the site would be helpful. If you prefer to email directly I am mdw at mdw dot la. Thanks.
I have a scenario where I am only allowed to upload specific file types, e.g. PDF.
I don't want to validate the type at form submit time. I need to verify the type is OK before selecting the file. Keep in mind the accept attribute is not supported in HTML5.
I have two options in mind.
Only acceptable file types should be available choices.
If possible, trigger a Javascript function after selecting a file. Opposite of onclick.
This is how I tried to validate on submit:
<form name="fileupload" onsubmit="return file_upload();">
<table align="center" bgcolor="#8080FF" height="100">
<tr>
<th> Fileupload:</th>
<td> <input type="file" name="word" id="word" > </td>
</tr>
<tr>
<td> <input type="submit" /> </td>
</tr>
</table>
</form>
<script type="text/javascript">
function file_upload()
{
var imgpath = document.getElementById('word').value;
if (imgpath == "") {
alert("upload your word file");
document.file.word.focus();
return false;
}
else {
// code to get File Extension..
var arr1 = new Array;
arr1 = imgpath.split("\\");
var len = arr1.length;
var img1 = arr1[len - 1];
var filext = img1.substring(img1.lastIndexOf(".") + 1);
// Checking Extension
if (filext == "doc" || filext == "docx") {
alert("File has been upload correctly")
return true;
}
else {
alert("Invalid File Format Selected");
document.form.word.focus();
return false;
}
}
}
</script>
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 am trying to validate a form with java script .. yet the javascript does not output anything and the form completes into processing.
here is the script tag:
here is the form tag:
<FORM id="frm" name="newCustomer" METHOD="POST" ACTION="register.php" onsubmit="return validateNewCustomer()">
i've created this label so that java script can write the warnings:
<TH WIDTH="30%" NOWRAP> <Label>First Name</Label></TH>
<TD WIDTH="70%"><INPUT TYPE="TEXT" NAME="f_name"
SIZE="8" MAXLENGTH="8">
<label class ="err" id="errname"></label>
Here is the valdiation function :
function validateNewCustomer(){
var name = document.getElementById('f_name').value;
var okCustomer = true;
if(name == ""){
document.getElementById('errname').innerHTML = "Error Name";
okCustomer = okCustomer && false;
}
return okCustomer;
}
I should note that i tried to make the function return false , but it still didn't stop php processing.
I appreciate your help.
Thank you.
var name = document.getElementByName('f_name').value;
and
okCustomer = false; instead of okCustomer = okCustomer && false;
Your code is wrong use
var name = document.getElementsByName('f_name').value;
instead of
var name = document.getElementsById('f_name')[0].value;
Use
if(name.value == ""){
instead of
if(name == ""){