mysql insert array of js created textareas - php

I have a page where the user can add dynamically created textareas that are nested in divs.
I am trying to insert the added textareas
the problem i have is if I add 3 textareas and then remove the second one and then submit the amount of submitted textareas is 2 but the id of the two areas are 1 and 3 and when i try to add with a for loop the 2nd textarea has no value
how else can I insert into the db the posted text areas except with a for loop.
heres the code
php insert code:
<?
$page_ref="170";
$template_ref="15";
if($_SERVER['REQUEST_METHOD'] == "POST")
{
mysql_query("DELETE FROM site_content WHERE page_ref='$page_ref' AND template_ref='$template_ref' AND box_type='text'");
$q=count($_POST["textarea"])+1;
for($m=1; $m<$q;$m++)
{
$left=$_POST["left"][$m];
$top=$_POST["top"][$m];
$height=$_POST["height"][$m];
$width=$_POST["width"][$m];
$text=addslashes($_POST["textarea"][$m]);
$j=$m+1;
$drag_id++;
$box_type=$_POST['box_type'][$m];
$box_id=$_POST['id'][$m];
mysql_query("INSERT INTO site_content(page_ref, template_ref, content, box_id, box_type, box_top, box_left, box_width, box_height)VALUES('$page_ref','$template_ref','$text','$box_id','$box_type','$top','$left','$width','$height')");
}
}
?>
javascript:
function NewTextArea(id) {
id = id + i;
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.setAttribute('class', 'dragbox');
newdiv.setAttribute('iterate', i);
newdiv.style.position = "relative";
newdiv.style.top = p;
newdiv.style.left = p;
newdiv.style.cursor = 'move';
newdiv.innerHTML = "</div><br><textarea id='" + i + "' onDblClick='editor1(" + i + ")' name='textarea[" + i + "]' class='textarea1' style='position:absolute; top:10px;left:0px;overflow-y: auto;background-color:transparent;border: 1px solid #00FFFF; '>text here" + i + "</textarea>";
newdiv.innerHTML = newdiv.innerHTML + "<br><input type='hidden' value='" + i + "' name='id[" + i + "]'><br><input name='box_type[" + i + "]' type='hidden' value='text'/>";
newdiv.innerHTML = newdiv.innerHTML + "<br><input type='hidden' value='300' name='width[" + i + "]' id='width" + i + "'><br><input type='hidden' value='75' name='height[" + i + "]' id='height" + i + "'>";
newdiv.innerHTML = newdiv.innerHTML + "<br><input type='hidden' value='0' name='left[" + i + "]' id='left" + i + "'><br><input type='hidden' value='0' name='top[" + i + "]' id='top" + i + "'>";
document.getElementById("frmMain").appendChild(newdiv);
var but = document.createElement('input');
but.setAttribute('type', 'button');
but.setAttribute('class', 'removebutton');
but.style.visibility = "visible";
but.style.float = "right";
but.style.position = "absolute";
but.style.left = "300px";
but.style.top = "0px"
but.onclick = function () {
if (confirm('Really delete?')) {
document.getElementById("frmMain").removeChild(newdiv);
document.getElementById(id).removeChild(but);
document.getElementById(id).removeChild(newbr);
}
}
newbr = document.createElement('BR');
document.getElementById(id).appendChild(newbr);
document.getElementById(id).appendChild(but);
$(function() {
$("#" + i).resizable({
autoHide: true
})
$("#" + id).hover(function() {
$("#" + i).css('border', '1px solid #00FFFF');
});
$("#" + id).mouseleave(function() {
$("#" + i).css('border', '0px');
});
$("#" + i).resizable({
stop: function (event, ui) {
var width = ui.size.width;
var height = ui.size.height;
$("#" + id).find(".removebutton").css('left', +width + 'px');
// alert("width="+width+"height="+height);
ValProportions(width, height, ui.element.context.id);
}
});
$("#" + id).draggable({
stop: function(event, ui) {
Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: " + Stoppos.left + "\nTop: " + Stoppos.top);
// alert("left="+Stoppos.left+"top="+Stoppos.top);
ValPostion(Stoppos.left, Stoppos.top, $(this).attr('iterate'));
}
});
$("#" + i).draggable({
handle: "#handle"
});
});
function ValProportions(defaultwidth, defaultheight, id) {
$('#width' + id).val(defaultwidth);
$('#height' + id).val(defaultheight);
}
function ValPostion(defaultleft, defaulttop, id) {
$('#left' + id).val(defaultleft);
$('#top' + id).val(defaulttop);
}
p = p + 25;
i++;
$('.dragbox').click(function() {
$(".removebutton").css('visibility', 'hidden');
$("#" + i).css('border', '0px');
$(this).css('border', '1px solid #000');
$(this).css('background-color', 'red');
$(this).css('background-image', 'url(img/move.png)');
$(this).css('background-repeat', 'no-repeat');
$(this).css('width', '15px');
$(this).css('height', '15px');
$(this).find(".removebutton").css('visibility', 'visible');
$(this).find("#" + i).css('border', '1px solid #00FFFF');
});
$('.dragbox').focusout(function(e) {
$("#" + i).css('border', '0px');
$('.dragbox').css('background-color', 'transparent');
$('.dragbox').css('width', '0px');
$('.dragbox').css('border', '0px');
$(this).css('border', '0px');
$(this).css('background-color', 'transparent');
$(this).css('width', '0px');
});
}
html code:
<form id="frmMain" name="frmMain" enctype="multipart/form-data" action="dynamic_div5.php" method="post">
<input id="btn1" type="button" value="Add New textbox" onClick="NewTextArea('draggable');"/>
<input type="submit" value="Save Page" >
<div id="content">
<?
$sql=mysql_query("SELECT * FROM site_content WHERE page_ref='$page_ref' AND template_ref='$template_ref' ORDER BY box_id DESC");
$numrows=mysql_num_rows($sql);
while($row=mysql_fetch_array($sql))
{
?>
<script>OldTextArea('<? echo $row['box_id']; ?>','draggable','<? echo $row['box_top']; ?>','<? echo $row['box_left']; ?>','<? echo $row['box_width']; ?>','<? echo $row['box_height']; ?>','<? echo $row["content"]; ?>');</script>
<?
}
?>
</div>
</form>

