save file names in database after uploading files - php

I save picture files on a server.
I want to use this file names to save them in a existing database.
The database name is "sob" and the table is "items". The field name is "PicturesFilenames". It is a medium text field. I would like to save there all file names of the just some seconds before uploaded files, separated with a #.
I stack and have no idea how to do that.
Some code would be fantastic. I tried many ways and had no success.
File: "upload_bodyarticles.php"
<?php session_start();
$_db_host = "xxx.xxx.com:3306";
$_db_username = "admin0";
$_db_passwort = "xxx0";
$_db_datenbank = "sob";
$_db_currentID ="";
# Verbindung zur Datenbank herstellen
$_link = mysql_connect($_db_host, $_db_username, $_db_passwort);
# Pr�fen ob die Verbindung geklappt hat
if (!$_link)
{
# Nein, also das ganze Skript abbrechen !
die("Keine Verbindung zur Datenbank m�glich: " .
mysql_error());
}
# Datenbank ausw�hlen
mysql_select_db($_db_datenbank, $_link);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<title>SoB - Administration</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/scroll.js"></script>
<script type="text/javascript" src="js/producttemplate.js"></script>
<script type="text/javascript" src="js/jquery.js" ></script>
<script type="text/javascript" src="js/jquery.uploadfile.min.js"></script>
<script type="text/javascript">
$(function()
{
$(document).on('click', 'a.ajaxify', function (e) {
e.preventDefault(); // prevent normal link navigation
var $this = $(this),
url = $this.attr('href');
$('#main-content').empty();
$("#main-content").load(url);
return false;
});
}
);
</script>
<style type="text/css">.buttonarea: (\a)</style>
<script type="text/javascript">
<!--
var js_string;
document.getElementById("recordWrite").disabled = true;
var ArrivalDateShownYN = "";
var CurrentPreviousNext = "";
var date = new Date();
var mysqlDateTime;
var yyyy = date.getFullYear();
var mm = date.getMonth() + 1;
var dd = date.getDate();
var hh = date.getHours();
var min = date.getMinutes();
var ss = date.getSeconds();
mysqlDateTime = yyyy + '-' + mm + '-' + dd + ' ' + hh + ':' + min + ':' + ss;
var frm = $('#form_articles');
frm.submit(function (ev) {
alert(form_articles.ID.value);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
elem = document.getElementById('buttonID');
function stop(e) {
e.preventDefault(); // browser - don't act!
e.stopPropagation(); // bubbling - stop
return false; // added for completeness
}
elem.addEventListener('click', stop, false);
// this handler will work
elem.addEventListener('click', function() { alert('I still work') }, false);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function jsRecordUpdateWrite()
{
var strTimestring = new Date().toISOString().slice(0, 19).replace('T', ' ');
var jsObject = {
"ID": document.form_articles.ID.value,
"Item": document.form_articles.Item.value,
"ItemNo": document.form_articles.ItemNo.value,
"Material": document.form_articles.Material.value,
"Age": document.form_articles.Age.value,
"ItemSize": document.form_articles.ItemSize.value,
"Price": document.form_articles.Price.value,
"Info": document.form_articles.Info.value,
"InfoRed": document.form_articles.InfoRed.value,
"ArrivalDate": document.form_articles.ArrivalDate.value,
"ArrivalDateShown": document.form_articles.ArrivalDateShown.value,
"MainPicLink": document.form_articles.MainPicLink.value,
"ItemCondition": document.form_articles.ItemCondition.value,
"ItemTimestamp": strTimestring,
"ItemCategory": document.form_articles.ItemCategory.value
};
$.ajax({
url : 'updatearticle.php',
dataType : 'json',
contentType: 'application/x-www-form-urlencoded',
data : jsObject,
type : 'POST'
});
}
function jsRecordCurrent() {
// ... the AJAX request is successful
var updatePage = function (response) {
json_string = JSON.stringify(response);
jsBlankArticle();
jsShowArticle();
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("reading record failed");
};
// Create an object to describe the AJAX request
var ajaxOptions = {
url: 'currentarticle.php',
dataType: 'json',
success: updatePage,
error: printError
};
// Initiate the request!
$.ajax(ajaxOptions);
}
function jsShowArticle() {
js_articles = JSON.parse(json_string);
$('[name="recordNext"]').attr("id",js_articles[0]);
$('[name="recordCurrent"]').attr("id",js_articles[0]);
$('[name="recordPrevious"]').attr("id",js_articles[0]);
document.form_articles.ID.value = js_articles[0];
document.form_articles.Item.value = js_articles[1];
document.form_articles.ItemNo.value = js_articles[2];
document.form_articles.Material.value = js_articles[3];
document.form_articles.Age.value = js_articles[4];
document.form_articles.ItemSize.value = js_articles[5];
document.form_articles.Price.value = js_articles[6];
document.form_articles.Info.value = js_articles[7];
document.form_articles.InfoRed.value = js_articles[8];
document.form_articles.ArrivalDate.value = js_articles[9];
if (js_articles[10] = "Y") {
document.form_articles.ArrivalDateShown.checked = true;
}
else {
document.form_articles.ArrivalDateShown.checked = false;
}
document.form_articles.MainPicLink.value = js_articles[11];
document.form_articles.ItemCondition.value = js_articles[12];
document.form_articles.ItemCategory.value = js_articles[14];
var message_text = "Article Database Item-ID = ";
var message_array = js_articles[0];
$("#formheadline").html("<h2>" + message_text + message_array + "</h2>");
$("#hiddenID").html(message_array);
}
// -->
</SCRIPT>
</head>
<body class="page page-id-11505 page-template-default" onload="jsRecordCurrent();">
<div id="page-wrap">
<?php
include('includes/header.html');
?>
<div id="hiddenID" style="display: none;"></div>
<div id="container-main">
<div id="main-content">
<div class="post" id="post-11505">
<title>SoB - Administration</title>
<div class="entry">
<form class="formarticles" id="form_articles" method="post" action="<?= $_SERVER['PHP_SELF'] ?>" name="form_articles">
<table border="0" cellpadding="0" cellspacing="5">
<tr>
<td align="right" width="120">
</td>
<td align="left">
<span id="formheadline"></span><span id="recordID"></span>
</td>
</tr>
<tr>
<td align="right">
</td>
<td align="left">
<span style="padding-right:20px"><font color="orangered" size="+1"><tt><b>*</b></tt></font>indicates a required field</span>
</td>
</tr>
<br>
<tr>
<td align="right">
<span style="padding-right:20px">Item</span>
</td>
<td>
<input id="id" name="ID" type="hidden" name="ID">
<input id="Item" name="Item" type="text" maxlength="100" size="25"/>
<font color="orangered" size="+1"><tt><b>*</b></tt></font>
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Item Category</span>
</td>
<td>
<input name="ItemCategory" type="text" maxlength="100" size="25" />
<font color="orangered" size="+1"><tt><b>*</b></tt></font>
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Item No.</span>
</td>
<td>
<input name="ItemNo" type="text" maxlength="100" size="25" />
<font color="orangered" size="+1"><tt><b>*</b></tt></font>
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Arrival Date</span>
</td>
<td>
<input name="ArrivalDate" type="date" />
<font color="orangered" size="+1"><tt><b>*</b></tt></font>
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Show Arrival</span>
</td>
<td>
<input name="ArrivalDateShown" type="checkbox" />
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Material</span>
</td>
<td>
<input name="Material" type="text" maxlength="100" size="25" />
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Condition</span>
</td>
<td>
<input id="ItemCondition" name="ItemCondition" type="text" maxlength="100" size="25" />
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Age</span>
</td>
<td>
<input name="Age" type="text" maxlength="100" size="25" />
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Item Size</span>
</td>
<td>
<input name="ItemSize" type="text" maxlength="100" size="25" />
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Price</span>
</td>
<td>
<input name="Price" type="text" maxlength="100" size="25" />
<font color="orangered" size="+1"><tt><b>*</b></tt></font>
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Info Red</span>
</td>
<td>
<input name="InfoRed" type="text" maxlength="100" size="25" />
</td>
</tr>
<tr valign="top">
<td align="right">
<span style="padding-right:20px">Infos</span>
</td>
<td>
<textarea wrap="soft" name="Info" rows="5" cols="30"></textarea>
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">MainPicLink</span>
</td>
<td>
<input type="hidden" name="ItemTimestamp" value="">
<input id="MainPicLink" name="MainPicLink" type="text" maxlength="100" size="50" />
<input type="hidden" name="timestamp">
</td>
</tr>
<br><br><br>
<tr>
<td align="right">
<span style="padding-right:20px"></span>
</td>
<td>
<img src='sobimages/frame01.jpg' alt='' />
<input type="file" name="picture01" id="picture01" />
</td>
</tr>
<tr id="buttonarea">
<td align="left" colspan="2">
<hr noshade="noshade" />
<input type="button" name="recordPrevious" value=" < " onclick="jsRecordPrevious()"/>
<input type="button" name="recordNext" value=" > " onclick="jsRecordNext()"/>
<input id="recordDelete" type="submit" name="recordDelete" value="Delete Data" onclick="jsRecordDeleteWrite()" />
<input id="recordInsertEditCancel" type="button" name="recordInsertEditCancel" value=" Cancel New/Edit Data " onclick="jsRecordInsertEditCancel()"/>
<input id="recordEditWrite" type="submit" name="recordEditWrite" value="Save Edited Data" onclick="jsRecordUpdateWrite()" />
<input id="recordInsert" type="button" name="recordInsert" value="Create New Rec." onclick="jsRecordInsert()"/>
<input id="recordInsertWrite" type="button" name="recordInsertWrite" value="Save New Rec." onclick="jsRecordInsertWrite()" />
</td>
</tr>
</table>
<select id="lstCategories" name="Choose a Category" size="38" style="position: absolute; top: 145px; left: 160px; width: 210px; height: 670px;" onclick="lstCategorySelected()">
<option disabled="TRUE" style="background-color: #C0C0C0;">0200 Japanese Armor Yoroi & Yoroi Parts</option>
<option>0201 Yoroi</option>
<option>0202 Cuirass - Dou</option>
<option>0203 Kusazuri</option>
<option>0204 Haidate</option>
<option>0205 Suneate</option>
<option>0206 Kōgake</option>
<option>0207 Sode</option>
<option>0208 Kote</option>
<option>0209 Helmet - Kabuto</option>
<option>0210 Jingasa</option>
<option>0211 Maedate</option>
<option>0212 Menpō</option>
<option>0213 Yodare-kake</option>
<option>0214 Armor Box - Bitsu</option>
<option>0215 Kabuto Box</option>
<option>0216 Japanese Weapons</option>
<option>0217 Other Collectibles</option>
<option disabled="TRUE" style="background-color: #C0C0C0;">0300 Reacting</option>
<option>0301 Tsuka Ito</option>
<option>0302 Idoshi Ito</option>
<option>0303 Fabric</option>
<option>0304 Buttons</option>
<option>0305 Urushi</option>
<option>0306 Other (2)</option>
<option>0307 Other (3)</option>
<option>0308 Other (4)</option>
<option disabled="TRUE" style="background-color: #C0C0C0;">0400 Japanese Antique</option>
<option>0401 Ceramic</option>
<option>0402 Kakejiku - Kakemono Scroll</option>
<option>0403 Metal Work</option>
<option>0404 Painting - Ukiyo-e</option>
<option>0405 Taiko Drum</option>
<option>0406 Wood Carving</option>
<option>0407 Other Collectibles</option>
<option disabled="TRUE" style="background-color: #C0C0C0;">0500 Chinese & Vietnamese Antiques</option>
<option>0501 Various (1)</option>
<option>0502 Various (2)</option>
</select>
<select id="lstMaterial" name="Choose Materials" size="12" multiple="TRUE" style="position: absolute; top: 345px; left: 840px; width: 210px; height: 200px;">
<option>Kaki(Persimmons wood)</option>
<option>Hinoki(Cypress)</option>
<option>Sugi(Cedar)</option>
<option>Keyaki(Zelkova)</option>
<option>Bronze</option>
<option>Kiri (Paulownia wood)</option>
<option>Kuri(Chestnut wood)</option>
<option>Maki-e</option>
<option>Forged Iron Hardware</option>
<option>Coral</option>
<option>Bamboo</option>
<option>Jade Stone</option>
</select>
<input id="lstMaterialToString" type="button" name="materialToString" value="Add Selection to Material" onclick="lstMaterialSelected()" style="position: absolute; top: 545px; left: 840px;"/>
</form>
<div id="mulitplefileuploader" title="">
<br>
Upload
</div>
<div id="status"></div>
<script>
$(document).ready(function()
{
var settings = {
url: "upload.php",
method: "POST",
allowedTypes:"jpg,png,gif",
fileName: "myfile",
multiple: true,
onSuccess:function(files,data,xhr)
{
$("#status").html("<font color='green'>Upload successful</font>");
},
onError: function(files,status,errMsg)
{
$("#status").html("<font color='red'>Upload failed</font>");
}
}
$("#mulitplefileuploader").uploadFile(settings);
});
</script>
</div>
</div>
</div>
<div id="aside">
</div>
<br class="clearfloat" />
</div> <!-- End of main container -->
</div><!-- END Page Wrap -->
<div id="footer">
<br class="clearfloat" />
<?php
if(isset ($_SESSION['name']))
{
$loginTitle="Logout";
$loginLink="body_logout.php";
}
else
{
$loginTitle="Login";
$loginLink="body_login.php";
}
?>
<p id="copyright">© 2015 by XXX | Terms of Use & Privacy Policy | <?php echo $loginTitle;?></p>
</div>
</body>
</html>
File: "upload.php"
//If directory doesnot exists create it.
$output_dir = "sobimages/";
if(isset($_FILES["myfile"]))
{
$ret = array();
$error =$_FILES["myfile"]["error"];
{
if(!is_array($_FILES["myfile"]['name'])) //single file
{
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
//echo "<br> Error: ".$_FILES["myfile"]["error"];
$ret[$fileName]= $output_dir.$fileName;
}
else
{
$fileCount = count($_FILES["myfile"]['name']);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
$ret[$fileName]= $output_dir.$fileName;
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName );
}
}
}
echo json_encode($ret);
}
?>

