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.
Related
The console.log(response) returns the code of whole page in console when I inspect it in ajax . I have created a codeigniter project with MySQL as back end database . I have fetched content from table from database into table. Now I want to give option to user of mulitple delete. Please take it into account that I am not actually deleting value from table I am just turning status of of that row to inactive. It goes as :
If status= 0 : the row's data will be visible in table.
If status= 1:the row's data will not be visible in table.
I have given checkbox option in the table to select multiple checkbox.
Here is my javascript:
To check all the check boxes:-
<script language="JavaScript">
function selectAll(source) {
checkboxes = document.getElementsByName('sport');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
javascript to get value's from the checkboxes and send it to controller:
<script type="text/javascript">
function okay(){
var favorite = [];
$.each($("input[name='sport']:checked"), function(){
favorite.push($(this).val());
var txt=$(this).val();
});
for (var i = 0;i<favorite.length;i++) {
$.ajax({
url:('<?=base_url()?>/Repots/supervisor_muldel'),
type:'POST',
data:{'value_id':favorite[i]},
success:function(response)
{
console.log(response);
},
error:function(response)
{
console.log('nahi gaya');
},
});
//console.log(favorite[i]);
}
//alert("My favourite sports are: " + favorite.join(", "));
}
</script>
every check box is associate with particular values.
here the html button to call the fucntion:
<button onclick="okay();">Delete Selected</button>
Controller:Reports/supervisor_muldel:
//multiple delete supervisor
public function supervisor_muldel() {
$value_id = $this->input->post('value_id');
$selected_supervisor = array('supervisor_id' =>$value_id);
$staus=array('status'=>1);
$this->load->model('Entry_model');
$result = $this->Entry_model->supervisor_muldel($staus,$selected_supervisor);
}
Entry_model/supervisor_muldel:
//delete multiple supervisor
public function supervisor_muldel($staus,$condition)
{
$this->db->trans_start();
$this->db->where($condition)
->update('tbl_supervisor',$staus);
$this->db->trans_complete();
}
The console.log returns the code of whole page in console.I am stuck here.
You have put wrong ajax request URL.
Change
url:('<?=base_url()?>/Repots/supervisor_muldel'),
to
url:('<?=base_url()?>/Reports/supervisor_muldel'),
Look at the controller name in URL.
In a form, i have a dropdownlist and a textbox which will get user's input. Then when the user submits the form, i don't want the whole page to refresh. i only wanted the table which is just below it to refresh and load data from database. I tried code below but only alert pops up. The table is still empty.
$('#frmPrescDrugList').submit(function (e) {
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: '/consultation/PrescDrugList',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html',
success: function (data) {
var row_data = "";
row_data += "#{ var rowNum = 0; } #foreach (var item in Model.LoadDrugList) {
rowNum += 1;
<tr Class="odd gradeX">
<td>#rowNum</td>
<td>#item.dsubsystem</td>
<td>#item.tradename </td>
<td style="text-align: center; vertical-align: middle;"><form Class="form-horizontal" role="form" action="#Url.Action("Prescription", "consultation", new {dgid = item.dgid})" method="post"><Button type="submit" Class="btn btn-default" name="btnDrugListSelect">Select</Button></form></td>
</tr>
}";
$("#LoadDrugListTable").append(row_data);
alert('Drug list has been loaded.');
},
error: function () {
alert('Ajax Submit Failed ...');
}
}); // end ajax
}); // end form-submit
LoadDrugListTable is the table's id. Why didn't it load the data when the ajax is already successful? Can anyone please help point out my mistake or suggest me a better example reference?
I tried following this example, but i'm stuck at the #Url.Action(). Its underlined red. And when i try to separate them by "" and + it's still underlined red saying
Too many characters in character literal.
UPDATED
This is the form i mentioned that doesn't pass the id properly. I'm passing it to a get method. By the way, this is an entirely different page than the one i mentioned above. When i try to do the same thing in another page, it passes a null paid value. Paid is the id. Maybe because this time i'm passing to another page.
"<td style='text-align: center; vertical-align: middle;'><form Class='form-horizontal' role='form' action='#Url.Action("PatientMedicalInfo", "consultation", new { paid = Html.Raw(" + data[i].paid + ") }) method='get'><Button Class='btn btn-default' name='btnSelectPatient' id='btnSelectPatient'>Select</Button></form></td>"
This is the controller:
[HttpGet()]
public ActionResult PatientMedicalInfo(string paid)
{
PatientLookupVM Patient = new PatientLookupVM();
dynamic CurrentPatientDetailsByPtId = Patient.GetCurrentPatientDetailsByPtId(paid);
Patient.LoadCurrentPatientDetails = CurrentPatientDetailsByPtId;
return View(Patient);
}
Try replacing double " quotes with single ' quotes in action.
Well for consistency you could replace them everywhere.
<td ... action='#Url.Action("Prescription", "consultation", new {dgid = item.dgid})' ... </td>
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} );
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);
});
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();
});