How to hide the table until a string is searched? [duplicate] - javascript

This question already has answers here:
Rendering partial view on button click in ASP.NET MVC
(2 answers)
Closed 4 years ago.
I'm currently interning as part of my school course at a small tech company and one of the projects I'm working on right now is making a web application with MVC.
The manager gave me a SQL database to work with and I've been following this tutorial by Microsoft here to help me build the web app.
Now, the specific thing the manager wants me to do is hiding the table when someone loads the page and when a string is submitted into the search bar, the relevant information in the table matching the string shows up.
I've been looking everywhere, including SO how to do this for a few days now, no matter what code I try it doesn't seem to work! I've been trying different things using HTML and JS, following some examples posted here, I just can't figure out how to do it, the table flashes for a second when I click the search button, I think it's the page refreshing but why?
Here's my controller with the searchBar
public ActionResult Index(string searchString)
{
ViewBag.NameSortParm = String.IsNullOrEmpty (searchString) ? "name_prmrnm" : "";
var person = from p in db.persons
select p;
if (!String.IsNullOrEmpty(searchString))
{
person = person.Where(s => s.name.Contains(searchString));
}
return View(person.ToList());
}
Here's my javascript in the View:
<script type="text/javascript">
function escondeTable(){
var hideTab = document.getElementById("table-class");
if (hideTab.style.display == 'none') {
hideTab.style.display = '';
}
else {
hideTab.style.display == 'none'
}
}
</script>
And here's my form:
<form action="/people/Index" method="post" onsubmit="escondeTable()">
<p class="barraProc">
#Html.TextBox("searchString", "", new { placeholder = "Insira um nome..." })
<input type="button" value="Procurar">
</p>
</form>
Can anyone tell me what I could be using or doing?

You have to use Ajax call. And one option then is this
$( document ).ajaxStart(function() {
var hideTab = document.getElementById("table-class");
hideTab.hide();
});
$( document ).ajaxStop(function() {
var hideTab = document.getElementById("table-class");
hideTab.show();
});

May I suggest a proper approach?
I'd stay away from forms, because they cause a lot of headaches. Just use regular inputs and event listeners.
Also, I'd use a RESTful API, i.e. avoiding a POST method, and using a GET method to get the table data from the backend.
The API should serve the data on this URL localhost/search/critieria, where the user supplies the criteria.
You can render the table in the following way:
fetch("http://localhost/search/" + criteria)
.then((res) => res.json())
.then((data) => {
generateTable(data);
})
.catch((err) => err);
Here is a quick demo I made: https://jsfiddle.net/hwtgeo36/7/
You insert a number, and it returns a Star Wars character from a server (ex. 1 = Luke Skywalker). You can use the same logic with your own server.
Also, you would render your table here, instead of my example that replaces some html.
If you have troubles with this, please write back.

Related

Turning API data into HTML

sorry for the newbie question.
I'm new to using API's and I want to take the data from here
https://api.guildwars2.com/v2/commerce/prices/24615 (specifically the unit price under sells:) and display this in HTML.
This project will be using the unit price data across roughly 100 id's and I'd like to organize these numbers and run some basic math with them.
How can I go about this?
fetch('https://api.guildwars2.com/v2/commerce/prices/24615')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
So far I can get the data into the console, but I'm not sure how to turn this into something I can work with.
There is function in jQuery to make API calls, the following code makes you access api data,
$(document).ready( function() {
var info;
var whitelisted;
var quantity;
$.get("https://api.guildwars2.com/v2/commerce/prices/24615",function(obj){
info = obj['id'];
whitelisted = obj["whitlelisted"]
quantity = obj.buys['quantity']
$("#id1").html("id :"+info);
$("#whitelist").html("whitelisted :"+whitelisted);
$("#quan").html("quantity :"+quantity);
});
});
for more info you could look into the following pen link to the code
ignore these jerk moderators.
In your callback function, where you log myJson, edit your previously created html file,
like if you have a div, <div id="myDiv"> </div>, in the response function do something like this
const myDiv = document.getElementById("myDiv")
myDiv.textContent = myJson.name
And your div will show the name from json, or whatever you need. Play around with these ideas and you'll get far

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.

How to get selected row data from Vaadin Grid with polymer?

