How to pass global variable data inside ajax load data in jquery? - javascript

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.

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
}

How to submit dynamic data without form?

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

How do you transfer data from a table to a server?

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>

On page refresh html tag IDs,classes and names are not getting preserved

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?

Getting text box value that is in the td, store in array in Javascript and passing back to PHP

I have a table displayed using PHP. There are only two rows, the first row contains the headers, second row contains text box inside the td. What I am trying to do in this part of my script is for the user to enter some values, then I would like to grab the values according to the header names so that I can use them for a query.
I have created the table headers and text boxes according to how many headers there are as you can see in the codes below. This is inside one function, other parts are just the codes for the table and queries.
Now my main problem is that I want to get the values of each text box according to the headers. An example would be if the header is called Configuration and the value in the text box under that header is the user has typed in 1,5,8. After a button click, a new PHP function would be executed. This function is the one I'm working on to get the text box values. I've tried iterating through the table cells in Javascript but I'm stuck at getting the text box values.
If possible, I would like to know how all the headers can be stored in an array in Javascript, the text box values to be stored accordingly as well. If it were in PHP it'd be something like $user_input[$header][$text_val]. Or just separate arrays would be fine as well as long as I am able to get the values that correspond to the headers so that I can use it in my query.
Note: I am using ajax's post to pass back values to my PHP file. The table is created with dynamic values so it'll be getting the values in the same PHP file and passing it back to there as well (called database.php). I saw some codes that have something to do with json_encode but I,ve never used anything that has to do with json, so if there are solutions using json, pardon me in advance and help me to explain it in simple terms.
while($row = mysql_fetch_assoc($result))
{
$board_name = $row['board_name'];
$header[] = $board_name;
}
foreach($header as $index => $head)
{
$html .= "<th>$head</th>";
}
$html .= "
</tr>
<tr id=\"config_input\">
<td colspan = \"3\">
Please Key in Configuration:
</td>";
foreach($header as $index => $head)
{
$html .= "
<td>
<input type=\"text\" style=\"width: 70px\"/>
</td>";
}
$html .= "</tr>";
EDIT, this is what I've tried so far in my external JavaScript file:
// After use has typed in input and clicked button, this function is executed
function searchConfig()
{
var tester_type = $("#tester_type").val();
var table = document.getElementById("searchByConfigTable");
var headers = document.getElementById("headers");
var text_row = document.getElementById("config_input");
var page = "database.php";
var board_name = new Array();
var board_config = new Array();
for (var i = 3, col; col = headers.cells[i]; i++) // headers
{
var str = col.innerHTML;
board_name.push(str);
}
for (var i = 3, col; col = text_row.cells.value[i]; i++) // text_row
{
var str = col.innerHTML;
board_config.push(str);
// array has no value because it's not text box value
// that is stored, not sure what to do
}
// Not sure what to do from here on
$.post(page, {
tester_type : tester_type,
action : "search_config"
}, function(data) {
$("div#display_board").html(data);
});
}
with this code below you can get a JSON object of your headers and values. check it out:
HTML:
<table id="myTable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>comment</th>
</tr>
</thead>
<tbody>
<tr>
<td><input value="1" type="text"></td>
<td><input value="name1" type="text"></td>
<td><input value="coment1" type="text"></td>
</tr>
</tbody>
Javascript:
var header = [];
var values = [];
var json = [];
$('#myTable').find('th').each(function() {
header.push($(this).html());
});
$('#myTable').find('tbody > tr > td').each(function() {
values.push($(this).find('input').val());
str.push($(this).html());
});
for (var i in header) {
json[i] = {};
json[i][header[i]] = values[i];
}
console.log(json);
you can send this json object to php with AJAX
$.ajax({
type: "POST",
url: "file.php",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: json
}).done(function(JqXHR){
alert(JqXHR);
});

Categories