I am trying to fetch data from a table and push the selected data to my server.
I have tried selecting columns from my table then making an HTTP request, but it didn't work.
Can anyone help me?
This is my understanding
here is a procedure if you like to do
insert all you desire record set into an array
make a json using json_encode() method of php.
use curl post request and pass the json string
Here's an example of how to pull data from a HTML table, put it into a javascript array, convert it to json and send it to the server
https://jsfiddle.net/f958qokn/
<table id="MyTable">
<tr>
<td>1</td>
<td>Code Monkey</td>
</tr>
<tr>
<td>2</td>
<td>Code Elephpant</td>
</tr>
</table>
<input id="PostTableData" type="button" value="Post Table Data"/>
<script type="text/javascript">
$(document).ready(function() {
$( "#PostTableData" ).on( "click", function() {
var TableData = [];
$("#MyTable tr").each(function() {
var RowData = [];
var ColumnsData = $(this).find('td');
if (ColumnsData.length > 0) {
ColumnsData.each(function() { RowData.push($(this).text()); });
TableData.push(RowData);
}
});
alert(JSON.stringify(TableData));
jQuery.ajax({
type: 'POST',
url: "/SaveData.php",
data: JSON.stringify(TableData),
dataType: "json",
success: function(data){ alert(data); }
});
});
});
</script>
Related
I have an HTML Table and I am retrieving the data (using Jquery function) from the specific <td> VALUES and pass the data to another java server page using Ajax.
This is the table <tr>
<tr height=40 style='mso-height-source:userset;height:30.0pt'>
**<td class=xl86 style='border-left:none' contenteditable="true"> </td>
<td class=xl86 style='border-left:none' contenteditable="true"> </td>
<td class=xl86 style='border-left:none'contenteditable="true" > </td>
<td class=xl86 style='border-left:none'contenteditable="true"> </td>**
</tr>
I code a jQuery function for retrieving these table values individually that is below.
$(document).ready(function () {
var col1=" ";
var col2=" ";
var col3=" ";
var col4=" ";
$('#btn_read_HTML_Table').click(function () {
$('#mytable tbody>tr').each(function () {
var currentRow=$(this).closest("tr");
col1=currentRow.find("td:eq(0)").text();
col2=currentRow.find("td:eq(1)").text();
col3=currentRow.find("td:eq(2)").text();
col4=currentRow.find("td:eq(3)").text();
var data1=col1+"\n"+col2+"\n"+col3+"\n"+col4;
});
$.ajax({
url: "load_tabledata.jsp",
type:'POST',
data:{c1: col1,c2:col2,c3:col3,c4:col4},
success: function (data, textStatus, jqXHR) {
console.log(data);
}
})
});
});
Problem is Ajax taking empty value of var col,col2,col3 and col4 but inside function table values retrieving.
I want to get these retrieved values in my ajax function so that I could pass these values inside the data.
In my Laravel app, I add ajax query (which work after pressed button). I get the result in ajax, I see it on console (it's array).
But I need to send an answer from js to PHP for creating a table
This is code of input:
<input type="text" name="check" id="check">
This is code of button:
<button type="button" class="check-client btn btn-success">Find</button>
This is code of ajax (JS):
$(document).on("click", ".check-client", function () {
const data = $("#check").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
data: {
'data': data
},
url: '/checkValues',
success: function (result) {
console.log(result);
const dataForTable = result;
}
});
});
For creating table I try to do this:
send response to php+html:
$(".testClass").append(result);
get this value:
<div class="testClass"></div>
and create a table, using foreach:
<div class="testClass"></div>
<table class="table table-bordered text-center">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Person</th>
<th scope="col">Cost</th>
</tr>
</thead>
<tbody>
#foreach($dataForTable as $item)
<tr>
<th scope="row">$item['id']</th>
<td>$item['person']</td>
<td>$item['cost']</td>
</tr>
#endforeach
</tbody>
</table>
So, it doesn't work. How to create a table from ajax response?
The problem is that you trying to run jQuery at the client side to uses the return of ajax request (dataForTable) at the server side, it's out of PHP context server. PHP works only server side, meanwhile jQuery is working on browser client, if you want to run javascript in the server side you have to search for other technology, like Node, look at node.js.
Wether you want to update a table on client side using ajax request you have to update a table iterate de variable (dataForTable) on client side, after the request, like this:
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
There are many other examples like this above in jQuery.
Finally, you have to work at Client side wether you want to use jQuery, or work at server side using the PHP helpers.
I am getting data as form of Java Bean and I am inserting each value into a table.
Values are retrieved as common way at first.
But I added some Javascript source, so that I can modify the value if I click any area near it.
Now I would like to save the data in database as well if there was any change after I modify.
How can I do that?
Here is my HTML code
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-editable>${engboardVO.word}</td>
<td data-editable>${engboardVO.dialogue}</td>
<td data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
And Javascript
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
/* var $input = $('<input style="width:500px; height:100px"/>').val( $el.text() ); */
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.replaceWith($input);
var save = function() {
var $td = $("<td data-editable />").text($input.val());
$input.replaceWith($td);
};
$($input).blur(function() {
save();
})
});
You can use ajax for submitting data without form.
I can see you are using jQuery library. So I am writing code based on this library.
In HTML:
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-name="word" data-editable>${engboardVO.word}</td>
<td data-name="dialogue" data-editable>${engboardVO.dialogue}</td>
<td data-name="practice" data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
In javascript:
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.html($input);
var field_name = $el.attr('data-name');
var save = function() {
var $val= $input.val();
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
};
$($input).blur(function() {
save();
})
});
Then in server side, you can save fieldvalue as value of fieldname in your database.
Basically what we are doing here is:
Added an attribute data-name in td tag, its value can be related to your field name in table.
Get the name of attribute in javascript using var field_name = $el.attr('data-name');.
Using post request in ajax call passed the field_name and and value of this field to server.
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
Now in server side, you need to fetch this data as you fetch normally for post request in submit of a form and save this data in database.
url is same as action you provide in form tag.
Edit:
Check now. You were replacing the td, whereas you had to replace html inside td.
Don't worry if you don't have a form or can't have it for some reasons
You can still read the inputs of your web page and use them or send them to the server.
See below a simple example:
var inputs = document.getElementsByTagName('input');
var data = []
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
data.push(inputs[index].value)
}
var json = JSON2.stringify(data);
$.ajax({
type: "POST",
url: "your-api-url",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// done code
}
});
I have a dynamic table that displays data from a mysql database. My database is updated every time in the server. I want to refresh only the table every 2 seconds without refreshing the whole page. How can do this? Please help how accomplish this?.
Parts of my table look like this:
<table id="getdata" border="0" align="left" cellpadding="0" cellspacing="0">
<tr>
<td bgcolor="#CCFF00">Name</td>
<td bgcolor="#CCFF00">Comment</td>
<td bgcolor="#CCFF00">DatePosted</td>
</tr>
</table>
You will need to use a client-side scripting language such as javascript in order to be able to refresh certain contents on your HTML page. A very common library that is used is jQuery.
PHP
# ajax.php
$contents = '<table class="table table-hover">
<thead>
<tr>
<th>Sound</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bzzz Bzz</td>
</tr>
</tbody>
</table>';
echo json_encode($content);
HTML/Javascript
<button class="refresher">Refresh table</button>
<table id="table-to-refresh">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.refresher', function () {
$.ajax({
url: 'ajax.php',
method: get,
dataType: 'json',
success: function(response) {
$('#table-to-refresh').html(response);
}
});
});
});
</script>
Additional reading
jQuery Docs - Ajax
<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 ()
{
$('#load_tweets').load('file.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
in file put your full html and php sql code like full code by which you are generating that table.
check this for refrence http://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html
Use ajax on an specified time interval like:
$.ajax({
url: 'your_url',
method: get,
data:
{
var1 : val1
},
success: function(response)
{
$('#getdata').html(response); // it will update the html of table body
}
});
just do this:
$.ajax({
contentType: contentType,
dataType: dataType,
type: type,
url: urlGetsearch,
data: '{textvalue: "' + $("#tableId").val() + '" }',
success: function (textvalue) {
$("#tableId").html(htmlData);
},
});
}
The controller is look like this:-
[HttpPost]
public ActionResult Getsearch(string textvalue)
{
your code.....
}
I am taking the data from textbox and option field using AJAX request to the server storing it to db, creating the row and attaching it to table.
$("#addRecord").click(function(e) {
e.preventDefault();
var question_id = $("#questionId").val();
var question_text = $("#questionText").val();
$.ajax({
url: "addContestAnswer.html",
type: "post",
dataType: "json",
data: {"questionId": question_id, "contestText": question_text},
success: function(data){
addRows(data.questionId,data.contestText);
// calling the function to create row
},
error: function (request, status, error) {
console.log("error" + status);
}
});
});
creating the row
function addRows(questionId ,questionText) {
var deleteButton = 'delete';
var fileUpload = '<input type="file" name="supportingDocument" accept="application/pdf" id="uploadSupportingDoc" />';
var row = "<tr><td class=\"ques_id\">"+questionId+"</td><td class=\"ques_text\">"+questionText+"</td><td class=\"ques_file\">"+fileUpload+"</td><td></td><td>"+deleteButton+"</td></tr>";
$('#recordTable tr:last').after(row);
$("#questionId").val("-1");
$("#questionText").val("");
}
So far the html generated is looking good.
But when I'm refreshing the page, none of the html IDs,classes and Names of generated row are getting preserved.
generated row after ajax call
<tr>
<td class="ques_id">17</td>
<td class="ques_text">asddgfdg</td>
<td class="ques_file"><input type="file" name="supportingDocument" accept="application/pdf" id="uploadSupportingDoc"></td>
<td></td>
<td>delete</td>
</tr>
After refreshing the page
<tr>
<td>17</td>
<td>asddgfdg</td>
<td><input type="file" name="" id=""></td>
<td></td>
<td>delete</td>
</tr>
why is it happening? am I missing some tweak while generating the row, if not what's the solution?