Adding data dynamically to HTML Table in PHP - javascript

I want to add data's from input fields to the HTML Table dynamically when clicking the Add button as shown in the sample image. How can I accomplish this? Can I do it with PHP? As I'm a
beginner I can't find the exactly matched results from here,
but I found a related thread, Creating a dynamic table using php based on users input data, but I think this process is done by 2 pages (1 page for inputs and another for showing that input data's in table) as per the code... Any help will appreciated.

Assuming you're using jquery (given your tag), something like the following will work:
$("button").click(function() {
var newRow = "<tr>";
$("form input").each(function() {
newRow += "<td>"+$(this).val()+"</td>";
});
newRow += "</tr>";
$("table").append(newRow);
});
There are better ways to do this, but this is probably a very simple place to start if you're just beginning to learn. The functions you should be interested in here are: .click, .each, .val, and .append. I'd recommend you check out the jquery docs - they will give you good examples to expand your knowledge.

If you can use jQuery you can do it like this. It's not the full code it's just to give you the idea how to start with it.
jQuery('#add').click(function(){
var memberName = jQuery('#memberName').val();
var address = jQuery('#address').val();
var designation = jQuery('#designation').val();
// Do some saving process first, using ajax and sending it to a php page on the server
// then make that php return something to validate if it's succesfully added or something
// before you show it on table. You can use ajax like
jQuery.ajax({
type: 'POST',
url: 'you php file url.php',
data: { name: memeberName, addr: address, desig: designation },
dataType: 'json', // any return type you like
succes: function(response){ // if php return a success state
jQuery('#tableID tbody').append('<tr><td>' + memberName + '</td><td>' + address + '</td><td>' + designation + '</td></tr>');
},
error: function(response){ // if error in the middle of the call
alert('Cant Add');
}
});
});
Be sure to change the id to the id you have in your html elements.
This is only on the front end side. If you have other processes like saving the newly added into the DB then you have to process that first before showing it on the table.

First, let's make this:
into table, like this:
<table id='mytable'>
<tr>
<tr>
<td>Member Name</td><td><input type="text" name="member[]"></td>
</tr>
<tr>
<td>Address</td><td><textarea></td>
</tr>
<tr>
<td>Designation</td><td>
<select>
<option value="asd">Asd</option>
<option value="sda">Sda</option>
</select></td>
</tr>
</tr>
</table>
<div>
<input name='buttonadd' type='button' id='add_table' value='Add'>
</div>
And add this javascript in head or body:
$("#add_table").click(function(){
$('#mytable tr').last().after('<tr><td>Member Name</td><td><input type="text" name="member[]"></td></tr><tr><td>Address</td><td><textarea></td></tr><tr><td>Designation</td><td><select><option value="asd">Asd</option><option value="sda">Sda</option></select></td></tr>');
});
Inside after(''); don't use enter, just type the code sideways.
Hope this can help you.

Ty jean for your instant reply..i tried that code, but i couldn't get +ve result,coz of my knowledge with javascript,jquery, etc are very poor.now my code is like this
so i expect you will help me coz of im just stepping into javascript and jquery.

$(document).ready(function()
{
$("#ser_itm").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
alert(dataString);
$.ajax
({
type: "POST",
url: "bar_pull.php",
data: dataString,
cache: false,
success: function(data)
{
$("#tbl").html(data);
}
});
});
});

Related

send jQuery generated table to another php page