1. Use mysqli_connect, mysqli object or pdo
mysql_connect is deprecated as of PHP 5.5.0
2. In your code
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
(a) Good Practice is modifying the provided filename with system generated filename :: you may use time() or microtime() functions
i.e. Use
$_filename = rand().time().end(explode('.', $_FILES['myfile']['name']));
(b) Fetch your database-table-field for the picture data and append the new file name with '#' as concatenation string.
i.e. $_filename = $dbfiles.'#'.$_filename
(c) This filename is to be saved to database with the query
'UPDATE `items` SET `PicturesFilenames` = \''.$_filename.'\' WHERE foo_id='.$_id
I prefer logic than code as coding methodology varies person to person
Thanks & Regards

Related

Insert add row feature in PHP form and linking it to the database

How can i include add row feature in my PHP form and insert additionally added rows into the database? I havetried using the HTML code for button to insert additional rows but it does not work. Do i need to use javascript?? Please help me
This is my HTML code. Row is not added after hitting add button.
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script language="javascript" type="text/javascript">
var i=1;
function addRow()
{
var tbl = document.getElementById('table2');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var el = document.createElement('input');
el.type = 'text';
el.name = 'activityname_' + i;
el.id = 'activityname_' + i;
firstCell.appendChild(el);
var secondCell = row.insertCell(1);
var el2 = document.createElement('input');
el2.type = 'text';
el2.name = 'unit_' + i;
el2.id = 'unit_' + i;
secondCell.appendChild(el2);
var thirdCell = row.insertCell(2);
var el3 = document.createElement('input');
el3.type = 'text';
el3.name = 'weightage_' + i;
el3.id = 'weightage_' + i;
thirdCell.appendChild(el3);
var thirdCell = row.insertCell(3);
var el4 = document.createElement('input');
el4.type = 'text';
el4.name = 'per100_' + i;
el4.id = 'per100_' + i;
fourthCell.appendChild(el4);
var thirdCell = row.insertCell(4);
var el5 = document.createElement('input');
el5.type = 'text';
el5.name = 'per75_' + i;
el5.id = 'per75_' + i;
fifthCell.appendChild(el5);
var thirdCell = row.insertCell(5);
var el6 = document.createElement('input');
el6.type = 'text';
el6.name = 'per50_' + i;
el6.id = 'per50_' + i;
sixthCell.appendChild(el6);
var thirdCell = row.insertCell(6);
var el7 = document.createElement('input');
el7.type = 'text';
el7.name = 'per75_' + i;
el7.id = 'per75_' + i;
seventhCell.appendChild(el7);
// alert(i);
i++;
frm.h.value=i;
// alert(i);
}
</script>
<?php
error_reporting(0);
include ('includes/workplan_func.php');
?>
<link rel="stylesheet" type="text/css" href="css/mystyle.css" />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Workplan Detail Form </title>
</head>
<body>
<div id="wrapper">
<div id="header">
<img src="images/logo.jpg" width="305" height="108" />
</div>
<div id="Box">
<ul>
<li>Workplan Detail</li>
<li>Workplan Progress</li>
<li>PBIS</li>
<li>Logout</li>
</ul>
</div>
<div id="rightcol">
<div id="Content" align="center">
<h1 align="center">Workplan Detail Form</h1>
<div id="table1" class="container" align="left">
//<form name="frm" id="frm" action="includes/workplan_func.php" method="post">
<table width="398" height="118" border="0" align="left" >
<td>
<tr>
<td > <p>Division Name:</p> </td>
<td><input name="divisionname" type="text" /></td>
</tr>
<tr>
<td><p>Division Chief: </p></td>
<td>
<input type="text" name="divisionchief" /></td>
</tr>
<tr>
<td><p> Period: </p> </td>
<td>
<input type="text" name="period" /></td>
</tr>
<tr>
<td><p> Month:</p> </td>
<td>
<input type="month" name="month" /> </td>
</tr>
</table>
</td>
</table>
</div>
<div id="table2">
<table border="1" align="center" cellpadding="1" cellspacing="1">
<tr>
<td rowspan="2" align="center"> SN </td>
<td rowspan="2" align="center"> Activity Name </td>
<td rowspan="2" align="center" > Unit </td>
<td rowspan="2" align="center"> Weightage </td>
<td colspan="4" align="center"> Performance Indicators(Percentage)
</td>
<tr>
<td align="center">100 </td>
<td align="center"> 75</td>
<td align="center"> 50 </td>
<td align="center"> <50 </td>
</tr>
<form name="frm" id="frm" action="includes/workplan_func.php" method="post">
<table border="1" align="center" cellpadding="1" cellspacing="1" id="table2">
<tr>
<td width:50px > </td>
<td> <input type="text" name="activityname_0" id="activityname_0" style="width:130px"/> </td>
<td> <input type="text" name="unit_0" id="unit_0" style="width:50px" /> </td>
<td> <input type="text" name="weightage_0" id="weightage_0" style="width:130px" /> </td>
<td> <input type="text" name="per100_0" id="per100_0" style="width:50px" /> </td>
<td> <input type="text" name="per75_0" id="per75_0" style="width:50px" /> </td>
<td> <input type="text" name="per50_0" ="per50_0" style="width:50px" /> </td>
<td> <input type="text" name="perless50_0" id="perless50_0" style="width:50px" /> </td>
</tr>
</table>
</div>
<div id="button">
<div align="center"> <input type="button" value="Add" onclick="addRow();" />
<input name="submit" type="submit" value="Submit" />
</div>
</div>
</div>
<label>
<input name="h" type="hidden" id="h" value="0" />
</label>
</form>
</body>
</html>
If you are just looking to add more than one value without having to iterate over the possible outputs again and again then a statement such as the following may help you assuming you are using MySQL:
INSERT INTO your_table (value1,value2,value3) VALUES (v1,v2,v3),(v1,v2,v3),(etc...)
If you are looking to simply add form fields to you HTML then you will want to look into some JavaScript/JQuery solution that gives you the visual appeal you are looking for.
You would need to create the code that dynamically forms the string in place of the (v1,v2,v3),(v1,v2,v3),(etc...) but that can be a simple foreach loop.
Hope this helps you out a little.

