What I am trying to do is retrieve the record (object) in the database that is the most recent in relation to the record that the user is entering. And get a specific property of that object and use it in a simple subtraction conditional statement.
JavaScript:
<script type="text/javascript">
$('#DialogTime').dialog({
autoOpen: false,
width: 600,
modal: true,
buttons: {
"Confirm": function () {
$("#DSCreateForm").submit();
},
"Cancel": function () { $(this).dialog("close"); }
}
});
$('.btnSubmitDS').on("click", function (e) {
// this is where the conditional statement needs to be.
{
e.preventDefault();
$(function () {
$('#DialogHighFlightTime').dialog('open')
});
}
});
</script>
Now, the view that has this script on it, is a form... and once the user hits submit, the record they just submitted will become the last row in the table.. so I need to get the property value from the row above the one the user just entered.
I know how to write the conditional statement.. I just need to know how to retrieve the right record.
I might be going about this all wrong, but I don't know how else to retrieve record that is closest to the record that the user just entered.
Any help is appreciated.
If you have a insert timestamp associated with the records, you may consider sorting the results in descending order,skip the first one (the one just got inserted) and take the first item.
LINQ might be handy.
Something like
var secondLastRecord = db.Issues.OrderByDescending(s=>s.CreatedTime).Skip(1).Take(1);
If you want to limit this to a specific user, you might consider adding other condition with a where clause.
var userIdToCheck=324;
var secondLastRecord = db.Issues.
.Where(c=>c.CreatedById==userIdToCheck)
.OrderByDescending(s=>s.CreatedTime).Skip(1).Take(1);
Assuming db is your DbContext object. If you are using non EF data access layer, you can still use the LINQ OrderByDescending-Skip-Take approach. Replace db.Issues with any IEnumerable<T> which represnts your table data.
Also, to get this in javascript, you need to make an ajax call to server action method where you will execute this code and return it.
Related
I'm working on my first HTML form that performs an AJAX HTTP POST using jQuery. When a user makes a change to an input text field and tabs out of the field it triggers the AJAX script which in turn calls a PHP script which performs a database update.
I've got this working successfully for my first input field - I would now like to extend this to a 2nd, 3rd etc input fields but want to try and avoid having multiple scripts that perform very similar functions. I'm new to jQuery and AJAX so learning the syntax as I go.
Here's my input fields:
Manager
Phone
Here's my Javascript that is working on the storeManager input field:
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){
var storeManager = $("#storeManager").val();
$.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
$("#managerRow").addClass("success");
}).fail(function () {
// no data available in this context
$("#managerRow").addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
});
});
});
</script>
I essentially need to branch and pass an additional POST parameter to the editProject.php script so it knows which database field to update, and then conditionally add a class to the appropriate row.
Everything I've tried breaks the script when I try and get it to branch or pass a parameter based on the input field that is being edited. I haven't been able to find any examples that show the correct syntax to have the one script that is called by different input fields - I'm presuming this is possible instead of having multiple versions of the same script acting on different fields.
This works for multiple fields. Just call the same function from different input fields. I just broke your code into two parts.
1. onChange function of each individual field, and
2. function call by passing the field parameters.
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){ yourFunction(this) }):
$("#worker").change(function(){ yourFunction(this) }):
$("#someX").change(function(){ yourFunction(this) }):
yourFunction(field)
{
var value = $(field).val();
var inputId=field.id;
$.post('editProject.php', { inputValue: value, id: inputId }, function(data) {
$('#'+inputId+'Row').addClass("success"); // (this looks like: *#storeManagerRow* ) you can change your Row id's accordingly to make your work easier. Eg: for **#storeManager** make this id as **storeManagerRow**
}).fail(function () {
// no data available in this context
$('#'+inputId+'Row').addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
});
});
</script>
You just try to post a value. for example type. Which should contain some value for identify the ajax call.
If it is for login, then add type = 'login'. Then check the value of $_POST['type'] and write php according to it
sample.php
if(isset($_POST['type']))
{
if($_POST['type'] == 'login')
{
//your code goes here
}
}
you can use this kind of code :
$("#storeManager, #Manager, #Phone").change(function(){
You could do something like this using :input or a class that they all have
$(":input").on("change", function(){
var text = $(this).val();
var idOfInput = $(this).attr("id");
//your post to php function using the above variables
});
From this you could post the id of the input to your php script using the idOfInput variable which you could then on the php side use a case switch to do a different query depending on which id is sent to the php
Here is a jsfiddle showing how it works
I've been trying to do Meteor's leaderboard example, and I'm stuck at the second exercise, resetting the scores. So far, the furthest I've got is this:
// On server startup, create some players if the database is empty.
if (Meteor.isServer) {
Meteor.startup(function () {
if (Players.find().count() === 0) {
var names = ["Ada Lovelace",
"Grace Hopper",
"Marie Curie",
"Carl Friedrich Gauss",
"Nikola Tesla",
"Claude Shannon"];
for (var i = 0; i < names.length; i++)
Players.insert({name: names[i]}, {score: Math.floor(Random.fraction()*10)*5});
}
});
Meteor.methods({
whymanwhy: function(){
Players.update({},{score: Math.floor(Random.fraction()*10)*5});
},
}
)};
And then to use the whymanwhy method I have a section like this in if(Meteor.isClient)
Template.leaderboard.events({
'click input#resetscore': function(){Meteor.call("whymanwhy"); }
});
The problem with this is that {} is supposed to select all the documents in MongoDB collection, but instead it creates a new blank scientist with a random score. Why? {} is supposed to select everything. I tried "_id" : { $exists : true }, but it's a kludge, I think. Plus it behaved the same as {}.
Is there a more elegant way to do this? The meteor webpage says:
Make a button that resets everyone's score to a random number. (There
is already code to do this in the server startup code. Can you factor
some of this code out and have it run on both the client and the
server?)
Well, to run this on the client first, instead of using a method to the server and having the results pushed back to the client, I would need to explicitly specify the _ids of each document in the collection, otherwise I will run into the "Error: Not permitted. Untrusted code may only update documents by ID. [403]". But how can I get that? Or should I just make it easy and use collection.allow()? Or is that the only way?
I think you are missing two things:
you need to pass the option, {multi: true}, to update or it will only ever change one record.
if you only want to change some fields of a document you need to use $set. Otherwise update assumes you are providing the complete new document you want and replaces the original.
So I think the correct function is:
Players.update({},{$set: {score: Math.floor(Random.fraction()*10)*5}}, {multi:true});
The documentation on this is pretty thorough.
I have a SelectList representing a delivery type for an order.
The delivery type reference data has the usual code/description, but also an additional boolean property which indicates if further information needs to be entered for the type selected.
So for Emergency deliveries additional data is required. The additional data entry fields would be set visible if Emergency was selected, otherwise hidden
My ViewModel contains <List>ReferenceDeliveryTypes which contains the 3 properties.
I have created a SelectListItems from the ViewModel data
#Html.DropDownListFor(model => model.DeliveryTypeCode,
new SelectList(Model.ReferenceDeliveryTypes as System.Collections.IEnumerable,
"DeliveryTypeCode", "DeliveryTypeDescription"), new { id = "ddlDeliveryType" })
How can I call a jQuery function on change of the delivery type, pass the selected code and check the Model.ReferenceDeliveryTypes for that code to see if the additional data property is true/false to show/hide the additional fields div?
I have managed to get the jQuery function called to pass the value.
$(function () {
$('#ddlDeliveryType').change(function () {
var value = $(this).val();
alert(value);
});
});
I don't know of any way you can do this using a select list but I suggest the following options:
Simple but a hack - add a string to the end of DeliveryTypeDescription, for example (emergency delivery) and check for that in your change function
Another hack - multiply DeliveryTypeCode by 10 and add 1 on if it's an emergency delivery (and then use mod 10 in your change function)
Use an Ajax lookup function
Load a JavaScript lookup table with the codes which require an emergency delivery
Use a hidden field in your form which contains a string list of the emergency codes with a suitable separator
Good luck
UPDATE
For the hidden field option if you use something like 123|456|789| and then use indexOf having appended a | to the selected ID.
I converted the Model.ReferenceDeliveryTypes to a JSON list which allowed me to access it from the jQuery.
Possibly not the best way, but it allows me to do everything on the client rather than making an AJAX call back. I can now show/hide the inside the if block.
Thought it worth documenting what I did as I've not come across the #Html.Raw(Json.Encode before and it might prove useful for someone who wants to access model data from within jQuery.
Any additional comments welcome.
<script type="text/javascript">
var ReferenceDeliveryTypeJsonList=#Html.Raw(Json.Encode(Model.ReferenceDeliveryTypes))
</script>
#Html.DropDownListFor(model => model.DeliveryTypeCode,
new SelectList(Model.ReferenceDeliveryTypes.ReferenceDeliveryType as System.Collections.IEnumerable,
"DeliveryTypeCode", "DeliveryTypeDescription"), new { id = "ddlDeliveryType" })
$(function () {
$('#ddlDeliveryType').change(function () {
var selectedDT= $(this).val();
$.each(ReferenceDeliveryTypeJsonList, function (index, item) {
if (selectedDT === item.DeliveryTypeCode) {
alert("match " + selectedDT);
}
});
});
});
I am new to jQuery. I have created a form where I hide some fields. I have created a function on the click of a button field. Here in this function definition I unhide the hidden fields one being my text field and another a button. I code that I use is:
finishOrder: function() {
document.getElementById("create-pwd").style.display = "block"
document.getElementById("finish-ok").style.display = "block" // this is my another button
// do further processing
},
Now on the click of another button (please see the comment "this is my another button") I call another function like this:
FinishcheckPassword: function() {
var pas = document.getElementById("pos-password")
var user = new db.web.Model("res.users").get_func("read")(this.session.uid, ['password']).pipe(function(result) {
if(pas.value == result.password){
return true
});
},
After the if condition returns true value, I want to the control to be transferred to the first function where I can do further processing. Is it possible, if yes how can this be achieved? Any help will be appreciated.
Sure, something like this:
$('#finish-ok').click(function(){
if(FinishcheckPassword()){
finishOrder();
}
}
Of course, this is probably not exactly the right code for you. The fact that you are assigning all your functions with : rather than = suggests that they are inside of some larger object. Therefore, they'd have to be called like myObject.finishOrder(). But the general approach of what I wrote above will work.
As a couple side notes, you have tagged the question with jQuery and refer to it in your post, but there isn't actually a single line of jQuery in your code.
Here is, more or less, the general workflow:
The user types something on a input element;
Onkeyup, it will grab values from our backend script, and choose one.
After choosing, onblur, we will grab that value and use it to query the database for some data,
With the data returned from the DB he will execute other commands on an external server.
Then it will grab that values and use them to fill some input elements that are there waiting to be filled in, once the user chooses is option from the autocomplete element.
With that data in place, the user can then change the values, and hit save for yet another "ajax adventure..."
So, here, we are on steps 1 and 2 only (so I believe):
This is what I have been able to accomplish with the help of this article. That I'm trying to understand and adapt.
//1) WHEN WILL verificaInput BE CALLED?
$(document).ready(function verificaInput(inputString) {
if (inputString.length == 0) {
$('#sugestoes').hide();
} else {
$.post('modelAutocompleteTeste.php',
{nomeDominio: $('#nome-dominio').val()},
function(dadosResposta){
if(inputString.length > 3) {
$('#sugestoes').show();
//2) WHAT SHOULD I PUT HERE?
}
},
"json"
);
}
}
About 1: We must NOT use inline js calls. Where should we call/use the events like onkeyup and onblur etc?
About 2:
view source
print?
function(dadosResposta){
This will contain the response from our server side script, if the input string is greater then 3, it will show our suggestions. Now, inside this suggestion I will need to populate some elements (<li>) containing ALL the data returned in json format from our server side script (it's PHP - using json_encode())?
If so, is this the proper place to loop over and create the li elements?
More then answers, I would like to ask for some advice; I'm lost and stuck.
To get you started...
$(document).ready(function() {
$('#your_input_field').bind('keyup', function() {
var theVal = $(this).val();
if (theVal.length > 3) {
verificaInput(theVal);
} else {
$('#sugestoes').hide();
}
});
});
function verificaInput(inputString) {
if (inputString.length == 0) {// this will never be true
$('#sugestoes').hide();// so this will never be necessary
} else {
$.post('modelAutocompleteTeste.php',
{nomeDominio: $('#nome-dominio').val()},
function(dadosResposta){
if(inputString.length > 3) {
$('#sugestoes').show();
//2 here you should include a function name that will allow interaction with the provided list
}
},
"json"
);
}
}