In my project (some kind of online game store), i have a jQuery generated table from click on original table row. The original table is populated from mysql database. On submit i need to send that generated table to another php page. I'm quite new with it and so far this is my code:
on php_first.php
generated table
<form action="php_second.php" id ="form_send" name ="form_send1" method="POST">
<div>
<table id="generated_table" style="display:none" name ="generated_table1">
<tr><th>Game</th><th>Platform</th> <th>Genre</th> <th>Price</th><tr>
// generated rows here
</table>
<input type="submit" value="Confirm" id="btnOrder" style="display:none"></input>
</div>
</form>
generated rows
$(document).ready(function(){
$('#original_table tbody tr').click(function(){
var data = $(this).children("td").map(function(){
return $(this).text();
}).get();
var row= '<tr name ="new_row"><td name = "game">' + data[0] + '</td><td name = "platform">' + data[1] +
'</td><td name = "genre">' + data[2] + '</td><td name = "price">' + data[3] +
'<button type="button" onclick="remove(this)" class ="btn_remove">Remove</button>' +'</td></tr>';
$("#generated_table tbody").append(row);
$('#generated_table').show();
$('#btnConfirm').show();
});
ajax post to php_second.php
$('#btnOrder').click(function(){
var table= $('#generated_table');
$.ajax({
url: 'php_second.php',
type: 'POST',
data: {data: table},
async: false,
success: function(data){
alert(data);
}
});
However, ajax dosen't do alert(data) so i asume this is the problem but i cant determine it.
and on php_second.php
<table id="table_order" name = "table_order1" style="display:show">
<?php
if(isset($_POST['generated_table'])){
$table= $_POST['generated_table'];
echo $table;
}
?>
</table>
The problem is that i cannot post table data to another php (and print that table on other php when redirected). Tried to use ajax to send row data on row click, or passing div where table is but nothing. It shows no errors but no data is passed.
This is my first question so it is possible that i missed out some details to make the problem more clear. Thanks!
EDIT
I've tried Kalaikumar Thangasamy's code and ajax is working fine now, but the problem is on other php page.
<?php
if(isset($_POST['data'])){
$table = $_POST['data'];
echo $table;
}
else {
echo "None selected";
}
?>
The $_POST['data'] or any other parameter from first php is always null.
Change data: {data: table} to data: {'generated_table': escape(table)}. Posting data as but referring post data in $_POST['generated_table']. You suppose to be used $_POST['data']. Try this
var table= $('#generated_table').html();
$.ajax({
url: 'php_second.php',
type: 'POST',
data: {'generated_table': escape(table)},
async: false,
success: function(data){
alert(data);
}
});

C# send table cell data from one page to another

I have two pages customer.aspx and customer_detail.aspc, each with their corresponding code behind files. The objective is being able to send a particular table cells's value from customer to customer_detail. For example, the following javascript renders the table dynamically onto customer.aspx based on the BindTable method in customer.aspx.cs file.
customer.aspx:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "customer.aspx/BindCustomer",
data: "{}",
dataType: "json",
success: function(data) {
for (var i = 0; i < data.d.length; i++) {
$("#customer_table").append("<tr><td>"+'<a id = "anchor" href="customer_individual.aspx">' + data.d[i].customer_name +'</a>'+ "</td><td>" + data.d[i].customer_id +"</td><td>" + data.d[i].total_value + "</td><td>" + data.d[i].created_date + "</td></tr>");
}
},
error: function(result) {
alert("Error");
}
});
});
The BindCustomer function above is a WebMethod written in customer.aspx.cs, which returns a customer array object, customer[], which is bound to the customer_table. Notice that, in the above I have a href within the first td element of the table, which redirects the page to the customer_detail.aspx.
The objective is to be able to send say a customer_name value upon clicking the link to the customer_detail.aspx.cs, so that I can query the customer object which I store separately, with the name and populate the page accordingly. What would be the best method to accomplish this? Any suggestions as to how to proceed will be greatly helpful!
The easiest way is to format a link to customer_detail.aspx with the data you want to pass in the querystring like this (it looks very similar to what you're already doing.)
Link
When customer_detail.aspx loads, you retrieve the value from the querystring.
In your Page_Load event in customer_detail.aspx
var customerName = Request["customerName"];
You could be more particular and say Request.Querystring["customerName"] but on this page you probably don't care whether the value was passed in the querystring or a form field. Request["customerName"] covers both.

how to pass php value from one file to another through java script

I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}

Getting data wtith Ajax (Placing inside div)

