I have a need to add rows to a html table after a successful ajax post. This happens inside of a Modal Popup window which the javascript appends a new line to the parent screens table. The appending is working with the exception of I do not see how to take a field value from the modal and use it as a variable in the javascript .append statement. Below is the current success method for the ajax call which works correctly except for not getting the NoteText value.
success: function (result) {
var noteText = $("#NoteText").val();
$("#TenantNotesTable").append('<tr><td class="EditButton">#Html.ActionLink("Note Details", "AddTenantNote", New With {.id = 0}, New With {.id = "openDialog", .class = "ButtonControl"})</td><td class="NoteDate">#DateTime.Now.ToShortDateString</td><td class="noteText">NoteText SHOULD SHOW HERE</td><td class="EnterBy">#Model.NoteEnteredBy</td>');
$('#waitMessage').hide();
$("#dialog-edit").dialog().dialog('close');
},
Please excuse this question as I am learning Javascript on a as needed basis.
Found the correct way to fix it I needed to add '+noteText+' in the append statement in the correct location.
Related
I am using jQuery's Ajax method to asynchronously send a POST request with the user "name" and "comment"values entered in a form with IDs of name and comment respectively and the comment.php page returns an HTML message (success or error) that gets shown in the #info div.
So far, everything works perfectly and the comment gets added to the database and is shown at page refresh in the #comments table. Now I just want to add the user's name and comment directly into the comments table but I have a problem, I'm not able to access the name and comment variables from inside the anonymous function that gets called inside the .done() method.
Here's my code:
var name = $('#name').val();
var comment = $('#comment').val();
var data = "name="+name+"&comment="+comment;
$.ajax(
{
type: "POST",
url: "comment.php",
data: data // Provided form data
}
).done
(
function(data) // Returned data from URL endpoint
{
// Show returned message
$('#info').html(data);
var newRowContent = '<tr> <td>'+name+'</td> <td>'+comment+'</td> </tr>';
$(newRowContent).appendTo( $('#comments') );
}
);
Apparently, simply adding name and comment to the anonymous function's arguments doesn't work, and the variables are declared outside the scope, so I'm not sure why they result in empty strings when printed on the table. I'd appreciate the help and an explanation of what I'm not getting here.
UPDATE: Here is an example JSFiddle of what I'm trying to do and it works here.
UPDATE: I think I've identified the problem, the ID selectors I'm using to assign a value from the field's value doesn't work for some reason, which leaves the variables as empty strings and that's also what gets stored in the database.
UPDATE: I finally discovered the reason, the form I'm using is wrapped in a div block with display; none so to only show the form once the user clicks a "show comments" button, and that works. The problem is the jQuery value selector $('').val(); treats "hidden" inputs differently and I've only been able to find answers dated back to 2009-2011 that work for older versions of jQuery and not this one.
I hope someone could answer me with how I can select by ID the value of an input that's inside a div with style of display: none when it gets displayed and filled by the user.
It think this is maybe caused by an "out of scope behavior". You can try to return the data(name,comment) submitted from your URL endpoint and then get those values. Something like:
function(data) // Returned data from URL endpoint
{
// First you need to parse the json data
data = JSON.parse(data);
// Show returned message
$('#info').html(data['info']);
// Then you get the data returned
var newRowContent = '<tr> <td>'+ data['name'] +'</td> <td>'+ data['comment'] +'</td> </tr>';
$(newRowContent).appendTo( $('#comments') );
}
Off course, this assuming that you're returning json data. Hope it helps! ;)
I have fixed the issue, as stated in my 3rd update, the problem was the inputs were in a div with display: none that makes it hidden at page load and only shown later when a button click shows it. The problem lies in how it's shown.
My old approach was copying the HTML enclosed in a div with display: none and id #commentForm to an empty div using the append() method, which caused the input IDs to be present 2 times in the page and thus the $() selector return an empty value.
What I did is change the jQuery to just "unhide" the HTML by removing the style="display: none" as such:
$('#commentForm').removeAttr('style');
That, alone, made the input values to be successfully retrieved with the AJAX code present in my question above. I hope this helps someone who might encounter a similar situation.
Here is my code on plunker (link updated), I'm sorry but I was not able to make it work again as it works in my project but it helps for reading purpose instead of pasting here my code.
$scope.elements = [
{
'value': 'Default text',
'elem_type_name': 'text field'
}, {
'value': 'example#email.com',
'elem_type_name': 'email field'
}];
In fact initially my code works and I'm well able to render the right view, nevertheless in my code I have a submit button at the bottom of my page.
When clicking on it, it generates a new API call to update my current scope variable (elements list).
Some of those could be remain after the API call, some could be removed and some new could be added.
Unfortunately when I click on this submit button the scope is weirdly not well analysed, so if the same element remains with the same id, it is duplicated. If I get a completely new list of elements, I will see the previous elements + the new ones.
It seems that I have the same problem as this one: Another stackoverflow question but in my case after each click on the button I need to empty completely the elements scope variable before each API call.
Do you have any idea ?
Thanks very much in advance
In your call, you could set $scope.elements = '', and then you could assign $scope.elements = response.data, or whatever you are defining the results as. For example:
$http.get('jsonFile.json')
.then(function(jsonData) {
$scope.elements = '';
$scope.elements = jsonData.data;
});
This will clean $scope.elements, and then update with only the new response data.
newbie to coldfusion/jquery/programming general here. So the overview of my problem is this: I have a ticket id that corresponds with a specific row in my database. When I click a button, I would like one of the columns in that row to change values to "In Testing". My issue is that I do not know how to pull that ticket id number into my jquery function, or if this is even possible. My code:
<script src="/TicketFaster/js/jquery-1.11.3.js"></script>
<script src="/TicketFaster/js/scripts.js"></script>
<cfset ticketid="#ticketid#">
<button id="in_testing" type="button">In Testing</button>
my js:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (#ticketid#);
$.ajax({
url: 'ticketcomponent.cfc?method=in_testing',
type: 'POST',
data: {
test: x
}
});
});
});
The big problem is that these pages are being generated dynamically, so each one will have a different ticket id. Therefore, I need to have the ticket id variable be imported rather than just hard coded in to the jquery function. So is this possible? I did not include the query because it works fine when I use it in other places, just getting the data delivered is the tough part. I appreciate any help you can give me :)
Edit: I was requested to post what I'm trying right now.
The original coldfusion is the same so I'm not going to post that again. Here is the js I'm using:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (<cfoutput>#ticketid#</cfoutput>);
alert(x);
});
});
(I also tried without the cfoutput tags)
As you can see, I'm just trying to do a simple alert to check if my variable has been correctly set. Once I get that to work, then the ajax should follow fairly quickly because I have some experience in that.
What is your specific issue?, can you share a jsfiddle?
for dynamic events replace
$("#in_testing").click(function() {});
for
$(document).on('click','#in_testing', function() {});
This value
var x = (#ticketid#);
in jquery is some like that
var x = $('#ticketid').val(); // for value or $('#ticketid') for object
you just have to take account id created dynamically
I have a field named "selectedTime" in a document, this fields stores the selected timings added by user.Adding times is working perfect.This is back-end.
Now I will explain this issue of selecting date from front end.I have given a button add to add times.The custom control of date-time gets added to repeat control on click of Add button.Even if I check in document it shows the list of selected times.Even this works fine.
Now if I want to delete a selected time from repeat control randomly, it deleted that particular record from document, but on the page the last record of the repeat gets disappears,
I was assuming that this is the issue with partial refresh of repeat control,I have even tried that but no result.Full refresh breaks the page.
java script code for the delete button
`var doc:NotesDocument = database.getDocumentByUNID(context.getUrlParameter("refId"))
var selectedTimes:java.util.Vector = doc.getItemValue("selectedTimes");
if(selectedTimes != null){
var sdtString = getComponent("inputHidden1").getValue();
if(selectedTimes.contains(sdtString))
selectedTimes.remove(sdtString);
doc.replaceItemValue("selectedTimes",selectedTimes);
doc.save();
};
var url:XSPUrl = context.getUrl();
view.postScript("window.refresh('"+url+"')");`
I know it is difficult to understand what i want to explain but any suggestion on this will be appreciated.
Even if anybody have any idea to delete the a field values of a documents,In my case field name is "selectedTimes" and the values are added times in repeat control, Please share.
Edit 1:
//Repeat Control
var doc:NotesDocument = database.getDocumentByUNID(context.getUrlParameter("refId"))
var selectedTimes:java.util.Vector = doc.getItemValue("selectedTimes");
return selectedTimes;
Another try could be link the repeat with a viewScope instead of the document:
1) In the event beforeLoadPage/afterLoadPage: Get the value from the document, and put it in a viewScope variable:
// beforeLoadPage event:
// ... get the doc
viewScope.selectedTimes = doc.getItemValue("selectedTimes");
2) In the repeat control, use the viewScope:
<xp:repeat value="#{viewScope.selectedTimes}"...
3) When an update is done, update both the viewScope and the document:
//...update the View Scope variable and get the document:
doc.replaceItemValue("selectedTimes", viewScope.selectedTimes);
This could be a hint if the document would be added as DataSource:
Do you have the document included in the XPage as a DataSource? In that case, try to get and update the NotesXspDocument instead of the Document from the DB:
XPage:
<xp:this.data>
<xp:dominoDocument var="xspDocument"
action="editDocument"
documentId="#{param.unid}">
</xp:dominoDocument>
</xp:this.data>
SSJS code: work directly with the XspDocument
var selectedTimes:java.util.Vector = xspDocument.getItemValue("selectedTimes");
...
xspDocument.replaceItemValue("selectedTimes", selectedTimes);
This could be a hint if the value would not be removed from the document:
In sdtString you are getting a String value:
var sdtString = getComponent("inputHidden1").getValue();
If you have the time values stored as NotesDateTimes, you will get this type of value inside the Vector and the remove method won't find the String and nothing will be removed.
// In a Vector<NotesDateTime> the String cannot be found:
selectedTimes.remove(sdtString);
Be sure you remove the same type of value you get in the Vector
Very confused here.
I have a search box which reads a list of school names from my database. When I select a school, the id (from the db) gets put in a hidden textbox.
I also have a search box which reads a list of courses from my database. However, I made the query so that it only reads the courses from the selected school.
It does that, in theory.
I was planning to pass the school id, which I grab from the hidden box, to the search script which in turn passes it to my database query. However, the variable I put my school id in doesn't seem to be updating.. yet it does. Let me explain.
I come on the page. The school for my test account has id 1. The id number in my hidden box is indeed 1. I search for a school which I know has some courses assigned to it: the id number in the box changes to 3.
I have a JS variable called school_id which I declared outside of my $(document).ready. I assume that means it's global (that's what I got taught even though SO told me once it isn't really the correct way to do this. Still have to look into that). I wrote a function which updates this variable when the school search box loses focus:
$("#school").blur(function() {
school_id = $("#school_id").val();
});
A quick javascript:alert(school_id); in my browser bar also shows the updated variable: it is now 3 instead of 1.
Onto the search script part of my page (excerpt of the script):
script:"/profiel/search_richting?json=true&limit=6&id=" + school_id + "&"
As you can see, I pass the school_id variable to the script here. However, what seems to be happening is that it always passes '1', the default variable when the page loads. It simply ignores the updated variable. Does this string get parsed when the page loads? In other words, as soon as the page loads, does it actually say &id=1? That's the only idea I can come up with why it would always pass '1'.
Is there a way to make this variable update in my script string? Or what would be the best way to solve this? I'm probably missing out on something very simple here again, as usual. Thanks a lot.
EDIT
Updated per request. I added a function getTheString as was suggest and I use the value of this function to get the URL. Still doesn't work though, it still seems to be concatenating before I get a chance to update the var. HOWEVER, with this code, my ajax log says id:[object HTMLInputElement], instead of id:1. Not sure what that means.
<script type="text/javascript">
var school_id;
$(document).ready(function() {
$("#school").blur(function() {
school_id = $("#school_id").val();
});
// zoekfunctie
var scholen = {
script:"/profiel/search_school?json=true&limit=6&",
varname:"input",
json:true,
shownoresults:false,
maxresults:6,
callback: function (obj) { document.getElementById('school_id').value = obj.id; }
};
var as_json = new bsn.AutoSuggest('school', scholen);
var richtingen = {
script: getTheString(),
varname:"input",
json:true,
shownoresults:true,
maxresults:6
};
var as_json2 = new bsn.AutoSuggest('studierichting', richtingen);
});
function getTheString() {
return "/profiel/search_richting?json=true&limit=6&id=" + school_id + "&";
}
</script>
This is because the URL is static, it is not updated as the ID changes.
You should update the URL as part of the code you wrote to get the ID:
$("#school").blur(function() {
school_id = $("#school_id").val();
// update URL here ...
});
Aren't you concatenating script:"/profiel/search_richting?json=true&limit=6&id=" + school_id + "&" before the event is fired and the var updated?
Okay. So the problem was my third party plug-in instead of the code I wrote. I fixed this by editing the code of the autoSuggest plugin so it now includes my id field in the AJAX request.
var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp)+"&id="+ $("#school_id").val();
Thanks to everyone who tried to help me out!