The Easyway is create textareas as array
<textarea name="textarea[]"></textarea>
<textarea name="textarea[]"></textarea>
<textarea name="textarea[]"></textarea>
and in loop
<?php
foreach($_POST['textarea'] as $i => $value)
{
//Save Here
}
?>
and you will avoid missing textareas

Use this method:
<textarea name="somename[]"></textarea>
<textarea name="somename[]"></textarea>
<textarea name="somename[]"></textarea>
<textarea name="somename[]"></textarea>
and than in PHP you will have array:
$somename[0]; $somename[1]; $somename[2]; $somename[3]; ...
so, you must to change in your code (js)
newdiv.innerHTML = "</div><br><textarea id='"+i +"' onDblClick='editor1("+i+")' name='textarea[]' class='textarea1' style='position:absolute; top:10px;left:0px;overflow-y: auto;background-color:transparent;border: 1px solid #00FFFF; '>text here"+i+"</textarea>";
and (in PHP)
$q=count($_POST["textarea"]);
for($m=0; $m<$q;$m++)

Related

Save values of multiple text boxes using jquery and mysql

How to insert dynamically generated field values to backend using mysql.
Im trying to add rows with text box and drop down using jquery and auto saving
the field values at regular intervals.
So i need to fetch the ids of the textboxes and drop down, but currently i get the id of only the first text box and drop down.
$(function() {
$("#btnAdd").bind("click", function() {
AddControl();
});
$("#btnGet").bind("click", function() {
var values = "";
$("input[name=DynamicTextBox]").each(function() {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
var i = 1;
var Ids = [];
$('[id*=ddl]').each(function() {
$(this).attr("id", "ddl" + i);
Ids.push(i);
i++;
});
$('[id*=hfDDLId]').val(parseInt($('[id*=hfDDLId]').val()) - 1);
var resultIds = Ids.join(',');
$('[id*=hfDropDownIds]').val(resultIds);
});
});
function AddControl() {
var Id = parseInt($('[id*=hfDDLId]').val()) + 1;
var ddlId = "ddl" + (Id);
var div = $("<div />");
div.html(getDropDownList(ddlId, ddlId));
div.append(GetDynamicTextBox(''));
$("#TextBoxContainer").append(div);
$('[id*=hfDDLId]').val(Id);
var previousDropDownId = $('[id*=hfDropDownIds]').val();
if (previousDropDownId != '') {
$('[id*=hfDropDownIds]').val(previousDropDownId + ',' + Id);
} else {
$('[id*=hfDropDownIds]').val(Id);
}
return false;
}
function getDropDownList(name, id) {
var combo = $("<select></select>").attr("id", id).attr("name", name).attr("runat", "server").attr("class", "class").attr("required", "required");
combo.append("<option value=" + "" + ">" + "Select Category" + "</option>");
combo.append("<option value=" + "1" + ">" + "1" + "</option>");
combo.append("<option value=" + "2" + ">" + "2" + "</option>");
combo.append("<option value=" + "3" + ">" + "3" + "</option>");
return combo;
}
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" id="ingr_name" type="text" value = "' + value + '" required/>&nbsp' + '<input name = "DynamicTextBox" type="text" value="' + value + '" required/>&nbsp' + '<input type="button" value="Remove" class="remove" />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
<div>
<input id="btnAdd" type="button" value="Add" />
<br/>
<br/>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br/>
<input type="hidden" id="hfSelectedValue" runat="server" />
<input type="hidden" id="hfDropDownIds" value="" runat="server" />
<input id="btnGet" type="button" value="Get Values" />
<input type="hidden" id="hfDDLId" value="0" />
</div>
</form>
Code for inserting in the backend
Assunimg i have given the id for the text box as 'ingr_name' im posting the same as :
<?php
$con=mysqli_connect("localhost","root","pass","DB");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['txt_area']) && $_POST['txt_area'] != '') {
$ingr_name = mysqli_real_escape_string($con,$_POST['ingr_name']);
$qry = "Select count(*) as cnt from table";
$res = mysqli_query($con,$qry);
$row = mysqli_fetch_array($res);
if ($row['cnt'] == 0) {
$qry_ins = 'my insert query';
}
?>
#SachinSachin if you want to insert only one text box value try the below code
function insert_data(){
var url = "insert.php";
$.ajax({
url : url,
type: "POST",
data: $('#formid').serialize(),
success: function(data)
{
alert(data);
}
});
}
call this function on submit button and in insert.php you get the values using post method as usual and insert them in mysql. if it is success print echo "inserted"; else print echo "failed"; you will get this status in alert message in above insert_data() function. Here i assumed you are using php as backend if not use your language with same process.

JQuery table row deletion error

I'm new in jQuery and I'm working in jQuery table. When I added row 0, 1, and 2 and delete row 2, all is fine. The problem is when I delete row 0 or row 1. If I deleted row 0 then it's just return index row 1. When I deleted row 1 it's return index row 0.
jQuery(function () {
var i = -1;
function updateTotal() {
var total = 0;
$('.qty').each(function () {
var $this = $(this);
var qty = parseInt($this.val());
var index = $(this).prop('name').match(/\[(.*?)\]/)[1];
var price = $('input[name^=price]').eq(index).val();
var t = document.getElementById('tab');
var val1 = $(t.rows[parseInt(index)+1].cells[0]).text();
alert(index);
$.get('engine.php?kode='+val1+'&button=getStock' , function(data) {
if(qty > 0 && qty <= data) {
$('input[name^=sub]').eq(index).val(price*qty);
total += parseInt(price*qty);
}
else {
alert("wrong quantity");
$('.qty').eq(index).val("1");
$('input[name^=sub]').eq(index).val(price);
total = total+parseInt(price);
}
$('.total').text(total);
});
})
}
$('#tab').on('change', '.qty', function(){
updateTotal();
});
$('input[name=barcode]').keydown(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code==13) {
i = i+1;
var $this = $(this);
var code = $(".barcode").val();
$.get('engine.php?kode='+code +'&button=getData' , function(data) {
var arrayObj = JSON.parse(data);
var k=0;
var arr = [];
$.each(arrayObj , function(key, value) {
arr[k] = value;
k++;
});
var newRow = $("<tr align='center'><td class='code'>" + $this.val() + "</td>" +
"<td> "+arr[0]+" </td> <td> "+arr[1]+" </td> "+
" <td><input class='price' required type='text' name='price["+(i)+"]' size='10' maxlength='9' pattern='.{1,9}' value='"+arr[2]+"'> </td> <td class='stok'> "+arr[3]+" </td>"+
" <td> <input class='qty' required type='text' name='qty["+(i)+"]' size='3' maxlength='4' pattern='.{1,4}' value='1'> </td> "+
"<td><input type='text' name='sub["+(i)+"]' size='10' value='"+arr[2]+"' disabled></td>"+
"<td><a href='#' class='remove'><font color='0404B4'>Cancel</font></a></td>"+
"<input type='hidden' name='code[]' value='"+code+"'></tr>");
var row = $('#tab > tbody > tr').eq(i);
if (row.length) {
row.after(newRow);
} else {
$('#tab > tbody').append(newRow);
}
updateTotal();
});
return false;
}
});
$('#tab').on('click', '.remove', function(){
$(this).closest("tr").remove();
updateTotal();
});
});