I'm trying to add my data into a div, and its not working. The php is fine but I need a fine eye to see if they can spot any errors or can suggest any work arounds to help figure out why its not working.
I've tried to fix it for the past 5 hours or so and its racking my brains.
The user comments on a status like post and its suppose to add it to the div. Just like my main status does. The ajax for the main status is almost identical to the comment ajax below..yet the comment ahax isn't playing nice and is not inserting any data at all.
<script>
$(document).ready(function(){
$("form#mycommentform").submit(function() {
var streamidcontent = $('#streamidcontent').val();
var contents = $(this).children('#contents').val();
$.ajax({
type: "POST",
url: "comment_add.php",
cache: false,
dataType: "json",
data: { streamidcontent: streamidcontent, contents: contents},
success: function(data){
$('#containerid').html('<div class="stream_comment_holder" style="display:none;"
id="comment_holder_'+data['comment_streamitem']+'"><div
id="comment_list_'+data['comment_streamitem']+'"><div
id="tgy"></div><div class="stream_comment"
id="comment_'+data['comment_id']+'" style="margin-top:0px;"><table
width=100%><tr><td valign=top width=30px><img
class="stream_profileimage"
style="border:none;padding:0px;display:inline;" border=\"0\"
src=\"imgs/cropped'+data['id']+'.jpg\"
onerror="this.src=\"img/no_profile_img.jpeg\"" width=\"40\"
height=\"40\" ></a><td valign=top align=left>'+data['first']+'<div
class="commentholder">'+data['first']+'</div><br/><div
id="commentactivitycontainer"></div></div></table></div></div><div
class="form"><form id="mycommentform" method="POST"
class="form_statusinput"><input type="hidden" name="streamidcontent"
id="streamidcontent" value="'+data['comment_streamitem']+'"><input
type="text" name"contents" id="contents" placeholder="Say something"
autocomplete="off"><input type="submit" id="button"
value="Feed"></form></div><div class="stream_comment_holder"
style="display:;"><div class="like_name"><b><a
href="profile.php?username='+data['username']+'">You Like
This</a></b></div></div>');
}
});
return false
});
});
</script>
ERROR FOUND
success: function (data) {
alert("SUCCESS!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
alert(xhr.status);
alert(thrownError);
}
OK
200
SyntaxError.JSONparse:Unexpectedcharacter
JSON
$json = array();
$check = "SELECT comment_id, comment_datetime, comment_streamitem FROM streamdata_comments WHERE comment_streamitem=".$_POST['streamidcontent']."";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
mysqli_free_result($check1);
$check = "SELECT * FROM users WHERE id=".$_SESSION['id']."";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
mysqli_free_result($check1);
echo json_encode($json);
I would recommend using some sort of templating system to do all the hard work assembling your content.
Take a look into Create a makeshift Javascript templating or John Resig's solution.
Building that string of mark-up inside html() is a little crude.
You also have an inline style of display:none on the first div, so you won't see it.
Have you tried stripping the function down just to see if anything gets populated
success: function(data){
$('#containerid').html('blurb');
}
I don't know if this is the only problem, but where you're trying to embed quotation marks inside the html attributes that you're creating, e.g.:
'onerror="this.src=\"img/no_profile_img.jpeg\""'
It will produce this invalid string:
onerror="this.src="img/no_profile_img.jpeg""
You should embed single quotes instead, like this:
'onerror="this.src=\'img/no_profile_img.jpeg\'"'
Which would produce:
onerror="this.src='img/no_profile_img.jpeg'"
Also, on about the sixth last line you have an attribute missing an = sign:
name"contents"
And the outer-most div you are inserting has style="display:none;".

Assigning selectors to variables to call them depending on the type of button

Thats the best description I could think of. I normally do not post, but I honestly cannot figure this out.
Still in jquery learning mode, and basically what I want to accomplish is that depending on the type of button that is submitted, the script assigns variables to div's on the page. What I am making is a admin side of a user script to allow them to update that particular div that appears on the page.
When I put in the actual selectors, the script works.
When the page loads, it will take the field of the database that corresponds with the and load it. Once they push the update button, a new div will appear. The admin inputs his new data (the new information he wants to display) and it updates the mysql table, then pulls it back in through jquery's ajax.
Sorry for the long explanation. Like I said, I've never really posted, just always liked figuring it out on my own.
php page
<?php //
if(isLoggedIn())
{
echo '<button id="adultClassButton">Edit Class Information</button>';
}
?>
<div class="class" id="adultClass"><?php
$row = checkPost('adult');
echo $row['info'];
?>
</div>
<?php
echo '<div id="adultClassInput">
<textarea rows="2" cols="80" id="adultClassUpdate"></textarea>
<input type="hidden" id="className" name="adult"/>
<button id="adult">Save the Updated Class Info</button></div>';
?>
javascript (jquery) file
$(".button").click(function(){
var button = $(this).attr('id');
if (button == 'adult'){
var classDiv = $("#adultClass");
var className = $("#className");
var classDesc = $("#adultClassUpdate").val();
var classUpdateDiv = $("#adultClassInput");
postData(classDiv, className, classDesc, classUpdateDiv);
}
});
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: "name="+ className+ "& info="+ classDesc,
success:function(data){
$("#" + classDiv).html(data);
}
})
$("#" + classDesc).val('');
$("#" + classUpdateDiv).hide();
}
Like I said, if I have normal selectors in the function, it works as intended. But as of right now, I'm just stumped as to whats wrong.
Thanks a bunch!
classDiv is a jquery object not the ID of the element. So when you use this
$("#" + classDiv).html(data);
That's not working as expected.
Try
classDiv.html(data);
Your function should be like this:
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: {"name": className.val(), "info": classDesc}
success:function(data){
classDiv.html(data);
}
})
$("#"+classDesc).val('');
classUpdateDiv.hide();
}
because you already passed jquery objects (not strings) to your function, except for classDesc.
Hope this helps. Cheers

Categories