Dynamic Form Using Ajax PHP

I'm working on the ajax for the first time.
I've one dynamic form which adds similar form on clicking "Add Button" and also there is a field in each form "Get Data" which is used to retrieve data from database for individual filed. The problem is "Get Data" not working for all field.
<style>
td {
border: solid 1px lightGrey;
padding: 0 4px 0 4px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
var count = 0;
$(document).ready(function(){
$.ajaxSetup ({
cache: false
});
var loadUrl = "ajaxfunc.php";
$("#submit").click(function(){
count += 1;
$("#result").load(loadUrl,{name:document.getElementById('fields'+count).value},function(responseText){
});
});
$(function(){
$('p#addField').click(function(){
count += 1;
$('#fields1').append(
'<div id="fields">'
+'<table border="0">'
+'<tr>'
+'<td width="100">'
+'ISBN NO :'
+'</td>'
+'<td>'
+' <input type="text" id="cIsbn1" name="cIsbn[]" />'
+'</td>'
+'<td>'
+'<button name="submitit" id="submit' + count + '" type="button" class="btn " style="float:left;">Get Data</button>'
+'</td>'
+'</tr>'
+'<tr>'
+'<td> Book Name:</td>'
+'<td> <input type="text" id="bookName' + count + '" name="bookName[]" style="width:200px;" /> </td>'
+'<td> Price : </td>'
+'<td> RM<input type="text" id="price' + count + '" name="price[]" style="width:50px;"/>'
+' $<input type="text" id="other_price' + count + '" name="other_price[]" style="width:50px;" readonly="readonly"/> </td>'
+'</tr>'
+'<tr>'
+'<td> Quantity :</td>'
+'<td><input type="text" id="quantity' + count + '" name="quantity[]" /></td>'
+'<td> Discount (in %): </td>'
+'<td> <input type="text" id="discount' + count + '" name="discount[]" /></td>'
+'</tr>'
+'<tr>'
+'<td>'
+'Net Price :'
+'</td>'
+'<td>'
+'<input type="text" id="netPrice' + count + '" name="netPrice[]" />'
+'</td>'
+'</tr>'
+'<tr>'
+'<td>'
+'Remarks :'
+'</td>'
+'<td style="height:45px;">'
+'<textarea id="ind_remarks' + count + '" name="ind_remarks[]" style="resize:none; position:absolute;"></textarea>'
+'</td>'
+'</tr>'
+'</div>'
+'</table><hr>'
+'</div>');
});
});});
</script>
<div id="contentWrapper">
<?php include('includes/sidebar_left.php');?>
<div class="content">
<h2>Add New Customer & Issue Quotation</h2>
<hr />
<form id="newBook" action="newBookProcess.php" method="post" enctype="multipart/form-data">
<table border="0">
<tr>
<td width="152">Customer Name *</td>
<td width="231">:
<input class="validate[required] text-input" type="text" name="cName" /></td>
<td width="272" rowspan="6"><p>Remarks:</p>
<p>
<textarea name="remarks" rows="7" cols="33" style="resize:none;"></textarea>
</p></td>
</tr>
<tr>
<td>Address</td>
<td> :
<input type="text" name="cAddress1" /><br />
: <input type="text" name="cAddress2" /></td>
</tr>
<tr>
<td>Telephone </td>
<td>:
<input type="text" name="cTelephone" /></td>
</tr>
<tr>
<td>Fax</td>
<td>:
<input type="text" name="cFax" /></td>
</tr>
</table>
<hr />
<p style="width:100%;">
<h2 style="font-size:16px;">Add Book To Quotation </h2>
<p id="addField" style="border:none; background:none; width:100%;cursor:pointer; right:0; float:right;"><img src="images/addNew.png" width="100" style="border:none;"/> <p>
<hr />
</p>
<div id="fields1">
<table border="0">
<tr>
<td width="100">
ISBN NO :
</td>
<td>
<input type="text" name="cIsbn[]" id="cIsbn" />
</td>
<td>
<button name="submitit" id="submit2" type="button" class="btn " style="float:left;">Get Data</button>
</td>
</tr>
<tr>
<td>
Book Name:
</td>
<td>
<input type="text" name="bookName[]" style="width:200px;" />
</td>
<td>
Price :
</td>
<td>
RM<input type="text" name="price[]" style="width:50px;"/>
$<input type="text" name="other_price[]" style="width:50px;" readonly/>
</td>
</tr>
<tr>
<td>
Quantity :
</td>
<td>
<input type="text" name="quantity[]" />
</td>
<td>
Discount (in %):
</td>
<td>
<input type="text" name="discount[]" />
</td>
</tr>
<tr>
<td>
Net Price :
</td>
<td>
<input type="text" name="netPrice[]" />
</td>
</tr>
<tr>
<td>
Remarks :
</td>
<td style="height:45px;">
<textarea name="ind_remarks[]" style="resize:none; position:absolute;"></textarea>
</td>
<td>
<button id="addField">Add New </button>
</td>
</tr>
</table>
<hr />
</div>
<p>
<input type="submit" value="Add Book" style="cursor:pointer;" />
<input type="reset" style="cursor:pointer;" /> <span class="req">* required fileds</span>
</p>
</form>
<div id="result" style="overflow:hidden;" >
</div>
</div>
</div>
</div>
<?php include('includes/footer.php');?>
Above code is my code.
Please help me.
For a start, the value of the id attribute of an element has to be unique; it's an identifier, it can't uniquely identify a specific element if you have multiple elements with the same id. Use a class instead.
Now, when you do $('#submit') in your jQuery code, that will only select elements that exist on the page at the time the code is executed. And, because it's an ID selector, it will only select at most one element.
If you want to bind event handlers to elements that are added after the page loads, you'll need to use event delegation:
$('#fields1').on('click', '.submit-button', function(e) {
count += 1;
$("#result").load(loadUrl,{name:document.getElementById('fields'+count).value});
});
Note that I've removed the empty callback function; if you don't want to do anything inside it then you don't need to pass it - it's an optional argument. I've also used .submit-button as the selector for the call to .on(); I'm assuming that rather than id="submit" you'll be using class="submit-button".
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup ({
cache: false
});
var loadUrl = "ajaxfunc.php";
var count=1
$("button").live('click', function(){
$("#result").load(loadUrl,{name:document.getElementById('fname1').value, email:document.getElementById('mytext').value, id:document.getElementById('id'+count).value },function(responseText){
count=count+1;
});
});
});
$(document).ready(function(){
var i = $('input').size() + 1;
var count=1
$('#add').click(function() {
$('<div><input type="text" id="fname'+count+'" /><input type="text" id="id'+count+'" /><button id="submit'+count+'" type="button" style="float:left;">Submit'+count+'</button><div id="result" style="font-size:0px;width:30px;overflow:hidden;" ></div></div>').fadeIn('slow').appendTo('#form');
var bj = count;
count = count+1;
var test = bj;
document.getElementById("mytext").value = test;
});
});
function printIt(){
var sj = document.getElementById('mytext').value;
alert(sj);
}
</script>
</script>
Add
<form id="contact" action="" method="post" enctype="multipart/form-data" >
<div id="form"></div>
<div id="printHere"></div>
<input type="hidden" name="countC" id="mytext" />
<input type=button value="Get Value" onclick="printIt()" />
</form>

