suh suh - 7 months ago 18
Javascript Question

How to update data and add data on the single save button in jQuery?

I am trying to add text to textboxes dynamically when I press an add button.
I have added code for adding/removing textboxes that saves values to the database and deletes from the database. On page load I have created a function called

showitem
which again creates textboxes dynamically and fills value to it.

Now my problem is when I update any textbox it should be updated in database and if I add any new textboxes that value should be added to database.

Here is my code:

<HTML>
<HEAD>
<style>
#frmAddHtml{border: #ccc 1px solid; width:550px; margin-left: 400px;}
.add_button{ margin-top:20px; margin-left:470px; padding:5px; }
#outer div{ margin-bottom:10px; border: #ccc 1px solid;padding: 5px; width:480px;margin-left: 20px;}
input[type="text"] {padding: 5px;border:#ccc 1px solid;margin: 0px 20px;width:180px;height: 20px; }
#save_button {padding: 5px;border:#ccc 1px solid;margin: 0px 20px;width:180px;height: 30px; margin-left: 180px; padding: 5px;}
</style>

<SCRIPT src="http://code.jquery.com/jquery-2.1.1.js"></SCRIPT>
<SCRIPT>
$(document).ready(function(){
showitem();

$('.add_button').click(function() {
var textHTML = '<div><input type="text" name="item_text1" value=""/><input type="text" name="item_text2" value=""/><a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="image/minus.png"/></a></div>';
// $('.item_text:last').clone().insertAfter('.item_text:last');
$('.outer').append(textHTML);
});

$('.outer').on('click', '.remove_button', function() {
$(this).parent('div').remove();
var item_id = $(this).parent('div').find('input[type="hidden"]').val();
$.ajax({
type : 'POST',
url : 'data.php',
data : "action=deleteitem&item_id="+item_id,
success : function(data) {
$("#msg").html(data);
}
});
});

// $(document).on("keyup", "input[type=text]", function(){
// var $textbox = $(this);
// var item_id = $(this).parent('div').find('input[type="hidden"]').val();
// alert($textbox.val());
// alert(item_id);
// });

$('#save_button').click(function (){
var x = [];
var inputEle = document.getElementsByName("item_text1");
for(var i = 0; i < inputEle.length; i++){
inputField1 = inputEle[i].value;
x.push(inputField1);
}
var y = [];
var inputEle1 = document.getElementsByName("item_text2");
for(var i = 0; i < inputEle1.length; i++){
inputField2 = inputEle1[i].value;
y.push(inputField2);
}
var a = [];
var addedEle = document.getElementsByClassName("textbox1");
for(var i = 0; i < addedEle.length; i++) {
addedfield=addedEle[i].value;
a.push(addedfield);
}
alert(a);
// $('input[type="hidden"]').each(function () {
// z.push($(this).val());
// });
// alert(z);

var data = {'first_array':JSON.stringify(x),'second_array':JSON.stringify(y),'action':"additem"};
$.ajax({
type : 'POST',
url : 'data.php',
data : data,
success : function(data) {
$("#msg").html(data);
$("#outer").empty();
showitem();
}
});
});
});

function showitem() {
$.ajax({
type : 'POST',
url : 'data.php',
data : "action=showitem",
success : function(data) {
var item = JSON.parse(data);
for (var i = 0; i < item.length; i++){
var textHTML='<div><input type="hidden" name="item_id[]" value="'+item[i].id+'"/><input type="text" id="textbox1" class="textbox1" name="item_text1[]" value="'+item[i].item_text1+'"/><input type="text" name="item_text2[]" value="'+item[i].item_text2+'"/><a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="image/minus.png"/></a></div>';
$('.outer').append(textHTML);
}
}
});
}
</SCRIPT>
</HEAD>
<BODY>
<form name="frmAddHtml" id="frmAddHtml" action="" method="post">
<p id="msg"></p>
<a href="#" class="add_button" title="Add field"><img src="image/pus1.png"/></a>
<div class="outer" id="outer">
<!--
<div class="item_text">
<input type="text" name="item_text1" value=""/>
<input type="text" name="item_text2" value=""/>
<a href="#" class="remove_button" title="Remove field"><img src="image/minus.png"/></a>
</div>
-->
</div>
<input type="button" id="save_button" class="button" value="Save">
</form>
</BODY>
</HTML>


And here is my
data.php
file:

<?php
if(!mysql_connect("localhost", "root", "1234")) {
die(' connection problem ! --> '.mysql_error());
}
if(!mysql_select_db("logindemo")) {
die('oops database selection problem ! --> '.mysql_error());
}
$x = 0;
$action = $_POST['action'];
if($action == "additem") {
$array1 = json_decode($_POST['first_array']);
$array2 = json_decode($_POST['second_array']);
foreach(array_combine($array1, $array2) as $key => $value) {
$query="INSERT INTO tbl_item(item_text1,item_text2) VALUES ('$key','$value')";
if(mysql_query($query)) {
$x++;
}
}
if($x >= 1) {
echo "".$x." data added";
} else {
echo "error";
}
} else if($action == "showitem") {
$query = "select * from tbl_item";
$stmt = mysql_query($query);
while($crow = mysql_fetch_array($stmt)) {
$resultset[] = $crow;
}
echo json_encode($resultset);
} else if($action == "deleteitem") {
$id = $_POST['item_id'];
$query = "delete from tbl_item where id=$id";
$stmt = mysql_query($query);
echo "deleted";
}


I want to save updated data plus new added data store in a single save button click.

Answer

There are two ways to do this functionality.

  1. Check the possiblity for deleting the field values from database and add new records always while editing.

  2. Use index as database id value for the input field when populating.

< input type="text" name="item_text1[1]" value="10"/>
< input type="text" name="item_text1[2]" value="345"/>
< input type="text" name="item_text1[2]" value="345"/>
.
.
.
.
< input type="text" name="item_text1[10]" value="787"/>

Keep a max_id as hidden field,

 <input type="hidden" name="max_id " value="10"/>

And for adding new record,

$('.add_button').click(function()
    {
         var count   =  $("#max_id").val()+1; 
         var textHTML = <input type="text" name="item_text1[count]" value=""/>'; 
         $('.outer').append(textHTML);
         $("#max_id").val(count);   }) 

Since databse id are the indexes of the item_text1 , you can check easily in server side whether its a new field or existing field.