I am trying to get the selected row data form vaadin grid using polymer. But I am not able to get.
Here is the my code:
this.mileageGrid = this.$$("#mileageSectionGrid");
this.mileageGrid.addEventListener('selected-items-changed', function() {
var selected = this.mileageGrid.selection.selected();
this.selectedRowData = this.mileageGrid.getSelectedRow();
this.selectedRowData = this.mileageGrid.selection.getSelectedRow();
if (selected.length == 1) {
detailsOpenIndex = selected[0];
this.callback(detailsOpenIndex);
//this.fire("change-mileage", this.mileage);
}
}.bind(this));
I didn't get any idea after searching from google and vaadin grid document also.
Can anybody tell me, how to get selected row data?
These two lines seem to be incorrect, and look more like something from the Vaadin Java framework API:
this.selectedRowData = this.mileageGrid.getSelectedRow();
this.selectedRowData = this.mileageGrid.selection.getSelectedRow();
I think those are probably causing errors in the browser and any following JavaScript is not working. Check for any errors in your browser’s console.
Otherwise I can’t spot any issues in your code (I’m just not sure if you’ve declared detailsOpenIndex and this.callback outside the visible code).

Ready ViewBag values from controller?

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.

JQuery Autocomplete GET & JSON array data security concerns

I am learning JQuery with a MVC3 book. I find that Json data is really easy to use, but it may not be safe.
Consider the scenario, say, I got a CRM with senstive customer infomation. Ajax returns Json array as search results. The search textbox ajax autocomplete also return Json array of senstive keywords from database. etc...They all use GET method.
However, it is said that GET method has vulnerabilities when passing around Json array data:
http://haacked.com/archive/2009/06/25/json-hijacking.aspx
http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
How do you JQuery experts out there go about fixing this issue? Please help.
--- EDIT: ---
#Gren. Awesome. Thank you. Based on your tips, here is what I figured out.
The normal autocomplete returning json array
and a mod one with a json object wrapping the array
Here is the code, assuming we got a global List named txtlst in the controller.cs...
// normal one
public JsonResult AutoCompleteHelper1(string term) {
//if (!Request.IsAjaxRequest()) return null;
var lst = txtlst.Where(s => s.StartsWith(term)).ToList();
var res = lst.Select(x => new { value = x }).ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
//mod one
public JsonResult AutoCompleteHelper2(string term) {
//if (!Request.IsAjaxRequest()) return null;
var lst = txtlst.Where(s => s.StartsWith(term)).ToList();
var res = lst.Select(x => new { value = x }).ToList();
return Json(new { wrapper= res, name="wrapper" }, JsonRequestBehavior.AllowGet);
}
}
and then in the .cshtml file...
<p>Auto Complete Example</p>
<input type="text" name="q" id="MyInput1" data-autocomplete-source="#Url.Action("AutoCompleteHelper1", "Home")"/>
<input type="text" name="q" id="MyInput2" data-autocomplete-source="#Url.Action("AutoCompleteHelper2", "Home")" />
and then in the .js file...
$(document).ready(function () {
// normal autocomplete
$("#MyInput1").autocomplete({ source: $("#MyInput1").attr("data-autocomplete-source") });
// mod autocomplete with a wrap
$("#MyInput2").autocomplete({
source: function (req, add) {
$.getJSON($("#MyInput2").attr("data-autocomplete-source"), req, function (data) {
var suggestions = [];
$.each(data.wrapper, function (i, o) {
suggestions.push(o.value);
});
add(suggestions);
});
}
});
});
--- EDIT 2: ---
Please ignore those comments that are telling me to use POST. They
are not reading the blog links or do not understand the issue.
The other option is to wrap your JSON Arrays within JSON objects. The article and comments in it answered this question.
Edit:
From the article:
The fact that this is a JSON array is important. It turns out that a script that contains a JSON array is a valid JavaScript script and can thus be executed. A script that just contains a JSON object is not a valid JavaScript file.
If you wrap your json array in an object {"myJsonArray":[{"name":"sensitive"},{"name":"data"}]} the HTML script tag would not be able to execute.
Security of an Ajax/JSONP/JSON call is the same exact thing as the security of an http call since Ajax requests are http requests. Nothing changes in how you handle it. You make sure the user is logged in and can access the information.
If you are worried about data being cached, use Post or set the proper no caching headers with the backend.
EDIT:
Things you can do to prevent JOSN from being read is the infinite loop trick. Stick an infinte loop in front of the call, means your Ajax call will have to strip this before using it.
You can use keys, third party site would not have the keys needed to validate the request.
You can check referrers.

Categories

Resources