Dynamicly Change & Pass variable to partial in rails - javascript

Ok what i have is a Data table that has many records in it and each has there own button to open a dialog box. I want each dialog box to be able to change the data each time thru an AJAX request and is opened to the right data...
Problem is I need the sub variable to change dynamically and be different every time the AJAX script is ran..
Works perfectly the first time... but doesn't change on next load.. not sure if it is the Div replaceWith() or if it is something else.
Button:
<input class="payment_lookup" id="<%= account["account_code"] %>" type="button" value="View Payment Info">
Javascript:
$(".payment_lookup").on("click", function(event) {
var id = event.target.id;
$.ajax({
url: "/billing/" + id + "/toggle_partial",
type: "POST",
success: function (data) {
$("#payment_data").dialog("open");
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
});
$("#payment_data").dialog({
autoOpen: false,
width: $(window).width()-100,
buttons: {
"Close": function(){
$(this).dialog("close");
}
}
});
Routes:
post 'billing/:id/toggle_partial' => "billing#toggle_partial"
Controller:
def toggle_partial
code = params[:id]
#sub = subscription_info(code)
respond_to do |format|
format.js
end
end
def subscription_info(paysysid)
unless paysysid.nil? || paysysid.empty?
Recurly::Account.find(paysysid)
end
end
toggle_partial.js
$("#payment_data_details").replaceWith("<%= escape_javascript(render(:partial => 'payment_data', :sub => #sub )) %>");
Also Tried this:
$("#payment_data_details").replaceWith("<%= escape_javascript(render(:partial => 'payment_data', :locals =>{ :sub => #sub } )) %>");
Update:
I have logged everything:
everything works perfectly to the toggle_partial.js
#sub changes everytime it hits that partial JS file. and it passes the #sub to the partial as sub
BUT:
once sub is set in the view the first time it does not change it on the second request...
2nd UPDATE...
Have it Narrowed Down to The replaceWith() if i change it to append() it appends with the new variable information... but i would rather have it replace the previous information... not actually append....
SOLVED
added $("#payment_data_details").empty(); into the Onclick Javascript so that it emptys the contents of that div. before it trys to set new.
$(".payment_lookup").on("click", function(event) {
var id = event.target.id;
$("#payment_data_details").empty();
$.ajax({
url: "/billing/" + id + "/toggle_partial",
type: "POST",
success: function (data) {
$("#payment_data").dialog("open");
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
});

Related

How to get result from AJAX call before function returns?

My page has a button that calls a Razor Page page handler to delete the associated item.
<a class="delete-item" data-id="#item.Id" asp-page-handler="delete" asp-route-id="#item.Id"><img src="/images/delete.png" title="Delete" /></a>
I've defined a Javascript click handler. I need that handler to return false if the item should not be deleted.
$('.delete-item').on('click', function (e) {
var id = $(this).data('id');
var tr = $(this).closest('tr');
var td = tr.find('.item-description');
// Get number of lease details for this lease
$.ajax({
type: 'GET',
url: '?handler=LeaseDetailCount',
contentType: 'application/json',
dataType: 'json',
data: { 'leaseId': id },
})
.done(function (response) {
var description = 'Delete "' + description + '"? Are you sure? This cannot be undone.\r\n\r\n';
if (response.count == 0)
description += 'This lease has no lease details.'
else
description += 'WARNING: This lease has ' + response.count + ' lease detail(s).';
if (!confirm(description))
return false;
})
.fail(function (response) {
alert(response.responseText);
})
//.always(function (response) {
//});
}
The problem, of course, is that the AJAX call is asynchronous. And so it returns before my confirmation is displayed.
How can I get the code above to work as I want?
If you not wish to set asp-page-handler for the anchor tag, it is possible. As you mentioned
AJAX call is asynchronous
we can't predict which result come first, href navigation or onclick AJAX response
<a class="delete-item" data-id="#item.Id"><img src="/images/delete.png" title="Delete" /></a>
In AJAX .done event, If the confirmation is OK page redirect to delete handler
window.location.href = "/?id=" + id + "&handler=delete";
.done(function (response) {
......
.......
if (!confirm(description))
return false;
else
window.location.href = "/?id=" + id + "&handler=delete";
})

Using pushState inside success function of ajax

I want to append one more param at the end of the current url if the ajax call returns successfully. In this context, we can get back the identifier of the object has been persisted into the database, then append this identifier to the url.
The problem is curationNotes of data was lost if the line window.history.pushState({}, null, newHref); is uncommented. It means we cannot get 'params.curationNotes' in controller. The params.curationNotes, which is a map of user provided values on the form, is null when we try to parse it inside the controller.
Below is the snippet I am working on.
$('#btnSave').on("click", function(event) {
if ($('#curationNotesForm')[0].checkValidity()) {
var curationNotes = buildCurationNotesTC();
"use strict";
event.preventDefault();
$.ajax({
dataType: "text",
type: "POST",
url: $.jummp.createLink("curationNotes", "doAddOrUpdate"),
cache: true,
data: {
curationNotes: curationNotes,
model: "${id}"
},
processData: true,
async: true,
beforeSend: function() {
$('#txtStatus').text("The curation notes are being saved. Please wait...");
},
success: function(response) {
var response = JSON.parse(response);
var href = window.location.href;
if (href.indexOf("&cnId=") < 0) {
var newHref = href + "&cnId=" + response['cnId'];
//window.history.pushState({}, null, newHref);
}
$('#txtStatus').text(response['message']);
},
error: function(jqXHR, textStatus, errorThrown) {
// TODO: the error message doesn't show properly
$('#txtStatus').text("Error: ", jqXHR.responseText + textStatus + errorThrown + JSON.stringify(jqXHR));
}
});
} else {
$('#txtStatus').text("Please check required fields and click Save button again...");
}
});
If I comment this line window.history.pushState({}, null, newHref);, the code is working properly.
Notes: this snippet works fine in any web browsers on Linux but cannot work in any web browser of Windows 10. That's actually ridiculous to me.
Have you ever had any experience with this problem?

Using Rails html tags in jquery

I am wondering if i can use rails tags in html using jquery to reload a table based on a new query. See below:
<table id = "PlyrsTm2" style = float:right>
<tr><th id="PTTitle" colspan=2>List of players on selected team</th></tr>
<tr><th id="PTHRows">Player</th><th id="PTHRows">Team</th></tr>
<% #pl.each do |f| %>
<tr><td class="player"><%= f.Plyr %></td><td class="team"><%= f.Team %></td></tr>
<% end %>
</table>
So i know that i can do this:
$('#PlyrsTm2').html('<table id = "PlyrsTm2" style = float:right><tr><th id="PTTitle" colspan=2>List of players on selected team</th></tr><tr><th id="PTHRows">Player</th><th id="PTHRows">Team</th></tr><tr><td class="player"></td><td class="team"></td></tr></table>
but if I add the rails part to it, then it does not refresh/reload the table. I have looked all over the internet and have not found the solution. I posted a question similar to this, but no one answered and it was voted down because of not enough research(which is not true) because i only post questions to answer that i do not find so can someone help me with this, i would greatly appreciated
RE-UPDATED
it might be helpful to post the ajax and jquery that i am using:
$(document).ready(function(){
$('#showbtn').on('click', function() {
ids = $('#teams').val()
IM = false
$.ajax({
url: "http://localhost:3000/teamplayers.json?resolution="+ids+"&import="+IM,
type:"get",
dataType: "json",
cache: true,
success:function(data){
$('#PlyrsTm2').html(data);
$('#PlyrsTm2').show();
alert(data);
alert("Loading Players....");
},
error: function(error) {
alert("Failed " + console.log(error) + " " + error)
}
});
$('#PlyrsTm2').trigger('create');
});
});
I click a button (#showbtn) which it passes a integer value (#teams) to my controller, which is then changed and here is the table i want it to load:
'<table id = "PlyrsTm2" style = float:right><tr><th id="PTTitle" colspan=2>List of players on selected team</th></tr><tr><th id="PTHRows">Player</th><th id="PTHRows">Team</th></tr><tr><% #pl.each do |f| %><td class="player"><%= f.Plyr %></td><td class="team"><%= f.Team %></td></tr><% end %></table>
As you can see there is Rails html in it, but i do not think it actually re-excutes the rails part <& #pl.each do |f| %>
which then i see the same table that loaded when the page was first opened. So how do i get the rails to re-execute with the new info?
I can post the controller method if needed.
UPDATE
Here is the controller
class TeamplayersController < ApplicationController
before_filter :set_id
before_action :set_id, :set_teamplayer, only: [:show, :edit, :update, :destroy]
# GET /teamplayers
# GET /teamplayers.json
def index
#teamplayers = Teamplayer.all
#fteams = Fteam.all
tid = params[:resolution]
toimport = params[:import]
if tid.nil?
tid = 1
else
tid = tid.to_i;
end
#ids = tid
#pl = Teamplayer.joins(:live_player).where(:teamid => #ids).all << Here should refresh the table
if toimport == "true"
#turl = Fteam.where(:id => #ids).pluck(:TeamUrl)
#turl = #turl[0]
system "rake updateTm:updateA[#{#turl},#{#ids}]"
end
end
i looked at your fiddle.
change this
$('#SelectedTm').replaceWith(test2);
},
error: function(error) {
alert("Failed " + console.log(error) + " " + error)
}
});
$('#SelectedTm').trigger('create');
to this
$('#SelectedTm').html(test2);
$('#SelectedTm').trigger('create');
},
error: function(error) {
alert("Failed " + console.log(error) + " " + error)
}
});
after this you have to de a trigger create like
$('#PlyrsTm2').trigger('create');
modify this
success:function(success){
$('#PlyrsTm2').html(change1);
alert("test 3");
}
to this
success:function(data){
$('#PlyrsTm2').html(data);
$('#PlyrsTm2').trigger('create');
}

using colorbox over another colorbox using jquery/ajax

i have a page where i'm using a with id="emailfrnd", from the following script i successfully implemented the colorbox:
<script type="text/javascript">
$(document).ready(function(){
$("#emailfrnd").colorbox({
inline: true,
href:"#ef",
close:"",
opacity:0.95,
onClosed:function(){
//window.parent.location.reload(true);
}
});
});
</script>
now the new colorbox contains a form with a send button in it of id "emailfrnd_submit" now i had written some validations using the jquery & ajax and if there are no errorMessages i'll get another colorbox and the code is as follows:
if (errorMessage == '') {
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=emailfrnd',
data: "name=" + name + "&email=" + email + "&message=" + message,
async: true,
success: function (data) {
if (data == 1) {
$("#emailfrnd_submit").colorbox({
inline: false,
close: "",
html: "<div style='height:230px;width:400px;display:block;'><p style='color:black;font:16px verdana;'>Your email was successfully sent.</p><br/><p style='color:gray; font:16px verdana;'>Thank you for telling your friend</p><div id='emailfrnd_sub' style='width: 50px;margin-top:30px;float: right;'><input type='submit' value='OK' name='emailfrnd_submit' id='emailfrnd_sub' class='redbut' style='float:right;position:absolute;right: 198px;margin-top: 0px;color:white;'></div></div>",
opacity: 0.95,
onClosed: function () {
//window.parent.location.reload(true);
}
});
//window.location.assign("../index.php");
} else {
alert('mail not send');
}
}
});
} else {
alert(errorMessage);
}
});
upto now i succeed in getting the things as i want, here after doing the validations and onclick the send button according to this code a new colorbox with the html content as above is coming, here i have a Ok button here, i want to make that button as the closing button of this colorbox. how can i get that functionality for the ok button here??
anyone help is much appreciated....thanks in advance.....
You don't need 2 colorboxes to do it.
Why don't you simple create a div which class is message_content and you update it's text according to the ajax status ?
It's much better.
Example:
html:
<div id="colorbox_content"> //#todo: change to colorbox id
<form id="your_form"> //#todo: change according to your form id
</form>
<div class="message_content">
<p class="message"></p>
<span class="close">Close</span>
</div>
</div>
js:
/**
* Close message
*/
jQuery('#colorbox_content').on('click', '.close', function() {
jQuery(this).closest('#message_content').slideUp();
});
/**
* On form submit
*/
if (errorMessage == '') {
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=emailfrnd',
data: "name=" + name + "&email=" + email + "&message=" + message,
async: true,
success: function (data) {
if (data == 1) {
var message = "Your email was successfully sent.";
//window.location.assign("../index.php");
} else {
var message = "Your email was successfully sent.";
}
jQuery('#colorbox_content').slideDown().find('.message').text(message);
}
});
} else {
alert(errorMessage);
}
Update based on this comment:
If you want the same funcionality for different buttons you have to use the same class for them.
here's what do you need.
demo
I changed some ids to classes so you don't need 2 events with the same code.
And here's the las version.
You can see that you can store your options for each kind of colorbox and then pass them thrue parameter.
i got the answer and the fiddile shows how to do it.....::::)))))
http://jsfiddle.net/srinivaswaterdrop01/4vuDC/189/