populating a table in a jquery dialog with json results

When the user clicks on the button to view the comments, a jquery dialog opens with the list of comments. I can't quite figure out how to get the results to populate the table on success. I found some posts that said to use the .append (in my code) but it's not working for me and I'm not sure what I am missing.
PHP Code:
if(isset($_GET['parcel_id'])) {
$db = new ezSQL_mysql(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$comments = $db->get_results("SELECT * FROM comments where parcel_id=" . $_GET['parcel_id']);
if($comments != null) echo json_encode($comments);
/*foreach ($comments as $comment){
echo "<table><tr><td>" . $comment->date_created . "</td><td style=\"text-align:right;\">" . $comment->user_id . "</td></tr>";
echo "<tr><td colspan=\"2\">" . $comment->comment . "</td></tr></table>";
}*/
}
jQuery Code:
$('#ViewComments').click(function() {
$("#InsertComment").focus();
//view/add comments dialog
$( "#CommentsDialog" ).dialog({
height:320,
width: 500,
modal:true,
closeOnEscape:true,
buttons: [ { text: "Close", click: function() { $(this).dialog( "close" ); } } ]
});
var parcel_id = $('#ParcelId').val(parcel_id);
$.ajax({
url: "classes/get-comments.php?parcel_id=" + parcel_id,
type: "GET",
data: { parcel_id : parcel_id },
error: function(SMLHttpRequest, textStatus, errorThrown){
alert("An error has occurred making the request: " + errorThrown);
},
success: function(comments){
//do stuff here on success
//<div id="Comments"><table id="CommentResults">
var tr;
for(var i=0; i < comments.length; i++){
tr = $('<tr/>');
tr.append("<td>" + json[i].date_create + "</td>");
tr.append("<td style=\"text-align:right;\">" + json[i].user_id + "</td></tr>");
tr.append("<tr><td colspan=\"2\">" + json[i].comment + "</td>");
$('#CommentResults').append(tr);
}
}
});
});//end view comments click function
HTML:
<div id="CommentsDialog" title="Comments">
<div style="width:98%;height:75%; margin-bottom:5px; background-color: #fff; padding:5px;" id="Comments" name="Comments">
<table id="CommentResults" name="CommentResults"></table>
</div>
<input type="text" style="width:65%;margin-top:5px;" id="InsertComment" /> <input type="button" id="AddComment" value="Add Comment" class="floatRight" />
</form>
</div>

Jquery issue, have to double click for the toggle to occur, can you tell me why?

All else is working fine
jQuery:
$(".edit").click(function()
{
var user_id=$(this).attr('id');
var options = '';
$.getJSON("do_find_courses.php",{user_id:user_id}, function(data){
for (var i = 0; i < data.length; i++) {
if(data[i].optionDisplay=="No File Categories")
{
options = '<option disabled="disabled" selected="selected">No products</option>';
}
else
{
options +=' <input name="' + data[i].optionValue + '" type="checkbox" value="' + data[i].optionDisplay + '" />'+ data[i].optionDisplay +'<br>';
//options += '<option value="' + data[i].optionValue + '">' + data[i].optionDisplay + '</option>';
}
}
$("#chkbox"+user_id).slideToggle( "slow" ).html(options);
//$("#chkbox"+user_id).html(options);
});
return false;
});
php code generated for the a href
<?php
$get_students=mysql_query("SELECT user_id ,surname,name, admin FROM users WHERE users.admin=0 ORDER BY users.surname ASC") or die(mysql_error());
while($row=mysql_fetch_array($get_students))
{
echo'
<tr>
<td><h3>'.$row['surname'].'</h3></td>
<td>'.$row['name'].'</td>
<td><div id="chkbox'.$row['user_id'].'"></div></td>
<td>Delete
Edit</td>
</tr>';}
?>
$(document).ready(function{
$(".edit").unbind('click');
$(".edit").click(function(){ bla bla bla});
});

KCFinder image upload

I'm using the 'Choose an Image' option of KCFinder (seen here) and would like to know how/if I can have multiple image areas rather than just one?
Here is my html/php code with 3 instances of the image/upload area (wrapped in a 'form' and saved to the database on submit):
<label>Logo: </label><div class="image" onclick="openKCFinder(this)"><img src="'.$_POST['logo'].'" alt="" id="img" /></div>
<input type="hidden" name="logo" value="'.$_POST['logo'].'" id="image" /> <br />
<label>Header Image: </label><div class="image" onclick="openKCFinder(this)"><img src="'.$_POST['h_image'].'" alt="" id="img" /></div>
<input type="hidden" name="h_image" value="'.$_POST['h_image'].'" id="image" /> <br />
<label>Side Advert Image: </label><div class="image" onclick="openKCFinder(this)"><img src="'.$_POST['side_advert'].'" alt="" id="img" /></div>
<input type="hidden" name="side_advert" value="'.$_POST['side_advert'].'" id="image" /> <br />
Here is my code for opening the image uploader:
function openKCFinder(div) {
window.KCFinder = {
callBack: function(url) {
window.KCFinder = null;
div.innerHTML = '<div style="margin:5px">Loading...</div>';
var img = new Image();
img.src = url;
img.onload = function() {
div.innerHTML = '<img id="img" src="' + url + '" />';
$('#image').attr('value', url);
var img = document.getElementById('img');
var o_w = img.offsetWidth;
var o_h = img.offsetHeight;
var f_w = div.offsetWidth;
var f_h = div.offsetHeight;
if ((o_w > f_w) || (o_h > f_h)) {
if ((f_w / f_h) > (o_w / o_h))
f_w = parseInt((o_w * f_h) / o_h);
else if ((f_w / f_h) < (o_w / o_h))
f_h = parseInt((o_h * f_w) / o_w);
img.style.width = f_w + "px";
img.style.height = f_h + "px";
} else {
f_w = o_w;
f_h = o_h;
}
img.style.marginLeft = parseInt((div.offsetWidth - f_w) / 2) + 'px';
img.style.marginTop = parseInt((div.offsetHeight - f_h) / 2) + 'px';
img.style.visibility = "visible";
}
}
};
window.open('http://www.websitename/admin/ckeditor/kcfinder/browse.php?type=images&dir=images/public',
'kcfinder_image', 'status=0, toolbar=0, location=0, menubar=0, ' +
'directories=0, resizable=1, scrollbars=0, width=800, height=600'
);
}
How would you get it so that the image uploader works independantly for each image area? At the moment it will only add an image to the first image area as they are all using the same id's.
Not sure if I've explained this correctly but here goes... many thanks in advance, s.
I guess this will do (using jquery traversing to find img element):
function openKCFinder(div) {
window.KCFinder = {
callBack: function(url) {
div.innerHTML = '<div style="margin:5px">Loading...</div>';
var img = new Image();
img.src = url;
img.onload = function() {
var img = $(div).html('<img class="img" src="' + url + '" />').children('img').attr('value', url).get(0); // using jquery you can get the desirent img element:)
var o_w = img.offsetWidth;
var o_h = img.offsetHeight;
var f_w = div.offsetWidth;
var f_h = div.offsetHeight;
if ((o_w > f_w) || (o_h > f_h)) {
if ((f_w / f_h) > (o_w / o_h))
f_w = parseInt((o_w * f_h) / o_h);
else if ((f_w / f_h) < (o_w / o_h))
f_h = parseInt((o_h * f_w) / o_w);
img.style.width = f_w + "px";
img.style.height = f_h + "px";
} else {
f_w = o_w;
f_h = o_h;
}
img.style.marginLeft = parseInt((div.offsetWidth - f_w) / 2) + 'px';
img.style.marginTop = parseInt((div.offsetHeight - f_h) / 2) + 'px';
img.style.visibility = "visible";
}
}
};
window.open('http://www.websitename/admin/ckeditor/kcfinder/browse.php?type=images&dir=images/public',
'kcfinder_image', 'status=0, toolbar=0, location=0, menubar=0, ' +
'directories=0, resizable=1, scrollbars=0, width=800, height=600'
);
}

Categories