jQuery <select> Changes Another <select> - html

I am using trying to use jQuery .change() to create two <select> elements whereby the first <select id="state"> is for generating a list of states and the second <select id="city"> is to generate a list of cities.
The values of states and cities will not be hard-coded but generated from values pass from web services.
The list of options to be generated is supposed to work like this: if user selects state from <select id="state"> the selected value will be pass to a web service to retrieve the list to generate the <select id="city"> for cities.
I'm really not sure how to implement this. Can anyone please advise me?

it should look something like
$(function(){
// populate the states list from Ajax
$.ajax( {
url:"/listStates",
type:"GET",
success:function( data ) {
var statesList = data;
if ( typeof(data) == "string" ){
statesList = JSON.parse(data);
}
$.each( statesList, function( index, state ){
$("#state").append($("<option></option>",{value:state.value, text:state.label});
});
},
error:function( result ) {
console.log(["error getting states",result]);
}
});
// register on state list change
$("#state").change( function(){
// on change dispatch an AJAX request for cities and populate cities
$.ajax({ url : "/listCities",
data : {"state": $("#state").val() },
type:'GET',
success:function( data ) {
var citiesList = data; // assuming list object
if ( typeof(data) == "string"){ // but if string
citiesList = JSON.parse( data );
}
$("#city").empty();
$.each(citiesList, function(index,city){
$("#city").append($("<option></option>", {"value":city.value, "text":city.label}));
}
},
error:function( result ){ console.log(["error", result]); }
})
});
This can get you started however I did not follow lint best practices here.
Walk Through
I register for a "change" event on select with id state.
When a change if fired, I invoke an Ajax request to location "/listCities"
I assume this location is called with a "GET" method
I pass along the state that is currently selected - so the server will know which cities to list.
If the Ajax through an error, I log the error to the console.
If the Ajax was a success, I populate the select with id "city" with options containing values for each city and a label.
I assumed the following things while writing the code
You have a route GET /listCities that expects a state.
The response from that route is a JSON containing a list of values and labels for each city. Something like this :
[{ value : "AM" , label : "Amsterdam" }, .... ]
The only things you may need to read about for this example are :
JQuery Ajax Calls
Best Practice To Populate A List With JQuery
If you have any questions, please comment my response, I will be happy to explain/add/modify

You have to follow some steps achieving this:
first when page load populate the first country list via ajax (my assumption)
then create a .change() event with the country list
This will send a request and returns the states list response as per selected country.
you can try test it this way:
$(function(){
$.ajax({
url:your url,
type: 'post',
dataType: 'json', // or your choice of returned data
success: function(data){
$.each(data, function(i, v){
$('<option value="'+v.name+'">'+v.text+'</option>').appendTo('#country');
});
}
});
$('#country').change(function(){
$.ajax({
url:your url,
type: 'post',
dataType: 'json', // or your choice of returned data
success: function(states){
$.each(states, function(i, stt){
$('<option value="'+stt.name+'">'+stt.text+'</option>').appendTo('#states');
});
}
});
$('#states').empty();
});
});

Pretty simple - all you'll have to do is have the two dropdowns, one with the full lists of states and the second (empty) city list will contain only one blank disabled option.
As soon as your states dropdown triggers a change event, you extract the state data and send it via an AJAX call to your server or some web service which will return a list of cities in that state.
You'll then populate the second dropdown with the returned city values.

Related

Search mysql database with node in html

I connected a database to node and am trying to create an HTML page to search the database. I would rather not use EJS. I think I have to use a POST request in the HTML AJAX and connect it with a POST request in node.
Here is what I'm thinking:
app.post("/cities/:city", function(req, res) {
db.hospitalinfo.findAll({
where: { city: req.params.city }
}).then(function (result) {
res.json(result);
console.log("res--->"+result);
console.log("req--->"+req.params.city);
});
});
Here's the HTML:
<form id="author-form" method="POST">
<select id ="dropDownId">
<option value="Opp" >Opp</option>
<option value="Boaz">Boaz</option>
</select>
<input class="SubmitButton" type="submit" id="click" style="font-size:20px;" />
</form>
Now here's where I'm stuck. I need to grab the value from the select statement:
var nameInput = $("#dropDownId :selected");
I don't know how to actually send nameInput to the URL so my post statement will work. I probably don't completely understand how these routes work. This is my first project by myself. I would like to grab the nameInput, send it to the server via AJAX, and search my database with it. Right now it's returning an empty object. Thank you for your help.
You need to make a Ajax call to node server. For that you need to stop the default submit of form.
event.preventDefault();
can be used to stop the normal flow of submitting the form.
Here is an example of ajax call
(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type: "GET", // define the type of HTTP verb we want to use (POST for our form)
url: "http://localhost:5000/example" // the url where we want to POST
data: formData,
dataType: 'json', // what type of data do we expect back from the server
success: function (data) {
console.log(data.result);
// perform required changes
},
error: function (err) {
console.log(err);
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
you can refer this site for more details making ajax calls
I have modified the code taken from there.

How to use REST endpoints to return HTML and JSON in different calls

I'm creating a website where I want to perform CRUD operations to a dataset. For the sake of simplicity, assume a table of books. I understand that example.com/books should return a list of books, and example.com/books/24 should return the book with id 24.
Now, imagine that my list of books is very large, and I want to allow the user to browse the book list using a table with pagination, but as the dataset is very large I want to retrieve only the current page using AJAX.
The question is: should example.com/books return the HTML containing the table with all pagination controls and other widgets? or should it return the data in JSON format? What would be the right way to perform both calls.
Thanks in advance
In your controller you could do something like this:
function index (Request $request){
$books = Book::paginate(10);
if($request->ajax()){
//ajax request
return Response::json(view('books', compact('books'))->render());
}
//html request
return view('books', compact('books'));
}
You can pass a page parameter to the route to navigate to pages.
Example : example.com/books?page=2 will fetch the second page of results.
Suggested Approach
Render the initial request with as html like you would normaly do. Then for the next page, get the second page rendered as an ajax call and append it to the DOM.
return Response::json(view('books', compact('books'))->render());
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
e.preventDefault();
$.ajax({
type: "GET",
url: 'page=' + page,
dataType: 'json',
success:function(json){
alert("Success"+json);
},
error:function(){
alert("Error");
}
});
});
});
Take a look at Laravel Pagination

knockout's viewModel does not get updated

I have the following knockout's viewModel :
var viewModel={
businessName: "",
....
}
I also tried to identify the field like this: businessName: ko.observable("")
Then, I have a load method that requests for a JSon with a newly populated data
And this is how I'm trying to apply the new data:
$.ajax({
//
url: "#Html.Raw(#Url.Action("Load"))",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
success: function (result) {
//OPTION 1:
viewModel.businessName = result.vm.BusinessName;
//OPTION 2:
var viewModel2 = ko.mapping.fromJS(result.vm);
console.log(viewModel2.businessName);
}
});//ajax
As a result:
if I use Option1, I get the new data but it does not get updated on the page.
If I use Option2, it writes "undefined"
Please advise how can I update the new data on the page?
I checked the similar topics but there is no answer that helps
PS
It seems I resolved OPTION 1. But still don't understand why OPTION 2 does not work
ko.observable is a function, not a property. So you get it's value like this:
var whatsTheValue = myVM.MyObservable();
and you set it like this:
myVM.MyObservable(newValue);
This is all in the docs.
Note, however, when using the data-bind syntax in your HTML, you don't need to explicitly unwrap your observable by using the parenthesis because KO is smart enough to do it automatically:
<span data-bind="text: MyObservable"></span>
You have to use ko.observable in the ViewModel and access/write it accordingly.
var myViewModel = {
businessName = ko.observable('')
};
...
$.ajax({
...
success: function(result) {
myViewModel.businessName(result.vm.BusinessName);
},
...
});
Otherwise your view won't have any clue you changed businessName. In the implementation ko.observable, besides actually storing the new value, broadcasts some events to your view, letting it know the stored value changed.

JavaScript MVC Parsing JSON

I am trying to work with a client's API that lets me retrieve a group of orders in json format. I am able to use the code below which will display three alert boxes. The first box shows 200 (am assuming that's the html success code), then I get a blank alert box, then the third box says: [object Object].
In Chrome if I use the F12 key and go to Network Preview I see three sections, the Status which contains a Body section which contains the Orders section. There are 50 orders in the Orders section. Each order has properties such as: order_type: "Pickup", etc. My question is how do I iterate through the actual orders. I don't know the syntax to reach the order, and the properties inside the order.
My end goal is to loop though all 50 orders, assign some of the order properties to JavaScript vars and then pass that into an MVC controller which will insert that order into my database. Basically getting orders from the Clients database via their API and storing them into my local database. I am guessing that I will be using a another ajax call from inside the for first .each loop to post several of the order properties into my database via a call to an MVC controller that will do the database inserts?
Thank you in advance for any help.
$.ajax({
type: 'GET',
url: 'https://api.customer.com/2000105850/orders.json?v=1&key=12345',
success: function (data) {
$.each(data, function (index, element) {
alert(element);
});
}
});
Based on the information you've provided. The first 200 alert would be the count (number_of_orders_in_response). What you're doing with $.each is iterating over the objects properties, not the orders. The orders are a property on the data object. So data.orders is the array you want.
Try this:
$.ajax({
type: 'GET',
url: 'https://api.customer.com/2000105850/orders.json?v=1&key=12345',
success: function (data) {
var orders = data.orders;
var i = orders.length;
while (i--) {
alert(orders[i].order_type);
}
}
});
Also, it looks like there is pagination involved. So you will need to take that into consideration when writing your script to ensure you capture all the pages available, not just the first.
Change the first parameter of $.each from data to data.orders

jQgrid edit form dropdown list has extra quote

I have an MVC2 EditStatesController :
public JsonResult GetStates()
{
string statesToReturn = GetStates(); // returns "1: Alabama; 2: Alaska; 3: Arizona; 4: Arkansas"
return Json(statesToReturn);
}
this is the code that calls the controller:
//get States
var listOfStates = $.ajax({
url: '/EditStates/GetStates',
type: 'POST',
async: false,
success: function(data, result) {
if (!result)
alert('Failure to retrieve States.');
}
}).responseText;
The dropdown has the list of elements, but last element has extra " (double quote), so the last state Wyoming is Wyoming".
I searched other questions, but didn't find a similar one. Do you know why this is happening and how to fix this?
Thank you,
Jenny
The searchoptions can use dataUrl and optionally buildSelect instead of value which you try to use currently.
jqGrid need to construct the HTML fragment like the following:
<select>
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
</select>
So you can either provide the data from an action of your controller directly or provide any other output like JSON output:
[
{"id":1, "name":"Alabama"},
{"id":2, "name":"Alaska"},
{"id":3, "name":"Arizona"},
{"id":4, "name":"Arkansas"}
]
and use buildSelect event handler to convert the JSON data to the HTML fragment with <select>...</select>. See the answer for details.
If you choose the way you will have no problems with any special characters like '"', ':', ';' and so on.