I have here my Javascript code that adds dynamic textbox (row) my problem is how can I save the values from the dynamic textbox to database using PHP script? Hope you can help me guys.. Thanks!
<script type="text/JavaScript">
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
root.appendChild(cRow);
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
</script>
My HTML code:
<form method="POST" action="#"> <table width="1024" border="0" cellspacing="6" cellpadding="0"> <tr>
<td width="195"><div class="user"><input type="text" name="user_a" id="user" tabindex="6"/></div></td>
<td width="410"><div class="reported"><input type="text" name="user_b" id="reported" tabindex="7"/></div></td>
<td width="399"><div class="reported"><input type="text" name="user_c" id="reported" tabindex="8"/></div></td>
<td width="10"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td> </tr> </table> </form>
You have to use just name of the text box which is added by dynamically.
$('form').submit(function() {
var data=($(this).serialize());
return false;
});
This function get all the elements value and create one string which is store in data, now data will pass in ajax call.
$('form').submit(function() {
var data=($(this).serialize());
$.ajax({
type: "POST",
url: "your_some.php",
data: data,
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
<html>
<head>
<title>Dynamic Form</title>
<script language="javascript">
<?php $i = 1; ?>
function changeIt()
{
//alert(i);
//var i = 1;
my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext[<?php echo $i;?>]'><input type='text' name='mytext[<?php echo $i+1;?>]'><input type='text' name='mytext[<?php echo $i+2;?>]'><br>";
<?php $i = $i+3; ?>
}
</script>
</head>
<body>
<form name="form" action="http://localhost/try.php" method="post">
<!--<input type="text" name=t1>-->
<input type="button" value="test" onClick="changeIt()">
<div id="my_div"></div>
<p class="submit"><button type="submit">Register</button></p>
</body>
try.php(this is the file where you will be catching values and then inserting into sql
)
<?php
$var = $_POST['mytext'];
echo $var[1].$var[2];
?>
Related
i am taking the input from user and than showing the data and a button for confirmation after clicking the confirm button the data will be post to a php file but the data is in array i am handling that data with for each loop but it is giving me an error that invalid arguments supplied to for each loop i don't know why it is giving me an error.
here is html and ajax code.
<html>
<head><title>my jquery</title>
<script src="jquery-2.1.0.min.js"></script>
</head>
<body>
<button id="button">clickme</button>
Id:<input type="text" id="id" >
Name:<input type="text" id="name">
Message:<input type="text" id="message" >
Destination:<input type="text" id="destination" >
<button id="confirm" name="confirm">Confirm</button>
<div id="d">
<table id="t">
<tr>
<td>ID</td>
<td>Name</td>
<td>Message</td>
<td>Destination</td>
</tr>
</table>
</div>
<script type="text/javascript">
var arr = new Array();
$("#button").click(function(){
var id=$("#id").val();
var name=$("#name").val();
var message=$("#message").val();
var destination=$("#destination").val();
arr.push({id:id, name:name, msg:message, dest:destination});
for (var i=0; i<arr.length; i++){
//alert(arr.length);
var row="<tr><td>"+ arr[i].id +"</td><td>"+ arr[i].name +"</td><td>"+ arr[i].msg +"</td><td>"+ arr[i].dest +"</td></tr>";
}
$("#t").append(row);
});
$("#confirm").click(function(){
$.ajax({
type:"POST",
url:"ajax.php",
data:"data="+JSON.stringify(arr),
success: function(data){
alert(data);
}
});
});
</script>
</body>
And the php code is here.
please someone tell me why the for each loop is not working.
<?php
if(isset($_POST['data'])){
$yourdata = $_POST['data'];
foreach($yourdata as $data){
echo $data['id'];
}
var_dump($yourdata);
$yourdatas = json_decode($yourdata);
print_r($yourdata);
}
?>
Try this
data:{'data':JSON.stringify(arr)}
and in your php
$data=json_decode(filter_input(INPUT_POST, "data"));
I hope this helps you.
Try this,
data: {'yourdata':JSON.stringify(arr)},
instead of
data:"data="+arr,
in your php page,
<?php
$yourdata = $_POST['yourdata'];
$yourdatas = json_decode($yourdata);
var_dump($yourdatas);
?>
I have a simple ajax (jquery version) script and very short php function and they works fine without problem.
When I submit the value from the form input are, the ajax will work to send and get result from
the php script, in this case to get a total amount of the book order.
The Ajax script and html section are as follows:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get field value
var qtyVal = $('#qty').val();
// use HTTP GET get ajax
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
//get xml value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
<body>
Total price:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<form>
<p>
<label>quantity: </label>
<input type="text" id="qty" name="qty"/>
<br/>
<input type="submit" value="submit">
total price:</p>
<p> </p>
</form>
And the following php script serving as xml also works fine with above ajax request:
<?php
// XML document
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
echo "<?xml version=\"1.0\" ?>";
echo "<datetime>";
echo "<qty>" . $qty*100 . "</qty>";
$total=$qty*100;
if ($total==0)
echo "<caution>"."please input number!"."</caution>";
else if ($total<=500)
echo "<caution>"."you shoud buy more!"."</caution>";
echo "";
echo "</datetime>";
?>
However when I combine the above scripts with my shopping cart foreach loops, it doesn't work and the ajax script failed to get variables from the form input area. I don't know if it is a variable scope issue (globals or local)? or anything else?
The following is the total script I would like to fixed with:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get value from the form
var qtyVal = $('#qty').val();
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<table border="1" align="center">
<tr>
<th>no</th>
<th>name</th>
<th>price</th>
<th>qty</th>
<th>update</th>
</tr>
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<form action="sessionCartUpdate.php">
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" id="qty" name="qty" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="submit" name="qty"
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
</form>
<?php
}
?>
<tr><td colsan="5">total amount:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div></td></td>
</table>
<p>continue to shop
<p>Put your order
</body>
</html>
I would be very grateful if anyone can offer kind or possible suggestion or advice?
My goal is to put different number (variables) in the "input area" (name or id as "qty") throught the using of ajax to get a total amount of price and show the result in the div box (id="result" or "result1").
You should replace the id attribute with class because id is supposed to be unique in the dom and using class you can do a loop to get all quantities of the items in the cart
Another thing i have noticed that you have made the an individual form foreach item in the cart there should be one form having the multiple fields,also remove this line <input type="submit" name="qty" it doesent makes sense
<form action="sessionCartUpdate.php">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
<?php
}
?>
</form>
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
var qtyVal =0;
$( ".qty" ).each(function() {
qtyVal =qtyVal + parseInt($(this).val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
Instead of using both $_GET and $_POST, you can use $_REQUEST which will give data from either POST or GET.
The following code is used for getting two values from two textboxes , calculate the sum using javascript and display the result in third textbox. When I click the button, I just want these textbox values (both input and result) to be inserted into mysql database. I want to do this in the same page. How can I get the javascript values to php for inserting them into database? It would be great if you could help.
Thanks
Jeny
Code:
<html>
<head>
<script language="javascript">
function getText3()
{
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
document.getElementById('in3').value=in3;
}
</script>
</head>
<body>
<form>
<table width="306" border="0">
<tr>
<td width="146">Enter A </td>
<td width="144"><input name="text" type="text" id="in1"/></td>
</tr>
<tr>
<td>Enter B </td>
<td><input name="text2" type="text" id="in2"/></td>
</tr>
<tr>
<td height="41" colspan="2"> <center>
<button type="button" onclick="getText3()"> Get calculated result</button></center> </td>
</tr>
<tr>
<td><strong>RESULT</strong></td>
<td><input name="text3" type="text" id="in3"/></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>
For this you should use jQuery (http://jquery.com/)
Just send them to your php file like the following:
// JS:
var in1 = $('#in1').val();
var in2 = $('#in2').val();
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
$('#in3').val( in3 );
$.post('file.php', { one: in1, two: in2, three: in3 }, function(data) {
alert( data );
} )
PHP file get's them as normal POST params:
// file.php
echo $_POST['one'] . " + " . $_POST['two'] . " = " . $_POST['three'];
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script language="javascript">
function getText3()
{
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
document.getElementById('in3').value=in3;
$.ajax({
type: "POST",
url: "your_php_file_path.php",//you can get this values from php using $_POST['n1'], $_POST['n2'] and $_POST['add']
data: { n1: in1, n2: in2, add: in3 }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
You can Pass the JavaScript Values to a HIDDEN Value in FORM and then POST the form to the PHP Page. Below is an example of how to set hidden value.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function setPrice(el){
var prices=[30, 20, 10];
var p=el.options.selectedIndex;
el.form.elements['price'].value=prices[p];
}
</script>
</head>
<body>
<form>
<select name="category" onchange="setPrice(this);">
<option value="men">
Men
</option>
<option value="women">
Women
</option>
<option value="under18">
Under 18's
</option>
</select>
<input name="price" type="hidden" value="30">
</form>
</body>
</html>
Hope this will help you!
I'm new to jQuery and I keep getting undefined as data when I submit the form. I looked online and tried serialize(), the $.ajax function, $.post function, amongst other methods to no avail.
I'm trying to accomplish a form submit without a page refresh. The code works fine if I comment out the script to remain on the page after form submission.
index2.php
<script>
function newlock() {
$("#new-lock").load("new-lock.php");
}
</script>
<h3>Lock Settings</h3>
<div>
New Lock
</div>
//code in between
<div id="tabs-1">
<div id="new-lock"></div>
</div>
insert_new_lock.php
require "connect.php";
$name = $_POST['name'];
echo $name;
$IP = $_POST['IP'];
echo $name;
$sql="INSERT INTO door_lock (lock_IP, lock_name)
VALUES
('$name','$IP')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
mysql_close($conn);
?>
new-lock.php
<!doctype html>
<html lang="us">
<h2 align = "center"> Please enter information for the new lock </h2>
<table border="0" align= "center">
<form id="newlockform" action="insert_new_lock.php" method="post">
<tr><td>Lock Name:</td> <td><input type="text" name="name"></td></tr>
<tr><td>Lock IP:</td> <td><input type="text" name="IP"></td></tr>
<tr><td><input type="reset" value="Clear"> <input type="submit" name="submitted" value="Submit"></td></tr>
</form>
</table>
</html>
<script>
$("#newlockform").submit(function() {
var name = $("#name").val();
var IP = $("#IP").val();
var dataString = 'name=' + name + '&IP=' +IP;
$.post('insert_new_lock.php', dataString, function(data) {
$("#tabs-1").html(data).fadeIn('100');
$('#name,#IP').val('');
}, 'text');
return false;
});
</script>
Any help would be appreciated! :D
You do not have any id set on your form fields, so
var name = $("#name").val();
is going to return null, which you then submit as an empty string. The form fields should loo like
<input type="text" name="whatever" id="name" />
^^^^^^^^^^^
for your JS code to work.
I am trying to update the database using jquery and ajax. A pop up window is opened for updating the fields. My problem is : the database is udapted fine but the values are not reflected on the web page without refreshing the page. I am using jquery .html() method to update the contents.
Please help me with the problem.
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript' src="js/jquery-1.5.1.min.js"></script>
<script type='text/javascript' src="js/jquery-ui-1.8.13.custom.min.js"></script>
<link rel='stylesheet' href="js/jquery-ui-1.8.13.custom.css" />
<script type='text/javascript'>
$(document).ready(function() {
$update_dialog = $("#update_dialog").dialog({
autoOpen:false,
title:"Update Sub Sub Section",
width: '600px',
modal:true,
buttons:[
{text: "Submit", click: function() { $('form',$(this)).submit(); }},
{text: "Cancel", click: function() { $(this).dialog("close"); }},
]
});
$("#update_dialog form").submit(function() {
var form = $(this);
alert($(this).serialize());
$.post($(this).attr('action'), $(this).serialize(),function(data) {
var getbook = $('#book_'+data.id);
$('.description',getbook).empty().html(data.description);
$("#update_dialog").dialog('close');
},'json');
return false;
});
function edit3_link_action() {
var getbook = $(this).closest('.book');
//get id from div
var id = getbook.attr('id').split('_');
id = id[id.length-1];
$('#update_dialog input[name="id"]').val(id);
$('#update_dialog textarea[name="description"]').val($('.description',getbook).html());
$update_dialog.dialog('open');
return false;
}
$(".edit3").click(edit3_link_action);
});
</script>
</head>
<body>
<div align="center">
<form name="userform" method="post">
<?php
$proposalid='P09-001';
$res=mysql_query("Select * from tblproposaldocsections where ProposalID='$proposalid' order by SortOrder;");
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_row($res);
if($row[1]!=$row[2])
{
$result=mysql_query("Select * from tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row[1]' order by SortOrder;");
for($k=0;$k<mysql_num_rows($result);$k++)
{
$row1=mysql_fetch_row($result);
$exp=explode('.',$row1[2]);
$alter=$row[2].'.'.$exp[1].'.'.$exp[2];
$result1=mysql_query("Select * from tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row1[2]' order by OrderID;");
$lastsortorder= mysql_query("SELECT Max(SortOrder) FROM tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row1[1]';")or die(mysql_error());
$rr = mysql_fetch_row($lastsortorder);
$lastsortorder = $rr[0];
if(mysql_num_rows($result1)>0)
{
?>
<br>
<?php
for($j=0;$j<mysql_num_rows($result1);$j++)
{
$row2=mysql_fetch_row($result1);
$exp=explode('.',$row2[2]);
$alter=$row[2].'.'.$exp[1].'.'.$exp[2].'.'.$exp[3];
$lastsortorder= mysql_query("SELECT Max(SortOrder) FROM tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row2[1]';")or die(mysql_error());
$rr = mysql_fetch_row($lastsortorder);
$lastsortorder = $rr[0];
?>
<div class='book' id='book_<?php echo $row2[2];?>'>
<h3 class="title"><?php echo $alter;?> subsubsection_<?php echo $row2[2];?></h3>
<p class='description'><?php echo $row2[3];?></p>
<a class="edit3" href="#">Edit</a>
</div>
<br>
<?php
}
?>
<br>
<?php
}
}
}
echo('<br>');
}
?>
</table>
</form>
</div>
<div id='update_dialog'>
<form action='edit.php' method='post'>
<table>
<tr>
<td align="left">Description:</td>
<td>
<textarea name='description' cols='60' rows='5'></textarea>
</td>
</tr>
</table>
<input type='hidden' name='id' />
<input type='hidden' name='proposalid' value="<?php echo $proposalid;?>" />
</form>
</div>
</body>
</html>
EDIT by blasteralfred
I used FireBug for debugging and the problem was the same as expected. DOM object is unable to read updated data. Is this declaration for getting the DOM element correct? This is the only problem !
var getbook = $('#book_'+data.id);
This is how the tag is declared:
<div class='book' id='book_<?php echo $row2[2];?>'>
<table width="80%" align="left">
<tr>
<td width="10%"><?php echo $alter;?></td>
<td width="70%" class="description"><?php echo $row2[3];?></td>
<td width="10%" align="center"><a class="edit" href="#">Edit</a></td>
</tr>
</table>
</div>
If your .html() isn't working, its either because the element you're using it on isn't there or the value you're trying to set isn't defined.
You can figure out what's up by checking if the given element and the value are defined prior to the .html() call. I'd recommend FireBug for debugging, but this can also be done simply by alert()ing the element and the value..