Get the database content posted on a selected option into a form with single fields

I have a form with a select. The options are coming from a database and displayed into the select.
The columns on the database are:
id, date, title, body.
On the select I display only date and title. In the same page I have a form with:
date -> input text
title -> input text
body -> text area
I want that when an option from the select is clicked by the user the fields below will be update with the content kept from the selected option which contain the database data.
Now I have no idea how to get the data on the fields below.
My idea was to get the index of the option of the drop down. Is this possible?
EDIT COMPLETE CODE:
<html>
<body>
<div class="normal">
<table style="width:100%;height:100%;" border="1">
<tr>
<td width="174"><strong>geste n</strong></td>
<td width="505" valign="middle" height="24">
<input type="radio" name="n" id="new" value="nuova" onchange="shown(this.id);" <?php if($_POST['n'] == "nuova"){echo "CHECKED";} ?> />Nuova n
<input type="radio" name="n" id="mod" value="modifica" onchange="shown(this.id);" <?php if($_POST['n'] == "modifica"){echo "CHECKED";} ?> />Modifica n
<select id="sceltannascosta" style="display:none">
<?php
include("/login/flock/sql.php");
$conn = mysqli_connect($host, $user, $pw, $db) or die("Impossibile connettersi");
$a = "SELECT * FROM n ORDER BY id DESC";
$b = mysqli_query($conn, $a);
print '<option></option>';
while ($c = $b->fetch_object()) {
print '<option>'.$c->id.$c->data.$c->title.$c->body.'</option>';
}
$b->close();
$conn->close;
?>
</select>
<select id="sceltan" style="display:none" onChange="showEntry(this,this.value);setndamod(this);">
<?php
include("/login/flock/sql.php");
$conn = mysqli_connect($host, $user, $pw, $db) or die("Impossibile connettersi");
$a = "SELECT * FROM n ORDER BY id DESC";
$b = mysqli_query($conn, $a);
print '<option></option>';
while ($c = $b->fetch_object()) {
print '<option>'.$c->data.' - '.$c->title.'</option>';
}
$b->close();
$conn->close;
?>
</select>
<input type="submit" id="botenascostogeste" class="button">
</form>
</td>
</tr>
</table>
</div>
<p> </p>
<div class="normal" id="c" style="display:none">
<table style="width:100%;height:100%;">
<tr>
<td colspan="3" border="0">
<strong class="confirm">c nuova n</strong>
</td>
</tr>
<tr>
<td width="107" align="right">
<strong>Data</strong>
</td>
<td colspan="2">
<form name="nuovan" method="post" action="cht.php?c=yes">
<input name="datan" type="text" maxlength="10" size="8" value="<?php echo date(d.".".m.".".Y) ?>"> gg.mm.aaaa
</td>
</tr>
<tr>
<td align="right">
<strong>Titolo</strong>
<td width="360">
<input name="titolon" type="text" maxlength="50" size="50" value="<? echo htmlspecialchars("titolo n - lunghezza massima 50 caratteri") ?>" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')">
</td>
<td width="522">
<b><span id=myCounter>6</span></b> caratteri rimanenti per il titolo</font>
</td>
</tr>
<tr>
<td colspan="3">
<textarea name="teston"><?php if(isset($_POST['teston'])){echo $_POST['teston'];}else{echo 'Testo n con stile personalizzato';} ?></textarea>
<script>
CKEDITOR.replace('teston');
</script>
</td>
</tr>
<tr>
<td align="right">
<input type="submit" name="c" class="button" onClick="document.getElementById('botenascostogeste').click();">
</form>
</td>
<td colspan="2">
<?php
$c = $_GET['c'];
$titolon = $_POST['titolon'];
$teston = $_POST['teston'];
$datascritta = $_POST['datan'];
if($c == 'yes'){
if($_POST['titolon'] == NULL || $_POST['teston'] == NULL || $_POST['datan'] == NULL){
echo '<img src="'.$imagen.'" style=width:"' . $width . 'px;height:' . $height . 'px;">';
} else {
function verificadata($datascritta) {
list($dd,$mm,$yyyy)=explode(".",$datascritta);
if (is_numeric($dd) && is_numeric($mm) && is_numeric($yyyy))
{
return checkdate($mm,$dd,$yyyy);
}
return false;
}
if(verificadata($datascritta)){
$connessione = mysql_connect ($host, $user, $pw) or //connect to the database
die('<img src="'.$imagen.'" style=width:"' . $width . 'px;height:' . $height . 'px;">');
mysql_select_db ($db); //select the database
mysql_query("INSERT INTO n(data, title, body) VALUES ('$datascritta', '$titolon', '$teston')");
mysql_close($connessione);
echo ('<img src="'.$imagey.'" style=width:"' . $width . 'px;height:' . $height . 'px;"> Ok'); // It worked.
} else { die('<img src="'.$imagen.'" style=width:"' . $width . 'px;height:' . $height . 'px;">');
}
}
}
?>
</td>
</table>
</div>
<div class="normal" id="modifica" style="display:none">
<table style="width:100%;height:100%;">
<tr>
<td colspan="3" border="0">
<strong class="confirm">Modifica n</strong>
</td>
</tr>
<tr>
<td width="107" align="right">
<strong>Data</strong>
</td>
<td colspan="2">
<form name="modifican" method="post" action="cht.php?modifica=yes">
<input name="idmodifican" type="text" style="display:none" value="INSERIRE ID DI MODIFICA DEL DATABASE QUI">
<input name="datanmodificata" type="text" maxlength="10" size="8" value="POST DATE FROM THE n TO MODIFY SELECTED"> gg.mm.aaaa
</td>
</tr>
<tr>
<td align="right">
<strong>Titolo</strong>
</td>
<td width="360">
<input name="modificatitolo" type="text" maxlength="50" size="50" value="POST TITLE FROM THE n TO MODIFY SELECTED" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')">
</td>
<td width="522">
<b><span id=myCounter>50</span></b> caratteri rimanenti per il titolo</font>
</td>
</tr>
<tr>
<td colspan="3">
<textarea name="modificatesto">POST BODY FROM THE n TO MODIFY SELECTED</textarea>
<script>
CKEDITOR.replace('modificatesto');
</script>
</td>
</tr>
<tr>
<td align="right">
<input type="submit" name="modifica" class="button">
</form>
</td>
<td colspan="2">
PHP I HAVE TO DO TO UPDATE THE n ON THE DATABASE (I'm able to do this part).
</td>
</table>
</div>
</body>
for this you need to make ajax call.
then use jquery to get the field set up depending upon the value selected in the select field you can set the value of the other fields try this modify it according to your need
<body>
<form>
<select id="sel_opt">
<?php
$i = 1;
foreach($valueformdb as $value)
{
echo "<option class=\"option\" id=\"opt_$i\">";
echo $value;
echo '</option>';
$i++;
}
?>
</select>
<input type="text" id="txt_date" value="" />
<input type="text" id="txt_title" value="" />
<textarea id="ta_body"></textarea>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.sel_opt').on('change', function(){
var id = $(this).attr('id');
$.ajax({
type:'POST',
dataType: 'json',
url:" ",// path of file to handle ajax request
data:'option='+id, // this will be posted on the page which handle the ajax and give back the data from db
success:function(data){
$('#txt_date').val(data[date]);// ajax respond the array containg the value its advised to use json
$('#txt_title').val(data[title]);
}
});
});
});
</script>
</body>
this is not the exact code you need to modify a bit, cause i don't know the exact thing you are trying to achieve

