I have a dropdown in view that is using js I pass the selected item from dropdown to controller, inside the controller I ran a query using the selected item from dropdown to extract some records. Now the problem is that I cannot display the query result to view. Basically I cannot trigger the controller to display in view. Any help greatly appreciated.
Here is the js to pass the data to controller:
<script type="text/JavaScript">
$(function(){
$('.defined_call').bind('change', function(){
alert($(this).val());
$.ajax({
url: "<%= changeowner_path %>",
data: { my_str: $(this).val() }
});
});
});
</script>
<%= select_tag "dropdown_cases", options_for_select(#ownerlist),{:id=>"defined_Id",:class
=> "defined_call'} %>
Here is the controller:
class ReassignsController < ApplicationController
def changeowner
i=0
$myarr=[]
ownerl = Transaction.owner#declaredin model
#ownerlist=ownerl.collect { |c| [ c, c ] }#make it for dropdown
value=params[:my_str]#return value from dropdown
$value1=value.to_s#make it for owner table
#owner_records=Transaction.where(:owner => $value1)
===> I would like to display to the view?
end
end
Here is the view that I am using:
<table class="table table-condensed" id="sortTableExample">
<tr>
<th style="text-align:center">Book Name</th>
<th style="text-align:center">Owner</th>
</tr>
<% #owner_records.each do |arr_data| %>
<tr>
<td style="text-align:center"><%= arr_data.book%></td>
<td style="text-align:center"><%= arr_data.owner%></td>
</tr>
<% end %>
</table>
Joe, Try something like:
$('.defined_call').change(function() {
$.ajax({
url: "<%= changeowner_path %>", type: 'get',
data: { my_str: $(this).val() },
dataType: 'json',
processData: false,
success: function(data) {
if (data == "") {
alert('No Results');
}
else {
var jsonObj = eval( data );
var count = jsonObj.transactions.length;
for (var i = 0; i<count; i=i+1) {
$('#sortTableExample').append('<td style="text-align:center">' + jsonObj.transactions[i].book + '</td><td style="text-align:center">' + jsonObj.transactions[i].owner + '</td>');
}
}
}
});
});
Rails is rendering your view, you just aren't doing anything with it on the client side (in javascript).
In your ajax call you want to do something on success:
$.ajax({
url: "<%= changeowner_path %>",
data: { my_str: $(this).val() },
success: function(data) {
$('#myDiv').html(data); // This is writing the returned view from rails to myDiv
}
});
Related
I want to remove the deleted row from the table but it's not working with me. I tried the below code:
Scenario: When a user click on delete link/button, it sends a delete request and deletes data from Database so it should update the table front end view and should remove the clicked deleted row on success.
// Delete remedy which is linked with a Symptom ( Symptoms Table )
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
$.SmartMessageBox({
title: "Delete Remedy",
content: "Remedy Entry will be deleted, are you sure ?",
buttons: "[YES][NO]"
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
type: 'POST',
data: dataString,
url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-remedy-from-symptom') ?>',
success: function(data) {
$("#deleteMessage").show().delay(5000).fadeOut();
$(this).closest('tr').remove();
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});
I tried $(this).parent().closest('tr').remove(); also on success but not working.
HTML markup:
<table id="cx-records-table" class="table display table-striped table-bordered" width="100%">
<thead>
<tr>
<th>
Title
</th>
<th>
Delete
</th>
</tr>
<?php foreach($remedies as $key => $remedy){ ?>
<tr>
<td class="all"><?php echo $remedy['title']; ?><br></td>
<td><a class="cx-action remedy-row-delete" href="javascript:void(0)" data-id="{{remedy['id']}}"><i class="fa fa-trash-o"></i></a></td>
</tr>
<?php } ?>
</thead>
<tbody></tbody>
</table>
Thanks
because $(this) inside of ajax function is different than from outside you should do something like this
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
var $this = $(this) // <--- 1. Add this line
$.SmartMessageBox({
...
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
...
success: function(data) {
...
$this.closest('tr').remove(); // <----change this and will works well
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});
try this
// Delete remedy which is linked with a Symptom ( Symptoms Table )
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
var self = this;
$.SmartMessageBox({
title: "Delete Remedy",
content: "Remedy Entry will be deleted, are you sure ?",
buttons: "[YES][NO]"
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
type: 'POST',
data: dataString,
url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-remedy-from-symptom') ?>',
success: function(data) {
$("#deleteMessage").show().delay(5000).fadeOut();
$(self).closest('tr').remove();
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});
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 page that looks like this:
"Default List Name" is the name of the current page displayed. There are two buttons below and then a table which is the Default List table. Once I click Btn1, it will just re-display the default list table, but when I click Btn2, another table will be displayed, replacing the default list table. Let's call the second table "Second List". Once the table changes, the title "Default List Name" will also change to "Second List Name".
I am going to use AJAX for this so that real time button click and displaying of the corresponding table are applied. But I am still new to AJAX so I am having quite a hard time.
Here's my current code:
var title = $("#title").text();
var btn1 = $("#btn1");
var btn2 = $("#btn2");
/** If one of the buttons is clicked after another and then displays a table, the previous ajax that displayed the previous table, will be removed **/
$(document).ready(function() {
btn1.on("click", function() {
displayDefaultList();
});
btn2.on("click", function() {
displaySecondList();
});
});
function displayDefaultList(){
console.log("display default list table");
/*$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'url to current page (not sure)',
async: false
}).*/
}
function displaySecondList(){
console.log("display second list table");
}
I hope I'm making my self clear and hope you guys can help me.
I just wrote this for you just to show you that you can always show and hide your tables
$(document).ready(function(){
$("#mytable1").show();
$("#mytable2").hide();
$("#button1").click(function(){
$("#text").html("Default List Name");
$("#mytable2").hide();
$("#mytable1").show();
});
$("#button2").click(function(){
$("#mytable1").hide();
$("#mytable2").show();
$("#text").html("Second List Name");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div id = "text">Default List Name</div>
<button id = "button1">Button1</button>
<button id = "button2">Button2</button>
<table id = "mytable1" border = "1">
<tr>
<td>text1</td>
<td>text1</td>
<td>text1</td>
</tr>
<tr>
<td>text2</td>
<td>text2</td>
<td>text2</td>
</tr>
<tr>
<td>text3</td>
<td>text3</td>
<td>text3</td>
</tr>
<tr>
<td>text4</td>
<td>text4</td>
<td>text4</td>
</tr>
</table>
<br/>
<table id = "mytable2" border = "1">
<tr>
<td>box1</td>
<td>box1</td>
<td>box1</td>
</tr>
<tr>
<td>box2</td>
<td>box2</td>
<td>box2</td>
</tr>
<tr>
<td>box3</td>
<td>box3</td>
<td>box3</td>
</tr>
<tr>
<td>box4</td>
<td>box4</td>
<td>box4</td>
</tr>
</table>
NOW for your ajax, you should just simply hide one of the tables based on the button that was clicked, and then load the data to your specific table. This works for me. Hope it helps :)
Here's AJAX:
$(document).ready(function(){
$("#button1").click(function(){
$("#mytable2").hide();
$.ajax({
url:'app.php',
type: "GET",
data: ""
dataType: 'json',
success: function(data){
$.each(data, function(key, value){
$("table #mytable1").append("<tr><td>" +
"ID :" + value.ID +
"Name :"+ value.Name +
"Age :" + value.Age +
"</td><tr>");
.........
});
}
});
});
$("#button2").click(function(){
$("#mytable1").hide();
$.ajax({
url:'app.php',
type: "GET",
data: ""
dataType: 'json',
success: function(data){
$.each(data, function(key, value){
$("table #mytable2").append("<tr><td>" +
"ID :" + value.ID +
"Name :"+ value.Name +
"Age :" + value.Age +
"</td><tr>");
.........
});
}
});
});
});
I created this fiddle for you: https://jsfiddle.net/8bakcfub/.
Basically, each button click will simulate a call to an API that returns a very simple JSON object. On success, the code parses the response, empties the table and appends a new row to it with the data, and finally changes the title.
Note that the code is pretty much the same for both buttons, except for (a) the JSON returned from AJAX, and (b) the title :)
HTML:
<p id="title">
This title will be replaced...
</p>
<button id="btn1">
First list
</button>
<button id="btn2">
Second list
</button>
<table id="table">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
<tbody>
</tbody>
</table>
JS:
var btn1 = $("#btn1");
var btn2 = $("#btn2");
$(document).ready(function() {
btn1.on("click", function() {
displayDefaultList();
});
btn2.on("click", function() {
displaySecondList();
});
});
function displayDefaultList() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
async: false,
data: {
json: JSON.stringify({
row: [1, 2]
})
},
success: function(result) {
$('#title').text('first list');
$('#table tbody').remove();
var newRow = '<tbody><tr><td>' + result.row[0] + '</td></tr><tr><td>' + result.row[1] + '</td></tr></tbody>';
$('#table').append(newRow);
}
});
}
function displaySecondList() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
async: false,
data: {
json: JSON.stringify({
'row': [3, 4]
})
},
success: function(result) {
$('#title').text('second list');
$('#table tbody').remove();
var newRow = '<tbody><tr><td>' + result.row[0] + '</td></tr><tr><td>' + result.row[1] + '</td></tr></tbody>';
$('#table').append(newRow);
}
});
}
I need generate table in success ajax and draw in html. But I dont know how can I fill my table. I try this, but nothing draw.
$.ajax({
url: '/Private/Index',
method: 'POST',
dataType: "json",
data: $(addNewEduForm).serialize() + '&' + $.param(mm),
traditional: true,
success: function (selected) {
$('#your-modal').modal('toggle');
var row = $('<tr>');
for (var i = 0; i < selected.length; i++) {
row.append($('<td>').html(selected[i]));
}
$('#results').append(row);
},
error: function (error) {
}
});
My console.log(selected) :
PICTURE
And my html, where I need draw the table:
<table class="table_blur">
<tr>
<th>Date</th>
<th>Event</th>
<th>First</th>
</tr>
</table>
As result I need :
<th>Date</th><th>Event</th><th>FirstTeam</th>
<DateFromSelected><EventFrom Selected><FirstTeam>
You need that your code looks like that, for example you need show DateofEvent and FirstTeam.
HTML CODE
<table id="results">
<thead>
<tr>
<td>DateofEvent</td>
<td>FirstTeam</td>
</tr>
</thead>
<tboby>
</tbody>
</table>
JS CODE
$.ajax({
url: '/Private/Index',
method: 'POST',
dataType: "json",
data: $(addNewEduForm).serialize() + '&' + $.param(mm),
traditional: true,
success: function (selected) {
$('#your-modal').modal('toggle');
var row = $('<tr>');
for (var i = 0; i < selected.length; i++) {
row.append($('<td>').html(selected[i].DateofEvent));
row.append($('<td>').html(selected[i].FirstTeam));
}
$('#results').append(row);
},
error: function (error) {
}
});
*remember that you return a collection of objects and you access them by name.
This is how my webpage looks like:
As can be seen in the picture I have I have search on the top right, in the bottom right I have the amount of pages etc..
But as I add another project here by clicking "Lägg till ny" and add a project for some reason my page will end up like this:
http://puu.sh/kKSZz/387c71f487.png
As can be seen the table "Breaks" the search field gets removed and so does the pages. Same things happens when I chose to edit or delete a project I've already added.
This is my view:
<div id="tabs-current">
<div id="ConsultantTimes">
#{
Html.RenderAction("ConsulantTimes");
}
</div>
<a href="javascript:OpenDialog()" class="btn btn-primary">
Lägg till ny
</a>
</div>
As can be seen the table is a partial view and here it is:
<table class="table table-striped table-bordered table-hover" id="sample_1">
<thead>
<tr>
<th>Projekt</th>
<th>Mitt Datum</th>
<th>%</th>
<th>Projektdatum</th>
</tr>
</thead>
<tbody>
#foreach (var project in ViewData["times"] as List<ConsultantProjectTime>)
{
<tr>
<td>
<a href="javascript:OpenDialog2('#project.ID','#project.FK_ProjectID','#project.StartDate.ToShortDateString()','#project.EndDate.ToShortDateString()','#project.Pct');">
#project.Project.ProjectName
</a>
</td>
<td>#(project.StartDate.ToShortDateString() + " - " + project.EndDate.ToShortDateString())</td>
<td>#(project.Pct)%</td>
<td>
#if (project.Project.StartDate.HasValue && project.Project.EndDate.HasValue)
{
#(project.Project.StartDate.Value.ToShortDateString() + " - " + project.Project.EndDate.Value.ToShortDateString())
}
</td>
</tr>
}
</tbody>
And this is my script I run when I choose to add another project:
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 220,
width: 305,
modal: true,
buttons: {
'Spara': function() {
if (!validate()) {
alert('Procent måste vara mellan 0-100');
return false;
}
locstring = "#(Url.Action("Index"))/Update/?";
locstring += '&projectId=' + $('#projectList').val();
locstring += '&startDate=' + $('#startDate').val();
locstring += '&endDate=' + $('#endDate').val();
locstring += '&pct=' + $('#pct').val();
var sid = $('#sId').text();
if (sid != "") {
locstring += '&id=' + sid;
//locstring = "/Delete/" + sid;
}
//window.location = locstring;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function(data) {
//alert(locstring);
$('#dialog').dialog('close');
ReloadTable();
}
});
},
'Avbryt': function() {
$(this).dialog('close');
},
'Ta bort': function() {
var sid = $('#sId').text();
if (sid != "") {
locstring = "#(Url.Action("Index"))/Delete/" + sid;
//locstring += '&delete=true&id=' + sid;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function(data) {
$('#dialog').dialog('close');
ReloadTable();
}
});
Note, when this happends I have no errors in my console.
Found the error but not sure how to solve it, it's my ReloadTable function:
function ReloadTable() {
if (navigator.appName == "Microsoft Internet Explorer") {
//alert('suck..');
window.location.reload();
} else {
$.ajax({
type: "GET",
url: '#(Url.Action("ConsulantTimes"))',
dataType: "html",
success: function(data) {
$('#dialog').dialog('close');
$('#ConsultantTimes').html(data);
}
});
}
}
What you are doing is replacing the entire contents of #ConsultantTimes and replacing it with the data variable. Use $( "sample_1" ).replaceWith(data); instead, or maybe prepend or append.