I'm trying to create a dynamic table with checkbox. The problem with my code now is that it only should insert the first data in year,code and age. Male and Female would be checkbox, but these two field seem unable to get the correct data, The checkbox should store 1 with it's check 0 if it's uncheck. Please let me know if you see the causes these error in my code, Thank You
POST PHP
if(isset($_POST['add'])){
$h = $_POST['h'];
if($h >= 0){
for($i=0; $i<=$h; $i++){
$year=intval($_GET['year']);
$code=intval($_GET['code']);
$age = $_POST['age'][$i];
$male = $_POST['male'][$i];
$female = $_POST['female'][$i];
$sql = "delete from remark_details WHERE year=:year";
$query = $dbh->prepare($sql);
$query -> bindParam(':year',$year, PDO::PARAM_STR);
$query -> execute();
$sql2 = "INSERT INTO remark_details (year,code,age,male,female) VALUES('year','code','$age','$male','$female')";
$query2 = $dbh -> prepare($sql2);
$query2->execute();
}
}
}
PHP
<?php
foreach($results as $result){?>
<tr data-row='0'>
<td colspan="2"><input class="tableBody" type="text" name="age[]" value="<?php echo $result->age; ?>" autocomplete="off" /></td>
<td colspan="2"><input class="tableBody" type="checkbox" name="male[]" value="1" autocomplete="off" /></td>
<td colspan="2"><input class="tableBody" type="checkbox" name="female[]" value="1" autocomplete="off"/></td>
<td>
<a href='javascript:void(0);' class='remove' style='cursor:pointer'>
<i class='material-icons' title='Delete item'>remove_circle_outline</i>
</a>
</td>
</tr>
<?php }} ?>
<input name='h' type='text' id='h' value=0 readonly hidden />
JavaScript
<script>
document.addEventListener('click', function(to) {
var rows={};
const getparent=(e,tag)=>{
let n=e.target;
while( n.tagName.toUpperCase()!=tag.toUpperCase() ){
if( n.nodeName==='BODY' )return false;
n=n.parentNode;
}
return n;
};
const datedifference=(d1,d2)=>{
return {
y:Math.abs( d2.getFullYear() - d1.getFullYear() ),
m:Math.abs( d2.getMonth() - d1.getMonth() +1 ),
d:( Math.abs( ( d2 - d1 ) / ( 1000 * 60 * 60 * 24 ) ) )
}
};
document.getElementById('tbl_history').addEventListener('change',function(e){
if( e.target!=e.currentTarget && e.target.nodeType==1 && e.target.tagName=='INPUT' && e.target.type=='month' ){
let parent=getparent(e,'tr');
let duration=parent.querySelector('input[type="text"][name="duration[]"]');
let row=parent.dataset.row;
if( !rows.hasOwnProperty( row ) )rows[ row ]={};
rows[ row ][ e.target.name ]=e.target.value;
if( Object.keys( rows[ row ] ).length==2 ){
let keys=Object.keys( rows[ row ] );
let d1=new Date( rows[ row ][ keys[0] ] );
let d2=new Date( rows[ row ][ keys[1] ] );
let obj=datedifference(d1,d2);
duration.value=[obj.y+' Years' , obj.m+' Months' ].join(' ');
}
}
});
document.getElementById('tbl_history').addEventListener('click',function(e){
if( e.target!=e.currentTarget && e.target.nodeType==1 && e.target.tagName=='I' ){
let p=getparent(e,'tr');
p.parentNode.removeChild(p);
}
});
});
var h=0;
function history() {
h++;
var html = `
<tr data-row='${h}'>
<td colspan="2"><input class="tableBody" type="text" name="age[]" autocomplete="off" required /></td>
<td colspan="2"><input class="tableBody" type="checkbox" name="male[]" value="1" autocomplete="off" /></td>
<td colspan="2"><input class="tableBody" type="checkbox" name="female[]" value="1" autocomplete="off"/></td>
<td>
<a href='javascript:void(0);' class='remove' style='cursor:pointer'>
<i class='material-icons' title='Delete item'>remove_circle_outline</i>
</a>
</td>
</tr>`;
document.getElementById('tbl_history').insertAdjacentHTML('beforeend',html);
document.getElementById('h').value=h;
}
</script>
It seems, you should make yourself familiar with the checked attribute of the input[type=checkbox] element. See here: input checked
So I use a function like this:
function checked(bool $value): string
{
return $value ? ' checked="checked"' : '';
}
And your code should look like this:
<input class="tableBody" type="checkbox" name="male[]" value="1" <?php echo checked($result->male) ?> />
<input class="tableBody" type="checkbox" name="female[]" value="1" <?php echo checked($result->female) ?> />
You can delete the autocomplete="off" attribute in checkboxes. It's not supported in checkboxes, so it is ignored by the browser anyway.
I also recommend to just use one DB field for gender.
If you really want to hide the "h" element, then instead of your code you could use the type="hidden" version:
<input name='h' type='hidden' id='h' value=0 />
Edit:
Ok, you told me in the comments that you still have issues when inserting data to the DB. And really, there are a lot of wierd things going on in your code.
First of all, (if it would work) you would in fact insert just one record with your loop, which would be the last one. The year doesn't change in your loop, because of:
$year = intval($_GET['year']);
maybe this one should be (?):
$year = intval($_GET['year'][$i]);
Then you try to delete the record for that year (or all records for that year, but I assume there should only be one, which you want to update). But you bind the WHERE condition with PDO::PARAM_STR. Is the "year" field really a string? You should use PDO::PARAM_INT instead or drop the whole bindParam line and just use:
$query->execute(['year' => $year]);
Next, if you are using MySQL you could drop the whole DELETE action and use REPLACE instead of INSERT. But this can only work, if your PRIMARY KEY is "year". The syntax is quite the same as in INSERT. Just replace the word INSERT with REPLACE in your query. The difference is, REPLACE deletes the existing record with the same PRIMARY KEY before it inserts the new one. INSERT would just do nothing or throw an error instead.
Last, your INSERT statement is also quite buggy. You do not parameterize your query like the DELETE statement, so you could throw away the prepare/execute stuff (which I urge you NOT TO DO!) and use just the query method. But this would put a wide open door for hacker attacks.
Next, you put in hard the strings 'year' and 'code' instead of the variables $year and $code. And you force the variables $age, $male and $female to be strings by putting them into single quotation marks. But the age sould be an integer, and I assume male and female as booleans.
I recommend using a parameterized statement and execute it with an array of parameters:
$sql2 = "INSERT INTO remark_details (year,code,age,male,female) VALUES(?,?,?,?,?)";
$query2 = $dbh->prepare($sql2);
$query2->execute([$year, $code, $age, $male, $female]);
In standard cases this works fine. PDO will sort out the appropriate datatypes for you.
And as final advice: Never trust any user input. You should do some validation/salvation stuff to your $_POST parameters. You will always hear this because it's really important.
Related
Im making a page that has a search function. I would like to be able to click the results in the table and have it insert the information into a form below it. For Example: a page for medical records where you would search by last name, it would populate the table with the customers info, and you can click one of the results in the table for it to fill in all the information into the form below the table.
I currently have the table pulling the results and entering the data into the form but i have to click a button before it will allow me to select anything in the table. I really dont want to have to press the button. Below is the Javascript code, and php. If you need more, I can provide it.
Javascript: I have think what requires the button to be pressed is the var row = td.parentNode line, because when its just taken away, the selecting functionality ceases.
tbody.onclick = function (e) {
e = e || window.event;
var td = e.target || e.srcElement
var row = td.parentNode;
if (ishigh && ishigh != row) {
ishigh.className = '';
}
row.className = row.className === "highlighted" ? "" : "highlighted";
ishigh = row;
populateFields(row);
}
PHP
echo '<input id="selectstyle" type="button" value="Select" onclick="test()"><br><table class="table-search" id="searchresulttable"><br>';
if(count($row)) {
$end_result = '';
echo "<tr><td><u>Last Name</u></td><td><u>First Name</u></td><td><u>Phone #</u></td><td><u>Address</u></td><td><u>License</u></td><td><u>Tax Exempt</u></td><td><u>Tax ID</u></td></tr>";
foreach($row as $r) {
$result = ucwords($r['bidlname']);
// we will use this to bold the search word in result
$bold = '<td>' . ucwords($r['bidlname']) . '</td>' . '<td>' . ucwords($r['bidfname']) . '</td><td>' . $r['bidphnum'] . '</td><td>' . $r['bidaddress'] . '</td><td>' . $r['bidlicense'] . '</td><td>' . $r['bidtaxexempt'] . '</td><td>' . $r['bidtaxid'] .'</td>';
$end_result .= '<tr>' . $bold . '</tr>';
}
echo $end_result;
} else {
echo '<li>No results found</li>';
}
echo '</table><br>';
I would like to be able to just click the entry i want to insert, without having to click the button first. Thoughts or ideas?
If I understood correctly your question my answer is the following snippet:
var ishigh;
function populateFields(row) {
// get the form elements
var frmElements = document.getElementById('frm');
// for each cell in current row
for(var i=0; i< row.cells.length; i++) {
// copy the cell value to the input value
frmElements[i].value = row.cells[i].textContent;
}
}
// when document is ready
window.addEventListener("DOMContentLoaded", function(event) {
// associate the click handler for the table
document.getElementById('searchresulttable').onclick = function (e) {
e = e || window.event;
var td = e.target || e.srcElement;
var row = td.parentNode;
if (ishigh && ishigh != row) {
ishigh.className = '';
}
row.className = row.className === "highlighted" ? "" : "highlighted";
ishigh = row;
// populate the form with the content of current row
populateFields(row);
}
});
function test() {
// do nothing.....
}
.highlighted {
background-color: #ffff99;
}
<input id="selectstyle" type="button" value="Select" onclick="test()"><br>
<table class="table-search" id="searchresulttable"><br>
<tr>
<td><u>Last Name</u></td>
<td><u>First Name</u></td>
<td><u>Phone #</u></td>
<td><u>Address</u></td>
<td><u>License</u></td>
<td><u>Tax Exempt</u></td>
<td><u>Tax ID</u></td>
</tr>
<tr>
<td>1bidlname</td>
<td>1bidfname</td>
<td>1bidphnum</td>
<td>1bidaddress</td>
<td>1bidlicense</td>
<td>1bidtaxexempt</td>
<td>1bidtaxid</td>
</tr>
<tr>
<td>2bidlname</td>
<td>2bidfname</td>
<td>2bidphnum</td>
<td>2bidaddress</td>
<td>2bidlicense</td>
<td>2bidtaxexempt</td>
<td>2bidtaxid</td>
</tr>
<tr>
<td>3bidlname</td>
<td>3bidfname</td>
<td>3bidphnum</td>
<td>3bidaddress</td>
<td>3bidlicense</td>
<td>3bidtaxexempt</td>
<td>3bidtaxid</td>
</tr>
</table>
<br>
<form id="frm">
Last Name:<br>
<input type="text" name="lastname"><br>
First Name:<br>
<input type="text" name="firstname"><br>
Phone #:<br>
<input type="text" name="phonenumber"><br>
Address:<br>
<input type="text" name="address"><br>
License:<br>
<input type="text" name="license"><br>
Tax Exempt:<br>
<input type="text" name="taxexempt"><br>
Tax Id:<br>
<input type="text" name="taxid"><br>
</form>
I haven't 50 rep yet so I'll have to sort of hack my approach here...
Are you using regular js or are you running a library like jQuery or underscore?
Is this specifically for touch-enabled devices or not (its okay to have both but this info would help)
My recommendation is that you use any JS library that can do batch click assignment here.
Maybe add a button to the row to trigger the action or even adjust your PHP to add properties to an and in JS preventDefault on the event then take the data from off it.
something like...
<a class="click_here_for_population" data-fisrt-name="FirstName" data-last-name="LastName" data-anything-else="foo">Add to form</a>
then...
$('click_here_for_population').click(function(e){
e.preventDefault();
// do the population stuff from $(this) or pass $(this) to the function
})
This way the event target holds the data you need without having to navigate parents/siblings.
Well, I have a form where the user can select an item with a checkbox, the user type how many items he wants to send with an input text, but there are some items that requires a serial number that a checkbox holds.
This is my approach:
<script>
function checkall()
{
var ok=true;
$('input:checkbox[id^="art"]:checked').each(function() {
var vals = $(this).val();
//first attempt
if (typeof document.getElementById(vals+"existencia") === 'undefined') {
ok=false;
return false;
alert("Error message");
}else
if (typeof document.getElementById(vals+"-serie")==='undefined') {
ok=false
return false;
alert("Error message 2");
}
//second attempt
if (obj.hasOwnProperty(vals+'existencia')) {
art = document.getElementById(vals+"existencia").value;
alert(art);
}else if (obj.hasOwnProperty(vals+'serial')) {
sert=document.getElementById(vals+"-serie").value;
alert(sert);
}
});
if(ok)
{
document.getElementById("myform").submit();
}
}
</script>
The script is intended to loop all checked checkboxes and if the input is empty stops and alerts the user and the other stage is when he checks an article with serial number, at least 1 have to checked and also alerts the client
The first attempt, I tried, got passed cause those elements are defined and second attempt throws obj is not defined, maybe I missunderstood the codes and answers I searched, can someone help to achieve my goal or explain me what I did wrong, thank you.
UPDATE:
if ($inicio == 0) {
echo "<tr bgcolor= '#f4f4f4' >";
$inicio = 1;
} else {
echo "<tr bgcolor= white>";
$inicio = 0;
}
?>
<td style="width: 10%;text-align: center;">
<input type="checkbox" name="art[]" id="art" value="<?php echo $articulo; ?>" /></td>
<td width="12%" align="center"><?php echo $diferencia_dias ?> días</td>
<td width="8%" style="text-align: center;"><?php echo $articulo; ?></td>
<td width="45%"><?php echo $descripcion; ?></td>
<?php
if($numserie>0){
$esto = trim($articulo);
$bus_serie = mssql_query("execute serial_madness '$esto','$almacen'");
echo "<td style='width:10%;text-align:left;'>";
while($res_serie = mssql_fetch_array($bus_serie))
{
echo '<input type="checkbox" id="'.$articulo.'-serie" name="'.$articulo.'-Serie[]" value="'.$res_serie["ARTICULO"].','.$res_serie["NUMSERIE"].'_'.$valor.' "> '.$res_serie["NUMSERIE"].' <br>';
}
echo "</td>";
}else{
?><td style="width:10%;text-align:center;"><input type="number" style="text-align:center;width:30px; height:30px;" id="<?php echo $articulo_c; ?>existencia" name="<?php echo
$articulo_c; ?>existencia" value="<?php echo (int)$existencias; ?>" min="1" max="<?php echo (int)$existencias; ?>"/></td>
<?php
} ?>
So, in order to check a checkbox you can just use jquery.
Example: $("#checkboxId").prop('checked', true);
The example above will check the checkbox with id "checkboxId", changing the true to false will uncheck the box;
If you want to check how many or which inputs are checked you can use the .length of the array returned by the jquery selector.
The following will check if all the checkboxes with ids starting with the word "test" are checked:
if($('[id^="test"]:checkbox').length == $('[id^="test"]:checkbox:checked').length)
{
// Do stuff here
}
Likewise you can check if nothing is checked if the length is equal to zero.
I prepared a simple example that I think tackles the general issue you are solving here.
https://plnkr.co/edit/2v6x1DXRpAiaKiBFSMz6?p=preview
Notice that when you click 'Submit' in my plunker example all checkboxes will automatically become checked.
If you click the 'Validate' button it will verify that all checkboxes are indeed checked.
You should be able to use my example to create a solution for your specific case.
You may also want to use the .is() jquery function
example:
$('#' + id).is(":checked")
See the following answer for some similar solutions and explanations: Check if checkbox is checked with jQuery
I dynamically add a text box whenever a user clicks a button to add more, which works fine. However, in PHP when I get the submitted field values by $_POST['skills'] , I only receive the first text box value, not the dynamically added ones. I'm almost positive there is something wrong with the way I am adding the text boxes in javascript.
I use the following method to add a text box field:
function addTextBoxField()
{
var input = document.createElement('input');
input.type = "text";
input.name = "skills[]";
input.size = "30";
var container = document.getElementById("skillfield");
container.appendChild(input);
}
The HTML code I have for the text box is :
...
<td>
<div id="skillfield">
<input type="text" size="30" name="skills[]" />
</div>
</td>
<td><div class="button">+ Add</div></td>
Here is the php code as well:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$allskills = $_POST['skills'];
$size = count($_POST['skills']);
print_r($allskills);
}
The output is the following, even though I inputted three values
Array ( [0] => java )
Your field name is skills not skill .So it should be $_POST['skills'].$_POST['skills'] is an array in this case. So access try with var_dump($_POST['skills']); and you will see all the values.
As far as the $_POST['skills'] is an array, Try this..
$skill = $_POST['skills'];
foreach($skill as $value){
echo $value;
}
do you mean the values of $_POST['skills']
i dont think there is something wrong with your javascript, what is wrong is how you read the post data in your php. The post data will be an array in this case, so you access it like this $_POST['skills'][0] //value of 1st input $_POST['skills'][1] //value of 2nd input
$_POST['skills'] is an array,So use print_r() to view the array.You may use as follows
<script type="text/javascript">
function addTextBoxField()
{
var input = document.createElement('input');
input.type = "text";
input.name = "skills[]";
input.size = "30";
var container = document.getElementById("skillfield");
container.appendChild(input);
}
</script>
<form method ="post">
<td>
<div id="skillfield">
<input type="text" size="30" name="skills[]" />
</div>
</td>
<td>
<input type="submit" name="submit" value="Submit"/>
</td>
</form>
<td><div class="button">+ Add</div></td>
<?php
if(isset($_POST['submit']) && $_POST['submit'] == 'Submit'){
echo "<pre>";
print_r($_POST['skills']);
echo "</pre>";
}
?>
you could use the array length. Try to this
for($i=0;$i<=count($skills)-1;$i++)
{
$per=$skills[$i]*$skills[$i];
echo $per;
}
I'm Trying to change the values in the database using PHP and MySQL.
I am getting the values from database and storing them in placeholder for each input but when i submit the form again it submit the inputs with empty values, i tried storing them in Value attribute for each input again the old value is overwriting what i write in the input field so nothing in the database change.
How can i keep the old value in the input fields but in case the content of these fields changed the new value is passed back to the database instead of the old one.
Here is my Code :
function list_products () {
$get = mysql_query('SELECT `id`, `SKU`, `sub`, `pname`, `desc`, `price`, `ship`, `qty`, `cat` FROM `products` ORDER BY `id` DESC');
if (mysql_num_rows($get) == 0) {
echo "There are no product to display!";
} else {
while ($get_row = mysql_fetch_assoc($get)) {
echo
'<h5>'.$get_row['pname'].' id: '.$get_row['id'].'</h5>
<form action="delete_product.php" method="post">
<input type="hidden" value="'.$get_row['id'].'" name="id">
<input type="submit" name="submit" value="DELETE" class="btn btn-lg btn-danger">
</form>
<form action="update_p.php" method="post">
<input type="hidden" placeholder="'.$get_row['id'].'" name="id" value="'.$get_row['id'].'">
<label>SKU:</label>
<input type="text" placeholder="'.$get_row['SKU'].'" name="SKU" value="'.$get_row['SKU'].'" required="">
<label>Name:</label>
<input type="text" placeholder="'.$get_row['pname'].'" name="pname" required="" value="'.$get_row['pname'].'">
<label>Subtitle:</label>
<textarea rows="2" maxlength="46" name="desc" placeholder="'.$get_row['sub'].'" required="">'.$get_row['sub'].'</textarea>
<label>Description:</label>
<textarea rows="4" name="desc" placeholder="'.$get_row['desc'].'" required="">'.$get_row['desc'].'</textarea>
<label>Price:</label>
<input type="text" placeholder="'.number_format($get_row['price'], 2).'" name="price" value="'.number_format($get_row['price'], 2).'" required="">
<label>Shipping:</label>
<input type="text" placeholder="'.number_format($get_row['ship'], 2).'" name="ship" value="'.number_format($get_row['ship'], 2).'" required="">
<label>Quantity:</label>
<input type="text" placeholder="'.$get_row['qty'].'" name="qty" value="'.$get_row['qty'].'" required="">
<label>Category:</label>
<input type="text" placeholder="'.$get_row['cat'].'" name="cat" value="'.$get_row['cat'].'" required=""><br>
<input type="submit" name="submit" value="EDIT" class="btn btn-success btn-lg">
</form>
<hr>
';
};
}
}
The update_p.php page:
if (empty($_POST) === false && empty($errors) === true) {
$id = $_POST['id'];
$update_data = array(
'pname' => $_POST['pname'],
'desc' => $_POST['desc'],
'price' => $_POST['price'],
'ship' => $_POST['ship'],
'qty' => $_POST['qty'],
'cat' => $_POST['cat']
);
update_product($id, $update_data);
The update_data function :
function update_product($id, $update_data) {
$update = array();
array_walk($update_data);
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("UPDATE `products` SET " . implode(', ', $update) . " WHERE `id` = $id");
}
#MaveRick Thanks for the effort, but my question is how to overwrite the value of the input fields on the page before we send the information to the server, i think its can be done using JavaScript more than php, however to make more clear these input fields refers to values in the database already stored and i would like to give the option for the user to change them in his admin panel by retrieving the content of these fields from the database and print them in the actual input fields so in case the customer pressed edit(submit) with out touching anything the same values will be sent again to the database this way nothing will be change, and in another case where the customer added or changed any value in any of these fields then the new value will be passed. hopefully i clarified my issue now. Thanks for your help anyway.
#Prafful Garg i already tried the value field but it didn't work thanks for your help anyway
You can retrieve the data again from the database in file update_p.php as follow:
if (empty($_POST) === false && empty($errors) === true) {
$id = $_POST['id'];
$get = mysql_query("SELECT * FROM `products` WHERE `id` = '$id';");
$get_row = mysql_fetch_assoc($get);
$update_data = array(
'pname' => (empty($_POST['pname'])?$get_row['pname']:$_POST['pname']),
'desc' => (empty($_POST['desc'])?$get_row['desc']:$_POST['desc']),
'price' => (empty($_POST['price'])?$get_row['price']:$_POST['price']),
'ship' => (empty($_POST['ship'])?$get_row['ship']:$_POST['ship']),
'qty' => (empty($_POST['qty'])?$get_row['qty']:$_POST['qty']),
'cat' => (empty($_POST['cat'])?$get_row['cat']:$_POST['cat'])
);
update_product($id, $update_data);
But this is not a professional way to do it.
What you can do is a loop to create the update statement and test each input; if not empty then add to the update statement , name=value otherwise to skip this input and process the next one in the array POST. something similar to the following:
function update_product($id, $update_data) {
$update = array();
array_walk($update_data);
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
$query = "UPDATE `products` SET `id` = '$id'";
foreach($update_data AS $k=>$v){
if(!empty($v) && strlen($v)>0)
$query .= ", `".$k."` = '".$v."'";
}
$query .= " WHERE `id` = '$id';";
mysql_query($query);
}
IMPORTANT NOTE: mysql() is vulnerable and deprecated, please try to avoid using mysql() and use mysqli() or dbo() extensions instead.
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 >.>