javascript not working in mvccontrib grid

<% Html.Grid(Model.InnerModel.ParamaterDetails)
.Empty("No data available")
.Columns(column =>
{
column.For(x => x.MinValue).Named("Possible Min Value");
column.For(x => x.MaxValue).Named("Possible Max Value");
column.For(x => x.ScoreValue).Named("Bespoke Score Value");
column.For(x => "<input type='button' name='button' class='btn' id='editOpenDialog' value='Edit' onclick=javascript:editParametersDialog('" + x.ID + "'); />").DoNotEncode();
}).Render(); %>
<%Html.EndForm(); %>
<script type="text/javascript">
function editParametersDialog(ID) {
// Go back to the server and get the data for the road card timetable
$.ajax({
url: "GetDetails",
type: "POST",
data: "ID=" + ID,
dataType: "json",
success: function(data) {
UpdateEditDialog(data);
$('#addEditDialog').dialog('open');
},
error: function(jqXHR, textStatus, errorThrow) { alert(jqXHR); alert(textStatus); }
});
}
function UpdateEditDialog(data) {
$("#MinValue").val(data.MinValue);
$("#MaxValue").val(data.MaxValue);
$("#ScoreValue").val(data.ScoreValue);
}
$(document).ready(function() {
});
</script>
GetDetails above is in controller
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetDetails (int ID)
{
// some code here
}
The onclick call javascript:editParametersDialog does not work. It does not get evoked.
Any clues what I might be doing wrong.
I can figure out that javascript:editParametersDialog does not turn BLUE which is normally the case.
<div id="addEditDialog" ></div>
your code is ok but u didn't put
<div id="addEditDialog"></div>
in the .aspx page.
for show dialog box div tag is must.
$('#addEditDialog').dialog('open');
using this code you say div tag is show as popup.
Do it and try this one again.

Categories