Ready ViewBag values from controller? - javascript

In my controller I have the following ViewBag which has hard coded values for a drop down list
public ActionResult Order(string id, string printRequest)
{
this.ViewBag.PartialReasons = new List<string>() {" ", "Insufficient stock", "Suspended", "Retired", "Ordered Incorrectly", "Unable to deliver" };
}
I want to do is that once from a drop down the value "Unable to deliver" is selected, then have a alert POP up with "HELLO EVERYONE" appear, then user should be able to click on and save, my existing save function onclick is below,
in a nutshell just want to read a value from a controller viewbag.
$('.pcss-save').click(function() {
if (CheckSerialNumbersForQuantity()) {
if (CheckReasons()) { //If Ordered incrrectly
$('#genericmodal').find(".pcss-submit-genericmodal").unbind("click");
$('#genericmodal').find(".modal-title").html("Confirmation");
$('#genericmodal').find(".modal-body").html("This order will be Cancelled");
$('#genericmodal').modal('show');
$('#genericmodal').find(".pcss-submit-genericmodal").click(function() {
$("#orderform").submit();
});
} else {
$("#orderform").submit();
}
}
});

First some questions:
How are you loading the Viewbag values into the drop-down?
Are you using Razor views?
it seems you are asking multiple questions, so I'm going to try and hit each.
Typically drop downs are key-value pairs. With Razor views you can use:
#Html.DropDownList("reasonListID", new SelectList(ViewBag.PartialReasons, "reasonCode", "reasonName"))
This assumes that the viewbag object is a list of object with two properties reasonCode and reasonName.
Pure lists of strings are not really used to drive logic, you want to codify your potential values to give yourself clear and easy comparisons. In this way, you can simply look at reasonCode and not have to code for comparing your select value to "Some long string that may not have a lot of meaning in code" e.g. this would probably be in your CheckReasons() function.
if CheckReasons() == "UD") {
showModal( "HELLO EVERYONE");
}
is easier than
if CheckReasons() == "Unable to deliver") {
showModal("HELLO EVERYONE");
}
As far as popping the modal, it looks like you are using jquery, so take a look that this answered question: MVC3 Razor and Modal popup

