send jQuery generated table to another php page - javascript

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);
}
});

Related

binding an id passed through button to data in Jquery

I have a table with rows. In each row is a button that is specific to that row of data through the value of the data's id.
When a button in a specific row is clicked it fires the AJAX function 'options'. If that is successful then I want to append the data from $newElement to the row in which that button is located. The row is not always the same however so I cant just give it a tr#.
In the code below I have the append working with that data I want but it appends it to every row, not limited to the specific row and that button's id. What am I doing wrong?
AJAX/jQuery where I am appending the data from $newElement but am having trouble binding the id from the button. As a result it adds the data from $newElement to every row instead of ONLY the row in which I clicked the button.
function options(id){
jQuery.ajax({
type: 'post',url: my_ajax.ajax_url,
data: {action: 'options_function',cid : id_In},
success: function (data) {
var $id = id
var $newElement=jQuery("<tr>",
{id:'ideal_option'+id,html:data})
jQuery('#list-table tr').append($newElement)}
});
}
The button and its initial table are generated with a combo of jQuery and HTML. This function is launched on page load. :
function Pop(){ ?>
<script>
jQuery('document').ready(function(){
jQuery.ajax({ data: {action: 'list_ct'},
type: 'post', url: my_ajax.ajax_url,dataType: 'JSON', success: function(data) {
var lnth = data.length-1;jQuery.each( data, function( i, val ) {
console.log(val);
jQuery('<tr><td>'+val.Customer_FName+' '+val.Customer_LName+'<br></td><td class="tdid_'+val.id+'">'+val.Status+'</td><td><button id="options" href="javascript:void(0)" class="button" onclick="options('+val.id+')" data-id="'+val.id+'"></button></td></tr>');
});
}
});
});
</script>
<table id='list-header'>
<th>Name</th>
<tbody id='list-table'>
</tbody>
</table>
<?php
}

JavaScript function not posting

I have a javascript function that should remove a table row from a PHP page. My question is what am I missing to make this post to my PHP page.
the line clicked to do the remove
echo '<td align="right"><i class="glyphicon glyphicon-remove" id="abc" onClick="remove(id)"></i></td>';
the javascript:
function remove(id){
var rem = confirm('Are you sure you want to remove the id ' + id + '?');
if (rem == true){
alert(id); //just to see if my data is making it this far, it is
$.ajax({
data: 'id' + id,
url: 'pages/ini.php',
method: 'POST',
success: function(msg){
alert('Data entered!');
location.reload();
}
});
}
}
the php page:
$test = $_POST['id'];
But all that it is return is an empty value. I tried to display it and all I got was empty data, or when I'd do echo $test; Id get a blank page with no console errors
through $.ajax your request getting posted but your clicked "id" of element not getting passed because you have write
data: 'id' + id
instead of
data: {'id' : id }
This will actually send clicked element "id" to your PHP Code.
Hope, this will help you.

Unable to access AJAX Response Data through jQuery

