passing all table data from jsp to servlet - javascript

I have user editable table at front end. when user click process button, i am doing form validation in jquery from there i am passing flow to servlet, So i have to pass the bunch of table data to servlet. Some one please suggest me on how to pass all table data in ajax call. Currenly i have a piece of code which contains table data in array where i can get as each cell values. instead of that i wanna pass it in row manner
var InspTableArray = [];
$("#tab_logic tr.data").map(function (index, tr) {
$(this).find('td').each(function(){
var $data = $(this).html();
if($(this).find("select").length > 0) {
var $x = $(this).find("select").val();
}else{
var $x = $(this).find("input[type='text']").val();
}
InspTableArray.push($x);
});
});

I'd suggest using jQuery post method https://api.jquery.com/jquery.post/:
$.post('/url/to/page', {'arrayFieldName': InspTableArray} );

Related

Laravel blade condition in ajax

I have my data returning by ajax into table in blade but i need a filter in my returned data.
Example
If I use blade loop I can use #if ($loop->last) in order to make special changes for my last record, but since my data is returning by ajax (JSON) I'm not sure how to do that.
Code
Commented the part i need filter
$.ajax({
type:'GET',
url:'{{url('dashboard/getProjectReimburses')}}/'+projectID,
success:function(data){
$(data.data).each(function(_, i){
var number = i['amount'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
var row = `<tr data-id="${i.id}">'+
'<td>${i.created_at}</td>'+
'<td>${i.spent_date}</td>'+
'<td>${i.cost_name}</td>'+
'<td class="text-right">${nf.format(number)}</td>'+
'<td>${i.description}</td>'+
'<td>Attachments here</td>'+
'<td>${i.statusName}</td>'+
#role('employee|admin')
'<td>${i.statusDate}</td>'+
'<td>
// I need show this delete button only for latest row, for other rows just empty <td></td> //
<Form method="DELETE" id="organizationFormDel">
#csrf
#method('DELETE')
<button type="submit" data-id="${i.id}" class="btn btn-sm reimDelete btn-danger">Delete</button>
</form>
// I need show this delete button only for latest row, for other rows just empty <td></td> //
</td>'+
'</tr>`;
#else
'<td>status date here</td></tr>`;
#endrole
$('#visit_table2').append(row);
});
}
});
Any idea?
Update
Here is screenshot of my blade, I select 1 row from table 1, data shows in table 2
Now in table 2 as i marked it i want to show edit and delete button only for latest row other 3 rows empty <td>
You can use a partial view for ajax. For example when you will send an ajax request on the backend then you will use a partial blade file on the backend and there you can use if statement in blade file and you will return Html as response and then you will append that Html to DOM on success.
$html = view('partial-blade',['data'=> $data])->render();
return $html;
You have to make a view and set all html code there. after calling Ajax and render view
$view = view('blade',["data"=>$data,])->render();
return $view;
Solved
Well I manage to do it the way I wanted, thanks to comments but my problem wasn't in controller unfortunately I couldn't convince friends that what i need is handle my ajax data on success and not controller.
Anyway here is my solution which works perfectly for me :
$(data.data).each(function(_, i){
//.....
var ms = _ == data.data.length -1; //get latest row
if(ms == true){ // if is latest row
// show my tr's with action buttons
var row = `<tr data-id="${i.id}">'+
//....
} else {
// show mt tr's without buttons
var row = `<tr data-id="${i.id}">'+
//....
}
});
Thanks for all helps.

Create Array from HTML to send via AJAX

Im having a unusually hard time with this. If I have form that looks like this
HTML
<form id='logForm' method='post' action='seatingProcess.php'>
<span class='close' style='display:none' id='255' desk='9-4' deskval='2-3' changeType='REMOVE'></span>
<span class='close' style='display:none' id='255' desk='7-4' deskval='5-3' changeType='ADD'></span>
<span class='close' style='display:none' id='255' desk='8-4' deskval='8-3' changeType='CHANGE'></span>
<div class='btn btn-primary' type='submit' id='submit'>Submit</div>
</form>
What I want to happen is, when i click the button to submit the form, I want to have an array of the different elements in the span created so it can be sent via AJAX to process in PHP. How do you recommend I do this?
Also, this information will be dynamically created in this form based on user action. They will all be span's but will contain more or less the same attributes with a value attached to them. The idea is for php to receive the arrays and depending on what the attribute "changeType" says, it will generate the SQL script to perform that action. I may need help with this as well.
All I have for javascript. I dont have anything about making the array, thats what I need help with.The HTML above is an example output, but ill post one of the functions that generates the information. :
Javascript
function remDeskId(){
userObject = $dropObject.find('div.dragTest');
userObjectChange = 'REMOVESEAT';
userObjectID = userObject.attr('data-info');
userObjectDeskID = userObject.attr('data-id');
userObjectDeskIDVal = 0;
$('form#logForm').append("<span class='close' style='display:none' id='"+userObjectID+"' desk='"+userObjectDeskID+"' deskval='"+userObjectDeskIDVal+"' changeType='"+userObjectChange+"'></span>");
userObject.attr({"data-id":""}); //remove desk number for new user location
userObject.appendTo('#userPool');
}
$('#submit').click(function(){
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
//var formData = {
// };
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'seatingProcess.php', // the url where we want to POST
data : $('#logForm').serialize(), // our data object
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Thanks in advance
You can iterate through the spans and create an array.
var spans = $('#logForm span');
var data = [];
$.each(spans, function(i, item){
var newItem = {};
newItem.id = $(item).attr('id');
newItem.desk = $(item).attr('desk');
newItem.deskval = $(item).attr('deskval');
newItem.changeType = $(item).attr('changeType');
data.push(newItem);
});

How to submit dynamically created hidden variables using Jquery

I have created a dynamic table. DEMO to my project.
I have placed this dynamic table in the form under a div named 'box'
<div id="box">
</div>.
I am creating dynamic hidden variables table using Jquery which I need to store in DB. This is how I am creating the hash to submit to server.
criteria = $('form_name').serialize(true);
criteria = Object.toJSON(criteria);
// Build the object to store the parameters for the AJAX post request
parameters = {
title : $('report_title').value,
description : $('report_description').value,
criteria : criteria
}
// Make the AJAX post request
new Ajax.Request( URL, {
method: 'post',
parameters: parameters,
onSuccess: function( response ) {
$('messageSpan').innerHTML = response.responseText;
$('spinner').style.display='none';
}
});
I am not able to capture the dynamically created values in the criteria.
How to solve this?
In the dynamically created section, I tried adding a submit button and see if the values can be fetched. I am able to fetch and iterate all the hidden variables.
$('#jquerysaveButton').click(function(){
jsonObj = [];
$("input[id=rubric_cell]").each(function () {
var id = "cell_" + row + "_" + col;
item = {}
item["id"] = id;
item["selected_rubric"] = $(this).val();
jsonObj.push(item);
});
console.log(jsonObj); //I am getting the required values here
});
How to get these values in the criteria = $('form_name').serialize(true);. Am I doing some thing wrong? Please help me. thanks in advance.
DEMO to my project
You need to make sure that your hidden input fields have a name attribute set otherwise $.serialize will not process them.

PHP-CodeIgniter: How to get the corresponding html table row values to be deleted by Javascript

In my codeigniter project i'm using a Table in which it is dynamically generated by Ajax. on the each row there is a button to Delete the corresponding row from Html Table and Mysql table too.
i tried it already. and i get the code to remove Html table row , and it follows
$(document).on('click', '#deleteRow', function() {
$(this).parent().parent().remove();
});
and it worked. but i want to delete that corresponding row from Mysql too. so first of all , it needs to be pass the corresponding row informations from javascript. then pass this to the Controller via URL.?
window.location.href = "<?php echo base_url("settings/remove_company"); ?>?id="+current;
How i get corresponding row informations such as company_id, lic_id (field names of html table).?
any help would be greatly appreciated .
Add attributes to the <tr>
<tr data-companyId="<?php echo $companyId;?>" data-licId="<?php echo $licId;?>">
In your jQuery, get those attributes on click of delete link:
$(document).on('click', '#deleteRow', function() {
var companyId = $(this).parent().parent().attr('data-companyId');
var licId = $(this).parent().parent().attr('data-licId');
$(this).parent().parent().remove();
});
Even, you can do object caching (using variable instead of object to improve performance.
$(document).on('click', '#deleteRow', function() {
var obj = $(this).parent().parent();
var companyId = obj.attr('data-companyId');
var licId = obj.attr('data-licId');
obj.remove();
});

How do I create a web link inside a javascript function and pass cell value as a parameter to servlet?

I am creating a table dynamically with JavaScript as you can see below. I want users to be able to click on the first column value and pass the value of the cell as a parameter to a J#EE servlet. Can you help me? Basically the first column should be links to a new page with a country details. How can I do that? Thank you.
Where do I put the link code?
function oneSecondFunction() {
$.get('DisplayCountries', function(responseJson) {
if (responseJson != null) {
$("#countrytable").find("tr:gt(0)").remove();
var table1 = $("#countrytable");
$.each(responseJson, function(key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td>" +
"<td></td><td></td></tr>");
rowNew.children().eq(0).text(value['id']);
rowNew.children().eq(1).text(value['country1']);
rowNew.children().eq(2).text(value['country2']);
rowNew.children().eq(3).text(value['country3']);
rowNew.children().eq(4).text(value['country4']);
rowNew.children().eq(5).text(value['country5']);
rowNew.children().eq(6).text(value['country6']);
rowNew.children().eq(7).text(value['country7']);
rowNew.children().eq(8).text(value['country8']);
rowNew.appendTo(table1);
});
}
});
and here is the link code. I have tried several options and it doesn't work.
id
First, assign a class to the first <td> something like <td class="linkHolder">.
Then, write a click handler to send ajax request to servlet:
$('#countrytable').on('click', '.linkHolder', function() {
var link = $(this).html();
$.post('/myservlet', {url: link}, function(response) {
//handle response here
});
return false;
});
You can access the link on the servlet side with the request parameter url

Categories