SyntaxError: unexpected end of XML source

I have a site and iam using saleforce.com .
This is my code:
function salesforce() {
var first_name = $("#first_name_new").val();
var last_name = $("#last_name_new").val();
var coupon_code = $("#coupon_code_new").val();
var phone = $("#phone_new").val();
var email = $("#email_new").val();
var state = $("#state_new").val();
var oid = "00DU0000000HB32";
var retURL = "http://www.testsite.com";
var debug = "1";
var debugEmail = "arnold#gmail.com";
//alert(first_name_new+"/"+last_name+"/"+coupon_code+"/"+phone+"/"+email+"/"+state);
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8",
data: { first_name: first_name, last_name: last_name, phone: phone, email:email, state:state, oid:oid, debug:debug, debugEmail:debugEmail },
success:function(data){
contactSent = "true";
},
error:function(data){
contactSent = "true";
}
});
}
I called this function onclick of a button:
$(function(){
$('.next-product').click(function(){
salesforce();
});
});
This is the button:
<button class="next-product">Next</button>
When i clicked on the button it displays error in bug as:
SyntaxError: unexpected end of XML source
<BR><BR>Your request has been queued.<BR><BR>Record Information:<BR><BR>_: 1345203119160<BR>callback: jQuery172007126272654237087_1345203087782<BR>debug: 1<BR>debugEmail: arnold#gmail.com<BR>email: mariya#galtech.org<BR>encoding: UTF-8<BR>first_name: ttt<BR>last_name: tttteee<BR>oid: 00DU0000000HB32<BR>phone: 1234567896<BR>state: kerala<BR>
How can i solve this?
EDIT:
This is the whole code in the page iam using:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TradeYourWreck.com | Wrecked Car? Don't sell it… Fix it</title>
<link href="tyw.css" rel="stylesheet" type="text/css" />
<link type="text/css" href="css/redmond/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript" src="js/ajaxupload.3.5.js" ></script>
<script type="text/javascript" src="http://www.carqueryapi.com/js/carquery.0.3.3.js"></script>
<!--[if lte IE 7]>
<style>
.content { margin-right: -1px; } /* this 1px negative margin can be placed on any of the columns in this layout with the same corrective effect. */
ul.nav a { zoom: 1; } /* the zoom property gives IE the hasLayout trigger it needs to correct extra whiltespace between the links */
</style>
<![endif]-->
<script type="text/javascript">
$(document).ready(
function()
{
//Create a variable for the CarQuery object. You can call it whatever you like.
var carquery = new CarQuery();
//Run the carquery init function to get things started:
carquery.init();
//Optionally, you can pre-select a vehicle by passing year / make / model / trim to the init function:
//carquery.init('2000', 'dodge', 'Viper', 11636);
//Optional: Pass sold_in_us:true to the setFilters method to show only US models.
carquery.setFilters( {sold_in_us:true} );
//Optional: initialize the year, make, model, and trim drop downs by providing their element IDs
carquery.initYearMakeModelTrim('car-years', 'car-makes', 'car-models', 'car-model-trims');
//Optional: set the onclick event for a button to show car data.
$('#cq-show-data').click( function(){ carquery.populateCarData('car-model-data'); } );
//Optional: initialize the make, model, trim lists by providing their element IDs.
carquery.initMakeModelTrimList('make-list', 'model-list', 'trim-list', 'trim-data-list');
//Optional: set minimum and/or maximum year options.
carquery.year_select_min=1980;
carquery.year_select_max=2012;
//Optional: initialize search interface elements.
//The IDs provided below are the IDs of the text and select inputs that will be used to set the search criteria.
//All values are optional, and will be set to the default values provided below if not specified.
var searchArgs =
({
body_id: "cq-body"
,default_search_text: "Keyword Search"
,doors_id: "cq-doors"
,drive_id: "cq-drive"
,engine_position_id: "cq-engine-position"
,engine_type_id: "cq-engine-type"
,fuel_type_id: "cq-fuel-type"
,min_cylinders_id: "cq-min-cylinders"
,min_mpg_hwy_id: "cq-min-mpg-hwy"
,min_power_id: "cq-min-power"
,min_top_speed_id: "cq-min-top-speed"
,min_torque_id: "cq-min-torque"
,min_weight_id: "cq-min-weight"
,min_year_id: "cq-min-year"
,max_cylinders_id: "cq-max-cylinders"
,max_mpg_hwy_id: "cq-max-mpg-hwy"
,max_power_id: "cq-max-power"
,max_top_speed_id: "cq-max-top-speed"
,max_weight_id: "cq-max-weight"
,max_year_id: "cq-max-year"
,search_controls_id: "cq-search-controls"
,search_input_id: "cq-search-input"
,search_results_id: "cq-search-results"
,search_result_id: "cq-search-result"
,seats_id: "cq-seats"
,sold_in_us_id: "cq-sold-in-us"
});
carquery.initSearchInterface(searchArgs);
//If creating a search interface, set onclick event for the search button. Make sure the ID used matches your search button ID.
$('#cq-search-btn').click( function(){ carquery.search(); } );
});
</script>
<script type="text/javascript">
var contactSent = "false";
$(function(){
//$("#tabVPhoto").hide();
$("#tabPkg").hide();
$('#tabs').tabs({
fx: {
opacity: 'toggle'
}
});
});
function lookupVIN() {
//console.log("lookup vin");
var car_vin = $("#car-vin").val();
$.ajax({
type: "GET",
url: "vin.php",
data: { car_vin: car_vin },
success:function(data){
//console.log(data);
$("#vinDet").html(data);
//vinDet
},
error:function(data){
}
});
}
function salesforce() {
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var phone = $("#phone").val();
var email = $("#email").val();
var state = $("#state").val();
var oid = "00DU0000000HB32";
var retURL = "http://www.tradeyourwreck.com";
var debug = "1";
var debugEmail = "arnold#vemark.com";
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8",
data: { first_name: first_name, last_name: last_name, phone: phone, email:email, state:state, oid:oid, debug:debug, debugEmail:debugEmail },
success:function(data){
contactSent = "true";
},
error:function(data){
contactSent = "true";
}
});
}
$(function(){
$('.next-product').click(function(){
var index = jQuery('#tabs').data('tabs').options.selected;
//console.log(contactSent);
var pkg = $('input:radio[name=pkg]:checked').val();
/*
if(pkg=="self") {
$("#tabVPhoto").show();
$("#tabVCond").show();
$("#self").show();
$("#inspect").hide();
}else {
$("#tabVPhoto").hide();
$("#tabVCond").hide();
$("#self").hide();
$("#inspect").show();
//alert('inspect');
}
*/
var $tabs = $('#tabs').tabs();
var selected = $tabs.tabs('option', 'selected');
$tabs.tabs('select', selected+1);
if(index==0) {
if(contactSent == "false"){
salesforce();
}
}
})
$('.previous-product').click(function(){
var index = jQuery('#tabs').data('tabs').options.selected;
//console.log(index);
var pkg = $('input:radio[name=pkg]:checked').val();
if(pkg=="self") {
$("#tabVPhoto").show();
$("#tabVCond").show();
}else {
$("#tabVPhoto").hide();
$("#tabVCond").hide();
//alert('inspect');
}
var $tabs = $('#tabs').tabs();
var selected = $tabs.tabs('option', 'selected');
$tabs.tabs('select', selected-1);
})
$( '.next-product').button({
text: true,
icons: {
primary: "ui-icon-seek-next"
}
});
$( '.previous-product' ).button({
text: true,
icons: {
primary: "ui-icon-seek-prev"
}
});
});
$(function(){
var cntUp = 0;
var btnUpload=$('#upload');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
alert('Only JPG, PNG or GIF files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(file, response){
//On completion clear the status
status.text('image uploaded');
cntUp++;
//console.log(cntUp);
//Add uploaded file to list
if (response.toLowerCase().indexOf("success") >= 0 ) {
//alert('success');
$('<li></li>').appendTo('#files').html('<img src="uploads/'+file+'" alt="" /><br />'+file).addClass('success');
} else{
$('<li></li>').appendTo('#files').text(file).addClass('error');
//alert('error');
}
}
});
});
</script>
</head>
<body>
<div class="container">
<div class="header">
<nav id="access" role="navigation">
<div class="menu-top-menu-container">
<ul id="menu-top-menu" class="menu">
<li id="menu-item-30" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-25 current_page_item menu-item-30">Home</li>
<li id="menu-item-21" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-21">About TradeYourWreck.com</li>
<li id="menu-item-22" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-22">Inquiries</li>
</ul>
</div>
</nav>
<img src="images/header1.jpg" width="1000" height="163" alt=""> </div>
<?php include 'inc/sidebar.php'; ?>
<div class="content">
<div style="width:675px; margin: 0 auto; margin-top:10px; font-size:12px;" id="tabs">
<ul>
<!--<li id="tabPkg">Select Your Package</li> -->
<li id="tabVInfo">Contact Information</li>
<li id="tabVCond">Vehicle Information</li>
<li id="tabVPhoto">Additional Vehicle Information</li>
<li id="tabVCheck">Check Out</li>
</ul>
<div id="tabs-2">
<input type=hidden name="oid" value="00DU0000000HB32">
<input type=hidden name="retURL" value="http://www.tradeyourwreck.com">
<input type="hidden" name="debug" value=1>
<input type="hidden" name="debugEmail" value="arnold#vemark.com">
<!--<input type="hidden" name="debugEmail" value="jweeks#thoughtwm.com">-->
<table cellpadding="3">
<tr>
<td>First Name</td>
<td><input id="first_name" maxlength="40" name="first_name" size="20" type="text" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input id="last_name" maxlength="80" name="last_name" size="20" type="text" /></td>
</tr>
<tr>
<td>Phone</td>
<td><input id="phone" maxlength="40" name="phone" size="20" type="text" /></td>
</tr>
<tr>
<td>Email Address</td>
<td><input id="email" maxlength="80" name="email" size="30" type="text" /></td>
</tr>
<tr>
<td>State/Province</td>
<td><input id="state" maxlength="20" name="state" size="20" type="text" /></td>
</tr>
<tr>
<td> </td>
<td><button class="previous-product">Previous</button>
<button class="next-product">Next</button></td>
</tr>
</table>
​ </div>
<div id="tabs-3">
<!-- -->
<table cellpadding="3">
<tr>
<td valign="top">VIN</td>
<td>
<!-- test VINS:
1GDGG31Z4RF513458<br/>
KMHCG45C31U211444<br/>
2MEFM75W7YX721741<br/>
-->
<input class="frmIn" size="30" value="" name="car-vin" id="car-vin" type="text" value="" />
<input onclick="lookupVIN()" name="btnVin" type="button" value="Lookup" />
<br/>
<div id="vinDet"></div></td>
</tr>
<tr>
<td>Year</td>
<td><select name="car-years" id="car-years">
</select></td>
</tr>
<tr>
<td>Make</td>
<td><select name="car-makes" id="car-makes">
</select></td>
</tr>
<tr>
<td>Model</td>
<td><select name="car-models" id="car-models">
</select></td>
</tr>
<!--<tr>
<td>Trims</td>
<td><select name="car-model-trims" id="car-model-trims"></select></td>
</tr>
<tr>
<td>Color</td>
<td><input class="frmIn" name="car-color" type="text" value="" /></td>
</tr>
<tr>
<td>Mileage</td>
<td><input class="frmIn" name="car-mileage" type="text" value="" /></td>
</tr>
<tr>
<td>Repair Estimate</td>
<td><input class="frmIn" name="car-estimate" type="text" value="" /></td>
</tr>
<tr>
<td>Reserve Price</td>
<td><input class="frmIn" name="car-reserve" type="text" value="" /></td>
</tr>
<tr>
<td>Secondary Damage</td>
<td><input class="frmIn" name="car-damage" type="text" value="" /></td>
</tr>
<tr>
<td>Comments</td>
<td><textarea class="frmIn" name="car-comment" cols="20" rows="5"></textarea></td>
</tr>-->
<tr>
<td> </td>
<td><button class="previous-product">Previous</button>
<button class="next-product">Next</button></td>
</tr>
</table>
​ </div>
<div id="tabs-4">
<table cellpadding="3">
<tr>
<td>Repair Estimate</td>
<td><input class="frmIn" name="car-estimate" type="text" value="" /></td>
</tr>
<tr>
<td>Reserve Price</td>
<td><input class="frmIn" name="car-reserve" type="text" value="" /></td>
</tr>
<tr>
<td>Primary Damage</td>
<td><select name="car-damage">
<option value="Center Rear">Center Rear</option>
<option value="Chemical Spill">Chemical Spill</option>
<option value="Dash Fire">Dash Fire</option>
<option value="Engine">Engine</option>
<option value="Engine Fire">Engine Fire</option>
<option value="Fallen Tree">Fallen Tree</option>
<option value="Fresh Water">Fresh Water</option>
<option value="Hail Damage">Hail Damage</option>
<option value="Hard Roll">Hard Roll</option>
<option value="Interior Fire">Interior Fire</option>
<option value="Left Front">Left Front</option>
<option value="Left Rear">Left Rear</option>
<option value="Left Side">Left Side</option>
<option value="Lite Fire Damage">Lite Fire Damage</option>
<option value="Lite Roll">Lite Roll</option>
<option value="Medium Roll">Medium Roll</option>
<option value="None">None</option>
<option value="Right Front">Right Front</option>
<option value="Right Rear">Right Rear</option>
<option value="Right Side">Right Side</option>
<option value="Rolled">Rolled</option>
<option value="Roof">Roof</option>
<option value="Salt Water">Salt Water</option>
<option value="Theft Heavy Strip">Theft Heavy Strip</option>
<option value="Theft Lite Strip">Theft Lite Strip</option>
<option value="Theft Recovery">Theft Recovery</option>
<option value="Total Burn">Total Burn</option>
<option value="Undercarriage">Undercarriage</option>
<option value="Vandalized">Vandalized</option>
<option value="Transmission">Transmission</option>
<option value="Center Front">Center Front</option>
<option value="Mechanical">Mechanical</option>
</select></td>
</tr>
</table>
<div style="margin-top:15px;" id="mainbody" >
<div id="upload" style="margin-bottom:10px;" ><span>Upload Photos<span></div>
<!--<span id="status" >status</span> -->
<ul id="files" >
</ul>
<button class="previous-product">Previous</button>
<button class="next-product">Next</button>
</div>
​ </div>
<div id="tabs-5">
<div id="self">
<!-- <table border="0">
<tr>
<td><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="U3XMXN3S94BB6">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form></td>
</tr>
<tr>
<td><img src="images/packages_img1.png" width="286" height="95" alt="Let us Do The work" /></td>
</tr>
</table> -->
</div>
<div id="inspect">
<table border="0" cellpadding="0">
<tr>
<td><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="U3XMXN3S94BB6">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form></td>
<td><img src="images/packages_img1.png" width="286" height="95" alt="Let us Do The work" /></td>
</tr>
<tr>
<td><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="XEEB6CNLRWJAJ">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form></td>
<td><img src="images/packages_img2.png" width="286" height="95" alt="Let us Do The work" /></td>
</tr>
</table>
<!-- <table border="0">
<tr>
<td align="center"><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="XEEB6CNLRWJAJ">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form></td>
</tr>
<tr>
<td><img src="images/packages_img2.png" width="286" height="95" alt="Let us Do The work" /></td>
</tr>
</table>
--> </div>
</div>
</div>
</div>
<p> </p> </div>
<?php include 'inc/footer.php'; ?>
</body>
</html>