I have searched and tried for hours but unsuccessful.
I have an existing page which displays simple data from DB using PHP in an HTML table. Now I want to implement AJAX functionality so that data is refreshed without page refresh.
I have implemented this solution, to my understanding, the AJAX call part is working and the values are getting refreshed as expected. but I am stuck in getting the values.
index.php (main page)
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
</script>
</head>
<body>
<h3>Output: </h3>
<table border="1" id="output"></table>
<script id="source" language="javascript" type="text/javascript">
$(function() {
update_content();
});
function update_content()
{
$.ajax({
url: 'query.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to query.php
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
if(data){
(data + '').length;
}
var temp = new Array();
$('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");
}
});
setTimeout(function(){
update_content();
}, 1000);
}
</script>
</body>
</html>
query.php (used for AJAX call)
<?php
include('inc/connection.php');
# Main query
$sql = "
select LastUpdated, symbol, sum
from TheTable
";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)){
$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);
}
echo json_encode($table_data);
?>
If I run query.php directly in the browser, I see all the data in this format:[{"LastUpdated":"20170614","symbol":"AUD","sum":"20"},{"LastUpdated":"20170614","symbol":"AUD","sum":"10"}]
But on my main page, I see undefined inside the table.
I'd ideally like to have all the values (using a JS loop in the above code may be) to display all the records fetched from DB (variable no. of records).
HINT/MODIFICATION
When I change:
$('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");
to
$('#output').html("<tr><td>"+data[0]+"</td></tr>");
in index.php
AND
$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);
to
$table_data[]=$row;
in query.php, then I get only first row as a string like
20170614,AUD,40.
END HINT/MODIFICATION
I am sorry if that's a silly question/problem. I am new to jQuery and trying AJAX for first time.
P.S. I know mysql_* functions are deprecated and I am aware of the vulnerability.
Your help would be highly appreciated.
When you update your data table you'll probably want to just rebuild the table. In your callback function, you need to loop through the array and add new rows to the table.
$.ajax({
url: 'query.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) {
if (!Array.isArray(data) || !data.length) {
return;
}
$("#output").empty(); //clear old table data
for(var i = 0, len = data.length; i < len; i++) {
$("#output").append(
"<tr><td>" + data[i].LastUpdated + "</td>" +
"<td>" + data[i].symbol + "</td></tr>" +
"<td>" + data[i].sum + "</td></tr>"
);
}
}
});
You have to change code as mentioned below.
From
data["symbol"]
to
data.symbol
Let me know if it not works.

Ajax success function only updating values for first click

Okay I have a html table given below:
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th colspan="2">Total</th>
</tr>
</thead>
<tbody id="cart_table">
...
</tbody>
<tfoot>
<tr>
<th colspan="2">Total</th>
<th colspan="2">$446.00</th>
</tr>
</tfoot>
</table>
I am using ajax to append values clear tbody at every click of a button and refill the tbody with multidimensional session array. It works fine for 1st turn, but does not work for 2nd click
My jquery code is given below
<script>
$(document).ready(function(){
$('.addToCart').on('click',function(e){
$("#cart_table").empty();
var price = $(this).attr('data-price');
var item = $(this).attr('data-itemname');
e.preventDefault();
$.ajax({
method : "POST",
async: false,
url: "./php/addToCart.php",
dataType : "json",
data : {item:item,price:price},
success : function(response){
$("#cart_table").empty();
<?php
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item):
$item = $each_item['item'];
$price=$each_item['price'];
$quantity=$each_item['quantity'];
?>
$('#cart_table').append("<tr><td><?php echo $item; ?></td><td><?php echo $quantity; ?></td><td><?php echo $price; ?></td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>");
<?php
endforeach;
?>
}
});
});
});
</script>
I have checked my session values are updated. However, the change is not shown on my table except for first click.
As pointed out in comments PHP is server side language, for it to reflect the changes, your page needs to reload but because you are using ajax page is not going to reload (Or rather we don't need it to reload).
It work for the first time because for the first time when page is loaded, the current data will already be present in your JavaScript function :
Right here :
$('#cart_table').append(<?php echo "<tr><td>".$item."</td><td>".$quantity."</td><td>".$price."</td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>";?>);
So what happens here is that when you click for the first time, your ajax will execute and success function is called, this function will add the already presented data because it will not update unless your page is reload. So every time you click, your session will be updated and success function is also called but your table will not reflect the changes.
So, You need to change your PHP code To JavaScript, Here the basic idea of what to do, (Here i have assumed your response is JSON, And also note that following code will not work out of the box because i didn't tested it.)
<script>
$(document).ready(function(){
$('.addToCart').on('click',function(e){
$("#cart_table").empty();
var price = $(this).attr('data-price');
var item = $(this).attr('data-itemname');
e.preventDefault();
$.ajax({
method : "POST",
async: false,
url: "./php/addToCart.php",
dataType : "json",
data : {item:item,price:price},
success : function(response){
$("#cart_table").empty();
//New JavaScript code, make appropriate changes.
jQuery.each(response, function(key, row) {
$('#cart_table').append("<tr><td>" + row.item + "</td><td>" + row.quantity + "</td><td>" + row.price + "</td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>");
});
}
});
});
});

Adding data dynamically to HTML Table in PHP

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);
}
});
});
});

Categories