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>
Related
The loop works fine, it display what it supposed to do, but there is a mysql update button of which updates only the first row value displayed:
$(document).ready(function() {
$("#update").click(function() {
var fname = $("#fname").val();
var lname = $("#lname").val();
var recordId = $("#recordId").val();
$.ajax({
url: 'update.php',
method: 'POST',
async: true,
data: {
fname: fname,
lname: lname,
recordId: recordId
},
success: function(response) {
alert(response);
}
});
});
});
<?php
$conn = new mysqli('localhost', 'root', '123456', 'lc');
$sql = "SELECT * FROM lc where customer='souhail'";
$result = $conn->query($sql);
// while ( $row=mysqli_fetch_assoc($result)) {
while($row = $result->fetch_array()) {
echo 'LC ID :<input type="text" id="fname" value="'.$row['element_6'].'"><br>';
echo 'Status :<input type="text" id="lname" value="'.$row['element_101'].'"><br>';
$recordId = $row['lc_id'];
echo '<input id="recordId" name="recordId" value="' . $recordId . '" >';
?>
<button type="button" style="background-color:<?php
if($row['element_101'] == '1'){
echo '#0000FFF';
}elseif ($row['element_101'] == '2'){
echo '#ffff00';
}elseif ($row['element_101'] == '3'){
echo '#00FF00';
}elseif ($row['element_101'] == '4'){
echo '#ffffff';
}
//echo $row['element_101'];
?>;color:#000000" id="update">Go Forward ></button>
<br><br>
<?php
} ?>
You must have unique IDs but instead wrap each set in a container and access relative tags:
$(".update").on("click", function() {
var $container = $(this).closest(".container");
var fname = $container.find(".fname").val();
var lname = $container.find(".lname").val();
var recordId = $container.find(".recordId").val();
$.ajax({
url: 'update.php',
method: 'POST',
data: {
fname: fname,
lname: lname,
recordId: recordId
},
success: function(response) {
alert(response);
},
error: function(xhr, textStatus, error) {
alert(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
Php
while($row = $result->fetch_array()) {
echo '<div class="container">
echo 'LC ID :<input type="text" class="fname" value="'.$row['element_6'].'"><br>';
echo 'Status :<input type="text" class="lname" value="'.$row['element_101'].'"><br>'; $recordId = $row['lc_id'];
echo '<input class="recordId" name="recordId" value="' . $recordId . '">';
echo '<button type="button" clsss="update">Go Forward ></button>';
echo '/div>';
} ?>
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/> ' + '<input name = "DynamicTextBox" type="text" value="' + value + '" required/> ' + '<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.
My Project Description
I'm making Attendance management system. requirement is as follows
1)First i need make a Schedule.
2)Select Schedule and Put attendance.
I'm getting following Values from schedule.php file
Array ( [schedulename] => Class for 1st year [subject] => Data Structure [university] => abc [facultyname] => Dr Rao [scheduleStartDate] => 2015-06-09 [scheduleEndDate] => 2015-06-18 [submit] => )
And My AddAttendance.php file as follows
<?php
require_once 'config/config.php';
//require_once 'config/session.php';
require_once 'class/dbclass.php';
require_once 'class/StuRegister.php';
$stu = new StuRegister();
$AllList = $stu->AllList();
?>
<!DOCTYPE html>
<html>
<head>
<?php require_once 'config/commonJS.php'; ?>
<script>
$(document).ready(function(){
$( "#date" ).datepicker({
currentText: "Now",
dateFormat: 'yy-mm-dd',
inline: true,
altField: '#datepicker_value',
onSelect: function(){
getData();
}
});
var myDate = new Date();
var prettyDate =myDate.getFullYear() +'-' + (myDate.getMonth()+1) + '-' + myDate.getDate();
$("#datepicker_value").val(prettyDate);
});
</script>
<script type="text/javascript">
function getData(){
//alert('Hi you have Selected Date');
var dt = $("#datepicker_value").val();
$.ajax({
type: "POST",
url: "process/processStuAttendance.php",
data: {type:'get',date:dt},
beforeSend : function () {
$('#wait').html("Loading");
},
success: function(resp){
var obj = jQuery.parseJSON(resp);
if(obj.sucess == 'new'){
$('.present').attr('checked',false);
}else{
$('.present').attr('checked',false);
$(obj.data).attr('checked',true);
}
},
error: function(e){
alet('Please Try again form not submit sucessful');
}
});
}
function setData(){
if(!$('#formSubmit').validationEngine('validate')){
}else{
//alert('Hi setDate called');
var absent = unCheckedStudent();
var formVal = $('#formSubmit').serialize();
if(absent != null){
formVal+="&absent="+absent;
}
$.ajax({
type: "POST",
url: "process/processStuAttendance.php",
data: formVal,
beforeSend : function () {
$('#wait').html("Loading");
},
success: function(resp){
alert('Sucessful'+resp);
},
error: function(e){
alet('Please Try again form not submit sucessful');
}
});
}
}
function unCheckedStudent(){
//alert('Hi unCheckedStudent called');
var ellength = document.formSubmit.elements.length;
var absent = new Array();
for(i=0;i<ellength;i++){
var type = document.formSubmit.elements[i].type;
var name = document.formSubmit.elements[i].name;
if (type=="checkbox" && name=="present[]" && document.formSubmit.elements[i].checked){
}
else if(type=="checkbox" && name=="present[]"){
absent.push(document.formSubmit.elements[i].value);
}
}
return absent;
}
</script>
</head>
<body>
<div id="content-wrap">
<div id="main">
<form name="formSubmit" class='form' id="formSubmit" method="post" >
<input type="hidden" name="type" value="<?php echo $sl_no == '' ? 'Add' : 'Update'; ?>">
<!-- <input type="text" onchange="getData(this.value)" class="validate[required]" readonly style="margin-left: 20px;" name="date" id="date" >-->
<input type="hidden" onchange="getData(this.value)" class="validate[required]" readonly style="margin-left: 20px;" name="date" id="datepicker_value" >
<div id="date" style="float: right;margin: 20px;"></div>
<br/>
<br/>
<div style="float: left;margin: 20px;">
<table width="500px" class="tbl">
<tr><th><b>Present</b></th><th><b>Name</b></th><th><b>University</b></th></tr>
<?php
for ($i = 0; $i < count($AllList); $i++) {
echo "<tr>";
echo "<td><input id='{$AllList[$i]['sl_no']}' type='checkbox' name='present[]' class='present' value='{$AllList[$i]['sl_no']}'></td>";
echo "<td>{$AllList[$i]['student_name']}</td>";
echo "<td>{$AllList[$i]['university']}</td>";
echo "</tr>";
}
?>
</table>
<input style="margin: 20px;cursor: pointer;" type="button" class="button" onclick="setData()" value="Save">
</div>
</form>
</div>
</div>
</body>
</html>
How can Make only scheduled dates are Enabled in datepicker, Any help may greatly appreciated.
What you need to do is to do this tricky 2 step
Step 1 :
List the Dates between your From and To Date by
<?php
$scheduleStartDate = '2015-06-09';
$scheduleEndDate = '2015-06-18';
$Date = getDatesFromRange($scheduleStartDate,$scheduleEndDate);
$Date = substr($Date, 0, -1);
function getDatesFromRange($start, $end){
$dates = array($start);
$Value = '';
while(end($dates) < $end)
{
$dates[] = date('Y-m-d', strtotime(end($dates).' +1 day'));
$Value .= '"'.date('j-n-Y', strtotime(end($dates).' +1 day')).'",';
}
return $Value;
}
?>
Step 2 :
Pass it inside the script that you have , $Date is the one you got from php
<script>
$( window ).load(function() {
var availableDates = [<?php echo $Date?>];
function available(date) {
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
if ($.inArray(dmy, availableDates) != -1) {
return [true, "","Available"];
} else {
return [false,"","unAvailable"];
}
}
$('#date').datepicker({ beforeShowDay: available });
});
</script>
So, Finally you can this code to enable the date you want ;)
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++)
I have a question about using ajax.I want to delete something of my screen (to be clear, some articles) I'm generating content (the articles) on the screen with this code:
while($test = $allArticles->fetch_assoc())
{
echo "<div class='metfoto'>";
echo "<h1 name='tt' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<form method='post' action=''>";
echo "<input type='submit' class='delete' name='verwijder' value='verwijder'>";
echo "</form>";
//echo "<h1>".$test['id']."</h1>";
echo "</div>";
}
This all is working very well without ajax. But I want to make this(the delete with the button) happen without a page refresh.
When i for example check the content of $test['id'], i receive one number. My problem with the code below is that when i want to put the title into variabel (var titel) for ajax, it loads all the titels from my page.
<script type="text/javascript">
$(document).ready(function(){
$(".delete").click(function(){
var titel = $(".titelopmaak").text();
var artikel = $(".artikelopmaak").text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$(".titelopmaak").fadeOut();
}
else
{
}
}
});
return false;
})
});
</script>
EDIT
I hope i explained my question in a better way now
Your problem is here
var titel = $(".titelopmaak").text();
You get all the values of the elements with class .titelopmaak but you only need one.
This is the correct one, we go up the tree and then find the item.
var titel = $(this).closest('.metfoto').find('.titelopmaak').text();
But, control elements by the title its very bad practice, use id instead of.
<script>
$(document).ready( function(){
$('.delete').submit( function() {
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
type: $(this).attr('method'),
success: function(data, status, jqXHR) {
$(".titelopmaak").fadeOut();
},
error: function(jqXHR, textStatus, errorThrown) {
}
);
});
});
</script>
<? while($test = $allArticles->fetch_assoc()) { ?>
<form method="POST" action="" class="delete">
<input type="hidden" value="<?=$test['id']?>" name="delete">
<input type="submit" value='verwijder'>
</form>
<? } ?>
You can try like this....
You have to specify individual id for each html elements
while($test = $allArticles->fetch_assoc())
{
$cid = $test['id'];
echo "<div id='div$cid' class='metfoto'>";
echo "<h1 name='tt' id='h1$cid' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p id='para$cid' class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<input type='submit' class='delete' name='verwijder' id='verwijder$cid' onclick='deleteValue($cid);' value='verwijder'>";
echo "</div>";
}
javascript function
Refer the h1 and div by their ids.
<script type="text/javascript">
function deleteValue(cid)
{
var titel = $("#h1"+cid).text();
var artikel = $("#para"+cid).text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$("#h1"+cid).fadeOut();
}
else
{
}
}
});
return false;
})
}
</script>
deleteArticle.php
include "connection.php";
$title = $_POST['titelA'];
$ok = mysql_query("delete from yourtable where title='$title');
echo "your msg here";