Integrating validation with Recaptcha (or required fields)

I have a form below that I want to make certain fields required based on different things.
I want the following fields to be a straight forward required field with a popup alert if they're not filled in:
Name
Email
I want the phone field to be required if phone is ticked.
Address to be required if post is ticked.
How can I make the alert's pop up if things are missing but if everything is ok then send the form?
<div id="contactform">
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'white'
};
</script>
<form class="form" method="POST" action="<?php the_permalink(); ?>" onsubmit="return validateCaptcha()">
<input type="hidden" name="valid" value="0" />
<table border="0" style="float:left;" width="490">
<tbody>
<tr>
<td>
<p>Name:</p>
</td>
<td> </td>
<td colspan="2"><input type="text" name="fullname" id="fullname" /></td>
</tr>
<tr>
<td>
<p>Organisation:</p>
</td>
<td> </td>
<td colspan="2"><input type="text" name="companyname" id="companyname" /></td>
</tr>
<tr>
<td>
<p>E-mail:</p>
</td>
<td> </td>
<td colspan="2"><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>
<p>Daytime Tel:</p>
</td>
<td> </td>
<td colspan="2"><input type="text" name="tel" id="tel" /></td>
</tr>
<tr>
<td valign="top">
<p>Contact Method:</p>
</td>
<td> </td>
<td align="left" valign="top">
<p>
<input style="width:20px!IMPORTANT;" type="checkbox" name="CheckboxGroup1[]" value="Phone" id="phone" />
<label style="margin-right: 25px;">Phone</label>
</p>
<p>
<input style="width:20px!IMPORTANT;" type="checkbox" name="CheckboxGroup1[]" value="Email" id="email" />
<label style="margin-right: 25px;">Email</label>
</p>
<p>
<input style="width:20px!IMPORTANT;" type="checkbox" name="CheckboxGroup1[]" value="Post" id="post" />
<label style="margin-right: 25px;">Post</label>
</p>
</td>
</tr>
<tr>
<td>
<p>Address (if applicable):</p>
</td>
<td> </td>
<td colspan="2"><input type="text" name="address" id="address" /></td>
</tr>
<tr>
<td valign="top">
<p>Where did you hear about us?:</p>
</td>
<td> </td>
<td align="left" valign="top">
<p>
<input style="width:20px!IMPORTANT;" type="checkbox" name="CheckboxGroup2[]" value="Search Engine" id="search" />
<label style="margin-right: 25px;">Search Engine</label>
</p>
<p>
<input style="width:20px!IMPORTANT;" type="checkbox" name="CheckboxGroup2[]" value="NPA" id="NPA" />
<label style="margin-right: 25px;">NPA</label>
</p>
<p>
<input style="width:20px!IMPORTANT;" type="checkbox" name="CheckboxGroup2[]" value="Advertisement" id="advertisement" />
<label style="margin-right: 25px;">Advertisement</label>
</p>
<p>
<input style="width:20px!IMPORTANT;" type="checkbox" name="CheckboxGroup2[]" value="Brochure" id="brochure" />
<label style="margin-right: 25px;">Brochure</label>
</p>
<p>
<input style="width:20px!IMPORTANT;" type="checkbox" name="CheckboxGroup2[]" value="Show" id="show" />
<label style="margin-right: 25px;">Show</label>
</p>
<p>
<input style="width:20px!IMPORTANT;" type="checkbox" name="CheckboxGroup2[]" value="Other" id="other" />
<label style="margin-right: 25px;">Other</label>
</p>
</td>
</tr>
<tr>
<td>
<p>Please Specify:</p>
</td>
<td> </td>
<td colspan="2"><input type="text" name="specify" id="specify" /></td>
</tr>
</tbody>
</table>
<table border="0" style="float:left;margin-left:146px;" width="490">
<tbody>
<tr>
<td> </td>
<td>
<script type="text/javascript">
function validateCaptcha()
{
if ($('input[name="valid"]')) return true;
if ($('input[name="recaptcha_response_field"]').val() == "")
{
alert("Please complete the CAPTCHA field.");
return false
}
$.ajax({
url: "http://www.medilogicuk.com/wp-content/themes/default/verify.php",
type: "POST",
async:"false",
data: {
recaptcha_response_field: $('input[name="recaptcha_response_field"]').val(),
recaptcha_challenge_field: $('input[name="recaptcha_challenge_field"]').val()
},
success: function(data){
if (data == "OK")
{
$('input[name="valid"]').val(1);
$('.form').submit();
}
else
{
alert(data);
}
},
error: function(){
alert("An error occured, please try again later");
}
});
return false;
};
</script>
<?php require_once('recaptchalib.php');
$publickey = ""; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
</td>
</tr>
<tr>
<td colspan="2"><button type="submit" name="submit" value="Send message">Send message</button></td>
</tr>
</tbody>
</table>
<? if(isset($_POST['submit'])) {
$to = "rob#domain.com";
$header = 'From: info#domain.com';
$subject = "Website enquiry";
$companyname_field = $_POST['companyname'];
$fullname_field = $_POST['fullname'];
$email_field = $_POST['email'];
$tel_field = $_POST['tel'];
$address_field = $_POST['address'];
$specify_field = $_POST['specify'];
$CheckboxGroup1 = $_POST['CheckboxGroup1'];
$CheckboxGroup2 = $_POST['CheckboxGroup2'];
if( is_array($_POST['CheckboxGroup1']) ){
foreach ($_POST['CheckboxGroup1'] as $val) {
$checkbox1results .= $val.", ";
}
}
if( is_array($_POST['CheckboxGroup2']) ){
foreach ($_POST['CheckboxGroup2'] as $val) {
$checkbox2results .= $val.", ";
}
}
$body = "Hello,\n\n You have an enquiry from the website, please see the details below:\n\n Name: $fullname_field\n Company Name: $companyname_field\n E-Mail: $email_field\n Tel: $tel_field\n Method of contact: $checkbox1results\n Address: $address_field\n Hear about us?: $checkbox2results\n Specify: $specify_field\n\n Please reply to the enquiry asap.\n\n Kind Regards \n The website";
mail($to, $subject, $body, $header);
echo "</br><p style=\"color:#e41770!IMPORTANT;\">Thank you for getting in touch, we will contact you shortly.</p>";
} ?>
</form>
Okie a quick Example for you:
The Form
<html>
<body>
<form action="#" method="POST">
<input id="email" type="text" value="" />
<a id="submit" href="#">Submit Form</a>
</form>
</body>
</html>
The Jquery Part:
$(document).ready(function(){
$('a#submit').click(function(event){
event.preventDefault();
validateEmail();
})
});
function validateEmail(){
//declarations
rule = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
//check
if ($('input#email').val() === '' || !rule.test($('input#email').val())){
alert ('That is not a Valid Email Address !');
return false;
} else {
alert('validation passed! Submit the form !');
//submit the form action here
}
}
Also you can try it live here http://jsfiddle.net/XMbEK/
You already have your answer in the code:
<script type="text/javascript">
function validateCaptcha()
{
if ($('input[name="valid"]')) return true;
if ($('input[name="recaptcha_response_field"]').val() == "")
{
alert("Please complete the CAPTCHA field.");
return false
}
Add your own needs after this:
if ( phone == 'what it needs to be' )
{
if( email == 'asdasd' ) {
// all is good
} else {
alert( 'need email too' );
}
return true;
}
else
{
alert('Blah blah wrong phone');
return false;
}
etc.

Categories