Post form not working with jquery fields - php

i cant get the form to post the variables to another script using dynamic fields?
edit: the script creates a new row of input fields, but none of them manage to post variables to a php script.
jquery:
<script type="text/javascript">
$(function(){
var newRowNum = 2;
$('#addnew').click(function(){
// increment the counter
newRowNum += 1;
var addRow = $(this).parent().parent();
var newRow = addRow.clone();
$('input', addRow).val($(this).val());
$('name', addRow).val('os' + newRowNum);
$('td:last-child', newRow).html('<a href="" class="remove">Remove<\/a>');
$('input', newRow).each(function(i){
var newID = 'os' + newRowNum + i;
$(this).attr('id',newID).attr('name',newID);
});
addRow.before(newRow);
$('a.remove', newRow).click(function(){
$(this).parent().parent().remove();
return false;
});
return false;
});
});
html:
<tr>
<td>
<input name="os21" type="text" id="os21" value="" size="24" maxlength="60" /></td>
<td>
<input name="os22" type="text" id="os22" value="" size="24" maxlength="60" /></td>
<td>
<input name="os23" type="text" id="os23" value="" size="10" maxlength="60" /></td>
<td><a id="addnew" href="">Add +</a></td>
</tr>
<tr><td colspan="3" align="left" style="text-align: right; padding-top: 10px;">
<input type="submit" value="Update">
</td></tr>

<script language="text/javascript">
function postMyForm()
{
$.ajax({
url: "url from your file to post to",
data: $('#myForm').serialize(),
type: 'post',
success: function(data) {
// do stuff when request is done
}
});
}
function AddNewRule() {
// get last ID
// convert to a int to count with it
var LastID = parseInt( $('#myTable tr:last td input').attr('id').replace(/os/gi, '') );
// add 1 to get next ID
LastID += 1; // OR LastID = LastID + 1; what you wanna use
// create new rule and set the next ID
var newRule = $('<tr><td><input name="os'+ LastID +'" type="text" id="os'+ LastID +'" value="" size="10" maxlength="60" /></td></tr>');
// append / insert at the end of your table
$('#myTable').append(newRule);
}
</script>
<form id="myForm">
<table id="myTable">
<tr>
<td>
<input name="os21" type="text" id="os21" value="" size="24" maxlength="60" />
</td>
</tr>
<tr>
<td>
<input name="os22" type="text" id="os22" value="" size="24" maxlength="60" />
</td>
</tr>
<tr>
<td>
<input name="os23" type="text" id="os23" value="" size="10" maxlength="60" />
</td>
</tr>
</table>
<a id="addnew" onclick="AddNewRule();" href="javascript:void(0);">Add +</a>
<table>
<tr>
<td colspan="3" align="left" style="text-align: right; padding-top: 10px;">
<input type="submit" onclick="postMyForm();" value="Update">
</td>
</tr>
</table>
</form>

I don't see you initializing the variable i. We can't see all the source but I imagine this is probably the problem.

Input elements supposed to be inside element...

Why don't you just lose the counter and do it like this:
<input name="os[]" type="text" class="os" value="" size="24" maxlength="60" />
After you add rows dynamically you must bind('click') or just use live() method.

Related

save file names in database after uploading files

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

PHP grid/table Modal Popup Duplication