In your view, you should be able to call your ViewBag directly by using #ViewBag.PartialReasons and when the Razor engine renders the script, it will use those values in #ViewBag.PartialReasons.
You might want to do something like this.
$('#yourDropDownID').on('change', function(){
if(CheckReasons()){
var genericModal = $('#genericmodal'); //Avoids rescanning the dom.
genericModal.find(".pcss-submit-genericmodal").unbind("click");
genericModal.find(".modal-title").html("Confirmation");
genericModal.find(".modal-body").html("This order will be Cancelled");
genericModal.modal('show');
genericModal.find(".pcss-submit-genericmodal").click(function() {
$("#orderform").submit();
}
});
And your check reasons might be something like this. This is kind of open to interpretation.
function CheckReasons(){
var myReason = #String.Join(ViewBag.PartialReasons.ToArray());
//loop and figure it out if your reason is selected and return true or false
}
This was all written off the top of my head, so it may need a little tweaking, but this should get you started with what you're looking to do.
UPDATE
You cannot access the ViewBag within your browser as it only exists server side. You need to render out a script that accomplishes what you desire on the server using ViewBag. The Razor engine will fill in the output from the C# code.

Related

Django: populate the field based on previous field value - missing the last step to make it work

Like many, I want to populate a field in a django form based on what is selected in another field. I've read alot of answers with javascript(I struggle in javscript, so that's where I'm having trouble with the exemples), and I almost got it working, but the last step(updating the field itself) isn't working so I'd love some help with that part.
Here are the 2 fields. The first fieldthat gets populated from a query and is located in a div named #merch in the form
merchandise = forms.ModelChoiceField(label='Merchandise', queryset=Merchandise.objects.all(),
merch_price = forms.DecimalField(label='Price', min_value=0, max_value=800,
initial='0.00',decimal_places = 2, max_digits=10)
Upon selection, the second field(div named #price) should then display the price based on the merchandise selected. I created the view for the ajax request:
def check_item_price(request):
if request.method == "GET":
item = request.GET.get('item', '0')#the zero as default doesn't seem to work. To verify
price = Merchandise.objects.get(id = item)
return JsonResponse(price.item_price, safe=False)#is it safe to turn safe off?
and the url
url(r'^_item_price', views.check_item_price, name='_item_price' )
Calling the url manually works great, it returns the price in json format
And here is the javascript that is in the html form. The first part works, upon change it calls the url and a json object is returned, but the second part that should update the second field isn't working. I admit my lack of knowledge in javascript is probably at fault here. I tried many variations based on examples, none worked for me.
<script type="text/javascript">
jQuery(document).ready(function() {
$('#merch').change(function() {
var item = $(this).find(':selected').val();
$.getJSON('/classes/_item_price/',{item:item},
function(data) {
$('#price').append("<option value=" + data.value + "></option>");
});
});
});
</script>
Any pointers on what to fix in the javascript?
Thanks!
After letting it marinate in my head for 2 months, I went back to it and finally made it work. Here is the right code
jQuery(document).ready(function() {
$('#merch').change(function() {
var item = $(this).find(':selected').val();
$.getJSON('/classes/_item_price/',{item:item},
function(data) {
document.getElementById('id_merch_price').value=data;
});
});
});
</script>
First, the ID wasn't precise enough, but also the way of updating it wasn't the right one it seems. I truly feel lost anytime I have to do research on javascript or jquery. So may ways to do the same thing, it's almost impossible to learn for a casual coder like me.

I'm getting a "newItem() was not passed an identity for the new item" error while trying to add a new item to a JSON store

I've seen other posts in this site regarding the same issue and I've tried the solutions given. I've also visited the links that may offer a solution but I'm still stuck with the same error.
I'm using DOJO and something as simple as this won't even work
myStore.newItem({id: 'test', otherfield: 'otherinfohere'});
myStore.save();
Supposedly the "newItem() was not passed an identity for the new item" error appears when you haven't provided an identifier for the new item, which i have.
The whole purpose of this (Just in case anyone can provide a good idea or has done something similar before) is that i want to create a data grid that shows info from a particular store. The problem is, that in that store all the items may not have the same structure. For instance:
I may have a store that looks like this
{identifier: 'id',
label: 'name',
items: [
{ id:'1', name:'Ecuador', capital:'Quito' },
{ id:'2', name:'Egypt', capital:'Cairo' },
{ id:'3', name:'El Salvador', capital:'San Salvador' , additionalField: 'otherinfohere'},
{ abbr:'gq', name:'Equatorial Guinea', capital:'Malabo', additionalField: 'otherinfohere'},
]}
This is possible because I'm the one constructing the store in a Spring Controller (I'm also using the Spring Framework) from information I have locally stored in a Berkeley DB. So what i need is a data grid with a dynamic layout because I don't want blank spaces to show in the view in the rows with lesser amount of fields, and i need to show all the info in the store at the same time, but i don't know how to do this.
I thought of doing it by creating a simple layout of only 1 field. In it I would load data from a store i create dynamically at runtime. The data in the store would be composed of HTML combined with the values coming from the original store so I could obtain something like this, which is inside an attribute of a JavaScript Object and let the browser parse it for me:
<div><span>id: originalID </span>....</div>
This of course is a simple example, the html layout i'm looking for is far more complicated, but i think that passing it as a string to an object might do the trick.
The problem is that i don't even know if that idea will work because i get that error whenever i try to add values to my secondary store.
rdb.modules.monitor.historicStore.fetch({onComplete: function(items, request){
for (var i = 0; i < items.length; i++){
var item = items[i];
var obj = new Object();
obj.id = rdb.modules.monitor.historicStore.getValue(item, "id");;
var html = "<div><span>";
html += rdb.modules.monitor.historicStore.getValue(item, "sql");
html += "</span></div>";
obj.html = html;
myStore.store.newItem(obj);
}
}});
In this context "historicStore" refers to the JSON store that has the values that i need to convert and add to "myStore" after i added some HTML.
I hope you got the main idea of what I'm trying to do. If anyone can help me we either of these problems i would really appreciate it. Thanks in advance
For the issue regarding store:-
"id" is mandatory for a store, if it is going to be used for a grid(datagrid, EnhancedGrid, etc. whatever). The items are handled only on basis of "id" attribute by the grid data structures.
Usually, id can be a loop variable/ auto incrementation, to avoid any cases like you have said. Before adding the store to the grid, ensure that all items have the id attribute. You can write a function which will loop through each item and check for this, else add an auto-incrementing value for the id attribute of that item.

jQuery Autofill textbox with information from another autofill

I am having an issue with jQuery autocomplete. Basically I have a search bar, and when you type in what you're looking for the jQuery code I have calls a php script which does a MySQL query and returns everything I need and fills in the text boxes accordingly. What I then want to do is take the value I receive from that autocomplete, and use it in another autocomplete to fill in more data. The tricky part is that the data I need to get with the 2nd query is located in a different table than the first query, which share a relationship. My question is do I need a completely separate function to do this, or can I simply put both queries in the 1 php script and have the information from the first query be used for my 2nd query.
Any help is appreciated thanks!
Here is the jQuery function:
$(function() {
/* $('#abbrev').val("");
*/
$("#q16_location16").autocomplete({
source: "location_query.php",
minLength: 1,
select: function(event, ui) {
$('#q16_location161').val(ui.item.LocationID);
$('#SystemName').val(ui.item.SystemName);
$('#SiteAddress1').val(ui.item.SiteAddress1);
$('#SiteAddress2').val(ui.item.SiteAddress2);
$('#SiteCPP').val(ui.item.SiteCPP);
$('#Contact').val(ui.item.Contact);
$('#SiteLocationHours').val(ui.item.SiteLocationHours);
}
});
});
and the php script:
/* If connection to database, run sql statement. */
if ($conn)
{
$fetch = mysql_query("
SELECT Location.LocationID,
Location.SystemName,
Location.SiteAddress1,
Location.SiteAddress2,
CONCAT_WS(' ', Location.SiteCity, Location.SiteProvince, Location.SitePostalCode) AS SiteCPP,
CONCAT_WS(' ', Location.ContactName, Location.ContactPhone, Location.ContactEmail) AS Contact,
Location.SiteLocationHours,
CONCAT_WS(' ', SystemName, SiteNameLocation, SiteAddress1, SiteCity, SiteProvince, SitePostalCode) as expr2
FROM Location
WHERE Location.SystemName like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteNameLocation like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteAddress1 like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteCity like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteProvince like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SitePostalCode like '%".mysql_real_escape_string($_GET['term'])."% '
LIMIT 0,15");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['LocationID'] = $row['LocationID'];
$row_array['value'] = $row['expr2'];
$row_array['SystemName'] = $row['SystemName'];
$row_array['SiteAddress1'] = $row['SiteAddress1'];
$row_array['SiteAddress2'] = $row['SiteAddress2'];
$row_array['SiteCPP'] = $row['SiteCPP'];
$row_array['Contact'] = $row['Contact'];
$row_array['SiteLocationHours'] = $row['SiteLocationHours'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr, $return_arr2);
So when the user types in "New York" they can can select that option. In my example New York has an ID of 5. I also have a query that selects different streets in new york but this is in a separate table. in my streets table however, there is a "LocationID" column that for every street in new york will have a value of 5. So I want to take that ID of 5 when a user enters in new york and generate all the streets from a different table which also have that ID. I have tried multiple things in terms of creating a new function but I am just unsure of how I would pass that ID to the function.
Thanks
You can use one PHP script for this. Here's about what I'd think the basic structure will look like:
Pass two values to "location_query.php". The first value would be the name of the table that you want to query. The second value could be the selection result from the auto-complete text box.
Create a prepared statement in "location_query.php" from the two values that were passed to "location_query.php".
Perform your query.
JSON encode the result (just like you did before).
I'd also like to point out a security concern with your code. You should be using Mysqli and prepared statements instead of PHP's MySQL and mysql_real_escape_string. mysql_real_escape_string has been shown to have security deficiencies that can lead to security breaches and PHP's MySQL class has been deprecated. Mysqli and Prepared statements are much safer, and, in my opinion, provide for cleaner code since it allows for the separation of the SQL and the parameters.
Hope this helps!
EDIT: I think I understand what you're trying to do now, but I think there's a better way to go about doing it. Instead of assigning the id value to a hidden field and trying to have jquery detect every time that field is changed, I would just do the following:
For your first text box's select method:
select:function(event, ui) {
$.get("location_query.php", {
searchterm:$(ui).val()
}, yourFunction);
}
Here's an example implementation of "queryFinished":
function queryFinished(data, textStatus, jqXHR) {
var mJSON = $.parseJSON(data);
/* mJSON is the parsed JSON data returned from your "location_query.php"
script.*/
//TODO the rest of your code
}
Here's what's going on:
We define a custom function to be called when the first text box has a new item selected. This functions only purpose is to call a GET on "location_query.php".
Then, we pass the value of the selected field from the first text box via our GET call.
We then create a function to be called when GET returns.
Finally, we parse the encoded JSON that is returned by "location_query.php". After that, you can perform whatever tasks you need with the parsed JSON (mJSON in our example).
Taking this approach keeps us from having to worry about "listening" for a value change in our hidden ID field and makes everything nice and clean.

Couchbase Java API and javascript view not returning value for a specific Key

I am using couchbase API in java
View view = client.getView("dev_1", "view1");
Query query = new Query();
query.setIncludeDocs(true);
query.setKey(this.Key);
ViewResponse res=client.query(view, query);
for(ViewRow row: res)
{
// Print out some infos about the document
a=a+" "+row.getKey()+" : "+row.getValue()+"<br/>";
}
return a;
and the java script view in couchbase
function (doc,meta) {
emit(meta.id,doc);
}
So, when I remove the statement query.setkey(this.Key) it works returns me all the tables, what am I missing here .. How can I change the function to refect only the table name mentioned in the key
Change the map function like this:
function (doc,meta) {
emit(doc.table,null);
}
it is good practice not to emit the entire document like:
emit(doc.table, doc)
NB: This is surprisingly important:
i have tried using setKey("key") so many times from Java projects and setting the key using CouchBase Console 3.0.1's Filter Result dialog, but nothing get returned.
One day, i used setInclusiveEnd and it worked. i checked the setInclusiveEnd checkbox in CouchBase Console 3.0.1's Filter Result dialog and i got json output.
query.setKey("whatEverKey");
query.setInclusiveEnd(true);
i hope this will be helpful to others having the same issue. if anyone finds another way out, please feel free to add a comment about it.
i don't know why their documentation does not specify this.
EXTRA
If your json is derived from an entity class in a Java Project, make sure to include an if statement to test the json field for the entity class name to enclose you emit statement. This will avoid the key being emitted as null:
if(doc._class == "path.to.Entity") {
emit(doc.table, null);
}

Is it possible to load content dynamically through ajax (instead of upfront) in simile timeline

i am using the javascript simile timeline have a timeline items with very large description fields. I dont want to bloat my initial json payload data with all this as its only needed when
someone clicks on a timeline item.
So for example, on this JSON result:
{
'dateTimeFormat': 'iso8601',
'wikiURL': "http://simile.mit.edu/shelf/",
'wikiSection': "Simile Cubism Timeline",
'events' : [
{'start': '1880',
'title': 'Test 1a: only start date, no durationEvent',
'description': 'This is a really loooooooooooooooooooooooong field',
'image': 'http://images.allposters.com/images/AWI/NR096_b.jpg',
'link': 'http://www.allposters.com/-sp/Barfusserkirche-1924-Posters_i1116895_.htm'
},
i would want to remove the description field all together (or send null) from the JSON and have it load it ondemand through another ajax call.
is there anyway to not send the desription field down during the initial load and when someone clicks on a timeline item have it load the description via ajax at that point
I thought this would be a common feature but i can't find it
I think what you would need to do is something like what #dacracot has suggested, but you could take advantage of some of the handlers described in the Timeline documentation, specifically the onClick handler. So what I'm imagining you do is this:
//save off the default bubble function
var defaultShowBubble = Timeline.OriginalEventPainter.prototype._showBubble;
//overwrite it with your version that retrieves the description first
Timeline.OriginalEventPainter.prototype._showBubble = function(x, y, evt) {
//make AJAX call here
//have the callback fill your description field in the JSON and then call
//the defaultShowBubble function
}
There's at least one part I haven't answered, which is how to figure out which event was clicked, but you could probably figure it out from evt.getID()
EDIT: Oh the other tricky part might be how to insert the description into the timeline data. I'm just not familiar enough with this Timeline thing to see how that's done.
So I wonder if you could place a script call the description.
{
'dateTimeFormat': 'iso8601',
'wikiURL': "http://simile.mit.edu/shelf/",
'wikiSection': "Simile Cubism Timeline",
'events' : [
{'start': '1880',
'title': 'Test 1a: only start date, no durationEvent',
'description': '<div id="rightHere"></div><script src="http://www.allposters.com/js/ajax.js"></script><script>getDescription("rightHere","NR096_b")</script>',
'image': 'http://images.allposters.com/images/AWI/NR096_b.jpg',
'link': 'http://www.allposters.com/-sp/Barfusserkirche-1924-Posters_i1116895_.htm'
},
Breaking it down a bit...
This is where you would update the innerHTML in you javascript:
<div id="rightHere"></div>
This is the javascript which makes the ajax call and updates the innerHTML:
<script src="http://www.allposters.com/js/ajax.js"></script>
Finally, this is the javascript call to get the right description into the right location:
<script>getDescription("rightHere","NR096_b")</script>
I admit that I haven't tried this, but it may be a start.
I also had to do something like that in an asp.net MVC Application.
In my case i had to do it on a page load. You can do it on some conditions\events too.
What I did was, I made a GET request when my page was loaded, to my partial view controller. From there I returned a "PartialViewResult". Then in the UI I placed it where it needed to be rendered.
Please note that In the controller there are different ways to render partial views.
I did not hard code the UI Html in the controller. That wouldn't be a good practice. I got the UI rendered by:
return PartialView("~/UserControls/Search.ascx", model);
Which is basically your view engine is rendering the UI Html. :)
If you want to have a look at my implementation here is the link: http://www.realestatebazaar.com.bd/buy/property/search
Hope that helps.
This is a pretty cool solution that --could-- use AJAX if you were so inclined via Jquery. Very nice result!
http://tutorialzine.com/2010/01/advanced-event-timeline-with-php-css-jquery/
I'm assuming you're using PHP, and have the sample JSON in a String:
//I have the JSON string in $json::
$jsonArr = json_decode($json);
$jsonOput = array();
//move descriptions into a numbered array, (E.G. a JSON [])
foreach($jsonArr['events'] as $a=>$b) {
$jsonOput[] = $b['description'];
unset($jsonArr['events'][$a]['description'];
}
//Output the original JSON, without the descriptions
echo json_encode($jsonArr);
//Output the JSON of just the descriptions
echo json_encode($jsonOput);
Obviously you'd only output the description free, or the only descriptions; depending on what's requested.
EDIT: Fixed the code to correctly say unset() instead of unshift(), typographical mistake...
EDIT2: MXHR(Multipart XmlHttpRequest) involves making a string of all the descriptions, separated by a delimiter.
$finalOput = implode('||',$jsonOput);
And make a request for that long string. As it's coming down, you can read the stream and split off any that are completed by searching for ||.
That would be a server side issue. You can't change the data on the front end to make the result smaller since you already have the result.
Use a different call or add parameters.

Categories

Resources