jQuery .html() method does not update the HTML data - php

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..

Related

php foreach -> Get corresponding data with js

I have a blog and get data from some SQL-database.
I have a problem to get correct data from a foreach loop and i don't know why. I will try to explain.
For each image there is a textarea where users can put in a comment. For each comment i have to send the corresponding id (ajax) to add to the database.
foreach($db->query("SELECT id, image FROM news") as $row)
{
<a href='images/news/{$row['image']}'><img src='images/news/{$row['image']}'/></a>";
<div class="save_comment">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>
<input type="text" class="_comment_id" name="id" value="<?php print_r($row['id'] );?>" />
Comment:
<textarea id="_comment_text" class="comment_area" name="comment_area" maxlength="400" cols="80" rows="8" ></textarea>
</td>
</tr>
<tr>
<td>
<a class="post_comment" href=".popupContainer">Post Comment</a>
</td>
</tr>
</table>
</div>
}
On click on "Post Comment" following js-script will be initialised....
<script type="text/javascript">
jQuery(document).ready(function() {
$(".post_comment").leanModal({top : 200, overlay : 0.6, closeButton: ".modal_close" });
$(function(){
jQuery('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
jQuery('.tabs ' + currentAttrValue).show().siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});
});
</script>
....and a popup Container (div with class .popupContainer) is shown, where users can finally submit their comment.
<div class="popupContainer" style="display:none;">
Your Name: <input type="text" class="_user_name" />
Email:<input type="text" class="_comment_email" />
<input type='button' class='_submit_comment' value='Speichern' >
</div>
By submitting this comment, following script is initialised and data will be sent by ajax.
<script type="text/javascript">
$("._submit_comment").click(function(){
var parentObj = $(this).closest('.save_comment');
var _comment_id = parentObj.find('._comment_id').val(); -> I don't get the correct id
So here begins the problem. I only get the first id from the foreach-loop, but i need to get for every comment the corresponding id. Can anybody help with this problem?
Thank you
Misch
This part is wrong IMHO :
$(this).closest('.save_comment');
You should set a JS variable when you click on "Post Comment" with the id that you can store in the link like :
<a class="post_comment" href=".popupContainer" data-idcomment="<?php print($row['id'] );?>">Post Comment</a>
And
var _comment_id = null;
jQuery('.tabs .tab-links a').on('click', function(e) {
_comment_id = jQuery(this).data('idcomment');
var currentAttrValue = jQuery(this).attr('href');
jQuery('.tabs ' + currentAttrValue).show().siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});
});
Then you can use _comment_id for you ajax call

Dynamic Input error within tables or divs

Can somebody please explain why this code does not allow my imploded variable separated by commas does not work when I surround it in a table or many div format.
The code works when I remove it from within the table. I also tested it with elements of the form within other divs and that failed to. It only works when its a HTML form on its own.
Summary: I want engineers output like. john,derek,peter et al.... At the moment it only gives my the top line
<?php
$eng = array();
$test = $_POST['test'];
$eng = implode(',',$_POST['engineers']);
?>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script>
$(document).ready(function(){
//when the Add Filed button is clicked
$("#add").click(function (e) {
//Append a new row of code to the "#items" div
$("#items").append('<div><input type="text" name="engineers[]"><button class="delete">Delete</button></div>');
});
$("body").on("click", ".delete", function (e) {
$(this).parent("div").remove();
});
});
</script>
</head>
<body>
<?php echo $eng; ?>
<div class="form_table">
<table>
<form method="post">
<tr><th><label for="engineers">Engineers</label></th><td>
<button type="button" id="add">Add Another Engineer</button>
<div id="items">
<div><input type="text" name="engineers[]"></div>
</div>
</td></tr>
<tr><th colspan="2"><input type="submit" name="" value="Add Job" class="submit" /></th></tr>
</form></table>
</body>
</html>
One thing to point out is that always process form input when the form is submitted.
And your markup is a little bit wrong, its the other way around. The table must be inside the form.
<?php
// handle form inputs when the form is submitted
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$eng = implode(',', array_filter($_POST['engineers']));
echo $eng;
}
?>
<div class="form_table">
<!-- form must wrap the table -->
<form method="POST">
<table>
<tr>
<th><label for="engineers">Engineers</label></th>
<td>
<button type="button" id="add">Add Another Engineer</button>
<div id="items">
<div><input type="text" name="engineers[]" /></div>
</div>
</td>
</tr>
<tr>
<th colspan="2">
<input type="submit" name="" value="Add Job" class="submit" />
</th>
</tr>
</table>
</form>
</div>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script>
$(document).ready(function(){
//when the Add Filed button is clicked
$("#add").click(function (e) {
//Append a new row of code to the "#items" div
$("#items").append('<div><input type="text" name="engineers[]"> <button class="delete">Delete</button></div>');
});
$("body").on("click", ".delete", function (e) {
$(this).parent("div").remove();
});
});
</script>
Sample Output
put your form outside the table becase table tag can include tr tags not form tag
Ex:
<?php
$eng = array();
$test = $_POST['test'];
$eng = implode(',',$_POST['engineers']);
?>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script> $(document).ready(function(){
//when the Add Filed button is clicked
$("#add").click(function (e) {
//Append a new row of code to the "#items" div
$("#items").append('<div><input type="text" name="engineers[]">
<button class="delete">Delete</button></div>');
});
$("body").on("click", ".delete", function (e) {
$(this).parent("div").remove();
});
});
</script>
</head>
<body><?php
echo $eng;
?>
<div class="form_table">
<form method="post">
<table>
<tr><th><label for="engineers">Engineers</label></th><td>
<button type="button" id="add">Add Another Engineer</button>
<div id="items">
<div><input type="text" name="engineers[]"></div>
</div>
</td></tr>
<tr><th colspan="2"><input type="submit" name="" value="Add Job" class="submit" /></th></tr>
</table>
</form>

Returning a value from popup window using php and javascript

I am trying to create a popup page from a parent page, which will return a value to the parent page and will close eventually.
What I have done so far:
main.php:
<tr>
<th>Project Name</th>
<td><input type="text" name="project_name" id="pid" disabled="disabled" />
<input type="button" name="choice" onClick="selectValue('id')" value="?"></td>
</tr>
<head>
<script type="text/javascript">
function selectValue(pid){
// open popup window and pass field id
window.open('search_project.php?id=' + encodeURIComponent(pid),'popuppage',
'width=400,toolbar=1,resizable=1,scrollbars=yes,height=400,top=100,left=100');
}
function updateValue(pid, value){
// this gets called from the popup window and updates the field with a new value
document.getElementById(pid).value = value;
}
</script>
</head>
search_project.php:
<head>
<script>
function closeWin(){
myWindow.close();
}
</script>
<script type="text/javascript">
function sendValue(value)
{
var parentId = <?php echo json_encode($_GET['id']); ?>;
window.opener.updateValue(parentId, value);
window.close();
}
</script>
<?php
$sql = mysql_query("SELECT project_id from prjct where project_id like 'default'");
$num = mysql_num_rows($sql);
<tr>
<td><input type="button" value="Select" onClick="sendValue('<?php echo $sql['project_id']; ?>')" /></td>
<td align="center"><? echo $sql['project_id']; ?></td>
</tr>
So, it is supposed to close the popup(search_project.php) and return the value of project_id in the input field of main.php. But, nothing is happening when I'm clicking on the select button. The popup doesn't close and the value is not returned. Seems sendValue(value) is not working.
Need help.
Do you really want encodeURIComponent(pid) here?
Try without encodeURIComponent:
window.open('search_project.php?id=pid','popuppage',
'width=400,toolbar=1,resizable=1,scrollbars=yes,height=400,top=100,left=100');

How to add dynamic textbox (row) and save to database using PHP

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];
?>