I am using PHP to create a grid/table for user entry and all works fine. The problem is that one of the text boxes has a modal popup with some additional information. It works fine if there is only 1 row, but when I add 2 or more, the Modal options are then posted above the table and the popup does not work.
Any ideas?
Javascript/Jquery
$(function () {
$("#MyDialog").dialog({
autoOpen: false,
height: 300,
width: 340,
modal: true,
buttons: {
"Save": function () {
$('#popup').val($('#year').val() + " " + $('#week').val() + " " + $('#day').val());
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
},
close: function () {
$('#year').val("");
$('#week').val("");
$('#day').val("");
}
});
$("#popup").click(function () {
$("#MyDialog").dialog("open");
});
});
PHP
$line = $_GET["Line"];
if($line == 0){$line=1;}
for($i=1;$i<=$line;$i++)
{
Code
<tr>
<td><div align="center"><input type="text" id="type" title="X1" name="txttypeofunit<?=$i;?>" size="12"></div></td>
<td><input type="text" id="description" title="X2" name="txtunitdescription<?=$i;?>" size="15"></td>
<td><input type="text" id="manu" title="X3" name="txtmanufacturer<?=$i;?>" size="12"></td>
<td><div align="center"><input type="text" id="model" title="X4<?=$i;?>" size="12"></div> </td>
<td align="right"><input type="text" id="serial" title="X4" name="txtserial<?=$i;?>" size="12"></td>
<td align="right"><input type="text" id="tags" title="X5" name="txtyearbuilt<?=$i;?>" size="12"></td>
<div id="MyDialog" title="Running Time Of Unit <?=$i;?>" >
Months a year? <input type="text" id="year" size="5" /> - M/Y <br>
Days a week? <input type="text" id="week" size="5" /> - D/W <br>
Hours a day? <input type="text" id="day" size="5" /> - H/D
</div>
<div>
<td align="right"><input type="text" id="popup" id="cool" title="How many months in a year is the unit in use? 1 - 12" size="12">
</div>
<td><input type="text" id="refig" title="X6" name="txtrefrigerationtype<?=$i;?>" size="12"></td>
<td><div align="center"><input type="number" id="input" title="X7"

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>

PHP jQuery with .change how can i combine both?

I have this codes with select name=client
with the help of jQuery i want to populate my textbox and other field.
this select helps me to change my client option.
so for example i click the select im going to choice the client B.
after that it will populate the text box and other fields. with the information came from database.
is my code correct, i post question here because i dont know why is my code not working.
my jQuery Codes
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
jQuery('select[name=client]').change(function(){
var com_code = jQuery(this).val();
<?
$getClient = "SELECT * FROM jon_com_for";
$getClient .= "WHERE com_code=";
$getClient .= "'com_code'";
$setClient = SET_SQL( $getClient );
?>
jQuery('input[name=com_code]').val( '<?=$setClient['com_code'];?>' );
jQuery('input[name=set]').val( '1' );
jQuery('input[name=company_name_for]').val( '<?=$setClient['company_name_for'];?>' );
jQuery('input[name=street_name]').val( '<?=$setClient['street_name'];?>' );
jQuery('input[name=post_code]').val( '<?=$setClient['post_code'];?>' );
jQuery('input[name=city]').val( '<?=$setClient['city'];?>' );
jQuery('input[name=country]').val( '<?=$setClient['country'];?>' );
});
});
</script>
my html code this html was inside of a dialog.
<div id="dialog" title="Step 1">
<form id="submit_steps" method="POST" action="new-template.php">
<input type="hidden" name="user_code" value="<?=$_SESSION['user_code'];?>" />
<input type="hidden" name="com_code" value="<?=comucode();?>" />
<input type="hidden" name="footnote" value="1" />
<input type="hidden" name="set" value="1" />
<div style="margin:20px auto;">
<label for="client">Selecteer klant : </label>
<select name="client">
<?php
$list_of_client = mysql_query( "SELECT * FROM jon_com_for" ) or die ( mysql_error() );
while( $row = mysql_fetch_array( $list_of_client ) ) {
echo '<option value="'.$row['com_code'].'">'.$row['company_name_for'].'</option>';
}
?>
</select>
</div>
<table cellpadding="3" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="right" valign="middle">BEDRIJFSNAAM :</td>
<td><input name="company_name_for" size="30" id="company_name_for" class="input" type="text" /></td>
</tr>
<tr>
<td align="right" valign="middle">ONDERWERP VAN OFFERTE :</td>
<td><input class="input" name="sub_quo" id="sub_quo" size="30" type="text" /></td>
</tr>
<tr>
<td align="right" valign="middle">STRAAT :</td>
<td><input class="input" name="street_name" id="street_name" size="30" type="text" /></td>
</tr>
<tr>
<td align="right" valign="middle">Postcode :</td>
<td><input class="input" name="post_code" id="post_code" size="30" type="text" /></td>
</tr>
<tr>
<td align="right" valign="middle">STAD :</td>
<td><input class="input" name="city" id="city" size="30" type="text" /></td>
</tr>
<tr>
<td align="right" valign="middle">LAND :</td>
<td><input class="input" name="country" id="country" size="30" type="text" /></td>
</tr>
</tbody>
</table>
<div align="center">
<input type="submit" name="save_client_prof" value="Opsslaan" /> or Annuleren</p>
</div>
</form>
</div>
is that correct i put the PHP inside jQuery?
im sorry codes updated
also my dialog is not working anymore.
here are the code that i had changed thank you all...
<script type="text/javascript">
$(function(){
$('select[name=clientx]').change(function(e){
$('<img src="images/ajax-loader.gif" id="loading" style="width:auto;" />').appendTo("#client_details");
//Cancel the link behavior
e.preventDefault();
//Get the A tag
var com_code = $('select[name=clientx]').val();
var dia = jQuery( 'input[name=dia]' ).val();
$.ajax({
type:"GET",
url:"forms/company.php",
data: {dia: dia, com_code: com_code},
dataType: 'html',
target: '#dialog',
success: function(data){
$("#client_details").find('img#loading').remove();
$("#client_details").html(data);
}
})
});
});
</script>
Putting PHP code inside a jQuery change event does not mean that the PHP code is run when the change event happens.
PHP code written this way runs only once, when the page is loaded. This means that it will never know what the com_code JS variable contains after the click.
In order to execute PHP code whenever the JS change event happens, you need to use a technique called Ajax. Your javascript code needs to make a call to an entirely separate PHP program that will query the data and return the results back to the browser for the javascript code to work with.
This technique is well established, and jQuery provides functions that make it very easy to use. Look up some jQuery Ajax examples, and follow them from there.
Hope that helps.