form doesn't get submitted on an auto refreshed page

I have web application in PHP and i need some variables in this page to get refreshed automatically. Therefore i have put that processing in another page - "test.php" - which gets loaded into this div every 10 seconds.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval( function ()
{
$('#refresh').load('test.php').fadeIn("slow");
}, 10000);
</script>
</head>
<body>
<div id="refresh">
</div>
</body></html>
The problem is that this page has a form which on clicking, doesn't not submit the values and do the processing as it is supposed to do. Without the auto refresh code, it works fine. How do i overcome this problem?
the test.php contains this form:
<form action="count.php" method="post">
<?php
$votes = getVoteCount($popular[$i][1]);
$voted=checkVoted($screenName,$id);?>
<td><img src="<?php echo $popular[$i][4]; ?>" width=60></td>
<td align="center"><CITE><?php echo "#".$username; ?></CITE>
<?php echo "<br >".$text.
"<br >".$votes." votes |";?>
<?php
if($screenName!=$username && $voted==false){
?>
<input type="hidden" name="addID" value="<?php echo $id;?>">
<input type="hidden" name="username" value="<?php echo $screenName;?>">
<INPUT TYPE="image" src="images/vote.png" name='vote' ALT="Submit Form" onMouseOver="this.src='images/vote_link.png'"
onMouseOut="this.src='images/vote.png'" width="35" height="20" title="Click to Vote!"></form>
<?php }else if($voted){ ?>
<img src="images/voted.png" width="35" height="20" title="You have already voted">
<?php } else{
echo "<img src='images/authored.png' width='40' height='20'>";
}?>
Because you're reloading the page with ajax requests you no longer can use
$("submit-button").click()
or
$("submit-button").submit();
You will need to use either jquery's live, delegate, or on to do this. (Live is no longer a recommended way of doing this.
$("body").on("click", "submit-button", function()
{
//execute code here
});
or
$("body").on("submit", "submit-form", function()
{
//execute code here
});

Categories