adding input box dynamically when filling the other input box

i have a form like this
<FORM method="post">
<TABLE>
<TR>
<TD>Username</TD>
<TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD>
</TR>
<TR>
<TD>Age</TD>
<TD><INPUT type="text" value="" name="username" title="Enter Age"/><TD>
</TR>
<TR>
<TD>City</TD>
<TD><INPUT type="text" value="" name="username" title="Enter City"/><TD>
</TR>
<TR>
<TD>Comment</TD>
<TD><INPUT type="text" value="" name="username" title="Enter Comment"/><TD>
</TR>
</TABLE>
</FORM>
what i want is when user after filling the comment box ,when they press enter then dynamically another input box has to display with comment label by using javascript.
can anyone help me to write the code...
Try this my friend:
<FORM method="post">
<TABLE>
<TR>
<TD>Username</TD>
<TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD>
</TR>
<TR>
<TD>Age</TD>
<TD><INPUT type="text" value="" name="age" title="Enter Age"/><TD>
</TR>
<TR>
<TD>City</TD>
<TD><INPUT type="text" value="" name="city" title="Enter City"/><TD>
</TR>
<TR>
<TD>Comment</TD>
<TD><INPUT class="comment" type="text" value="" name="comment[]" title="Enter Comment"/><TD>
</TR>
</TABLE>
</FORM>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(function(){
$('.comment').live('keydown', function(e){
$field = $(this);
// capture enter key being pressed
if (e.which == 13)
{
$html = $(this).parents('tr').clone();
$html.find('input').val('');
$html.appendTo($field.parents('table'));
}
});
});
</script>
First of all your all the input names in your form are the same (name="username"), you have to give each input a unique name.
so change comment input to
<TR id="comment">
<TD>Comment</TD>
<TD><INPUT type="text" value="" name="comment[]" title="Enter Comment"/><TD>
</TR>
note that i added id to the TR so it'll be easier to latch on to it using jquery and i also changed the input name to be comment[] since if you add a new comment to the dom you'll have a comment array.
if the new comment should have a new name like : 'comment2', you can change it to be just 'comment'
Now, using Jquery do the following:
$(document).keypress(function(e) {
//catch enter event
if(e.which == 13) {
var $comment = $('#comments);
//check that the user entered something in the comment input
if($comment.find('input').val().length > 0)
{
//create new comment element and attach it to DOM
var $newComment = $comment.clone().removeAttr('id');
$('form table').append($newComment);
}
}
});
let me know if that helped or if you need more info.

Categories