Passing Select Option to POST request - javascript

I'm very new to web development and I'm trying to pass what the user has selected in a field called accesslevel_id to a POST request, so I can pass it to my database. I'm following the example in my book, but it doesn't seem to work as intended.
My script is the following:
<script>
$(document).ready(function () {
$('#accesslevel_id').on('change', function () {
alert($('#accesslevel_id').val());
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select class="form-control" id="accesslevel_id" onchange="accesslevel_id" title="">
<option>Facility</option>
<option>Division</option>
<option>Corporate</option>
<option>Market</option>
<option>Group</option>
</select>
When on the site and a user selects an option it currently displays None for my print function defined as accesslevel_id = request.POST.get('accesslevel_id'). The next step, which i'm not at yet is to convert the option name into numbers to store into the database. I'm looking for advice on how to accomplish this.

I think you need to post the value of option value when it changes right?
$(document).ready(function () {
$('#accesslevel_id').on('change', function () {
var accesslevel_id = $(this).val();
$.ajax({url: "action-page",
data:"accesslevel_id="+accesslevel_id,
type: "POST",
success: function(result){
alert(result);
}
});
});
});

Related

Add HTML code triggered by selection changed

I have a simple select into my HTML code (a dropdown menu).
HTML
<select name="razza" onchange="razzaChanged()">
<?php while ($row = gdrcd_query($result, 'fetch')){ ?>
<option value="<?php echo $row['id_razza']; ?>" <?php if(gdrcd_filter('get',$_POST['razza'])==$row['id_razza']){ echo 'SELECTED'; } ?>>
<?php echo gdrcd_filter('out',$row['nome_razza']); ?>
</option>
<?php } ?>
JavaScript
<script>
function razzaChanged()
{
alert("I am an alert box!");
}
</script>
When the selection of the dropdown is chosen, I have to add some information below the dropdown. The information I have to add is a bit complex and pretty formatted (I need to do some query to retrieve data and then add text and another dropdown after the info).
How can I achieve this? I can register via JavaScript that the selection changed but then I don't know how to go further.
You could use ajax methods. Get value from select using oninput/onchange, use that value as data in ajax request. If request is successful then show server's response in a container where ever you want.
HTML
<select name="razza" id="razza">
<option value="1">Some Option</option>
<option value="2">Another Option</option>
<!-- Use your loop here and remove these options -->
</select>
Javascript
$("#razza").on('input change',function(){
var value = $(this).val();
// Ajax Request
$.ajax({
type: 'post', // you can also use 'get'
url: '/link/to/your/server/file',
data: {
key: value // use key required by backend
},
success: function(response) {
$('#your-container-div-id').html(response);
}
});
});
Please note that I have used code without 'onchange' attribute, as this is better. Feel free to ask...
There are few ways to achieve this. One would be to use what jquery library offers.
Here are just some very rough steps of how one could do it:
In your razzaChanged() function establish which value is selected:
function razzaChanged()
{
var val = $('select[name="razza"] option:selected').val();
// step 2 here
}
Now use this value to fetch data from the server with the help of AJAX:
$.ajax({
type: "GET",
url: '/your-url-to-call',
data: 'your_value=' + val,
success: function(data) {
// step 3 here
}
});
Now having data from server (i.e. json format) build your new select dropdown, i.e.:
var newSelect = $('<select>').appendTo('body');
$(data).each(function() {
newSelect.append($("<option>").attr('value', this.some_property).text(this.some_text));
});
It's definitely not a ready-to-use code as you would have to make sure you return properly formatted data on server side or change the code accordingly. Also
make sure jquery library is loaded and the code is wrapped with its ready function (easy to find example on internet).
Hope this helps.
You will need to do an AJAX POST or GET request to retrieve data from your database and you will need to use document.createElement("elementtype"); to create an element to add to your page.
With jQuery, your AJAX would look something like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",//can be GET or POST
url: "yoururl",
statusCode: {
404: function() {
alert( "page not found" );
},
data: {key: value},//you can have multiple keys and values
success: function(res){
//add elements to the page
$('#yourelememntid').html(res.someattribute);
}
}).done(function() {
//AJAX request finished
});
</script>

Ajax Search as user types

I have a search feature that I am trying to implement. I would like the user to be able to type their "Search" and ajax fires as the user types to assist with finding their "Search".
I would like the user to be able to type their "Search" and ajax fires as the user types to assist with finding their "Search".
This is what I have; This is working but requires the user to hit search.
jQuery(document).ready(function($) {
// Let us trigger the search if the user clicks on the search button.
$('.btnSearch').click(function(){
makeAjaxRequest();
});
// Let us trigger the search if the user submit the form by an enter.
$('form').submit(function(e){
e.preventDefault();
makeAjaxRequest();
return false;
});
function makeAjaxRequest() {
$.ajax({
url: 'searchAction.php',
data: {name: $('input#name').val()},
type: 'get',
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
});
You need to bind your function to the keyup-event of the input field.
Adding the following line of code inside the $(document).ready()-function
$( "#name" ).keyup(makeAjaxRequest);
could do the trick for you.
To only perform the AJAX request on a minimum length of three chars in the input field, you can change your makeAjaxRequest() function like so:
function makeAjaxRequest() {
if($('input#name').val().length > 2) {
$.ajax({
url: 'searchAction.php',
data: {name: $('input#name').val()},
type: 'get',
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
}
You probably don't want to do your search on keyup as that would require 5 ajax calls to be made for the user to search for the word "Hello."
Consider the Google search bar: It will automatically show search results when it thinks it knows what you want, but not on every keystroke.
I wrote a little event plugin for jQuery that does this. It's only 20 lines of code fully formatted. Copy it and change it to your liking or use it as is.. Here's an example:
<script src='//raw.githubusercontent.com/Pamblam/textChange/master/textChange.js'>
<script>
jQuery(document).ready(function($) {
$('input#name').textChange(makeAjaxRequest);
function makeAjaxRequest() {
$.ajax({
url: 'searchAction.php',
data: {name: $('input#name').val()},
type: 'get',
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
});
</script>
$("input").keyup(function(){
$("#keyup").text("keyup: "+$(this).val());
});
$("input").textChange(function(){
$("#textchange").text("textchange: "+$(this).val());
});
b{display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='//raw.githubusercontent.com/Pamblam/textChange/master/textChange.js'></script>
<b>Type a few words:</b>
<input autofocus />
<div id='keyup'>keyup: </div>
<div id='textchange'>textchange: </div>
Thats it might be posible with Jquery Ui autocomplete.
https://jqueryui.com/autocomplete/

cascaded dropdown prepopulate knockout MVC

I am on the Update details screen and I have a Country and a state dropdown .I want to pre populate State dropdown on the basis of the selected Country.
On the initial page load I do have the selected Country,Country Collection and Selected State all I need is to fetch the State Collection using AJAX.
Country List: <select id="CountryDropdownList" data-bind="options: viewModel.CountryCollection,optionsText:'CountryName',optionsValue:'CountryName',value:viewModel.SelectedCountry"></select>
State List: <select id="StateDropdownList" data-bind="options: viewModel.StateCollection,optionsText:'StateName',optionsValue:'StateName',value:viewModel.SelectedState"></select>
<script>
var viewModel = ko.mapping.fromJS(#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
console.log(viewModel.SelectedState()); //State3 the initial value
viewModel.SelectedCountry.subscribe(function (newSelectedCountry) {
alert(newSelectedCountry);
console.log(viewModel.SelectedState()); //undefined why?
$.ajax({
url: 'Home/GetStateList?Country=' + newSelectedCountry,
success: function (data) {
viewModel.StateCollection(ko.mapping.fromJS(data)());
console.log(viewModel.SelectedState()); //state0 why?
}
})
});
ko.applyBindings(viewModel);
$(function () {
viewModel.SelectedCountry.valueHasMutated();
})
</script>
But when I try to fetch the state list through AJAX request the Selected State value gets reset and the first value in the list becomes the default selected value. I am confused, why does KO update my selected State value when I am not changing it at all?
But if I set the Selected State again in AJAX Success callback it works fine
viewModel.SelectedCountry.subscribe(function (newSelectedCountry) {
alert(newSelectedCountry);
$.ajax({
url: 'Home/GetStateList?Country=' + newSelectedCountry,
success: function (data) {
viewModel.StateCollection(ko.mapping.fromJS(data.StateCollection)());
viewModel.SelectedState(data.SelectedState);
}
})
});
I am looking for a reason for this strange behavior.
I have tried simplifying the code as directed by you and now I think it might help you to point out the issue.
<script>
var viewModel = ko.mapping.fromJS(#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
console.log(viewModel.SelectedState()); // o/p state3
$.ajax({
url: 'Home/GetStateList?Country=' + viewModel.SelectedCountry(),
success: function (data) {
viewModel.StateCollection(ko.mapping.fromJS(data)());
console.log(viewModel.SelectedState()); // o/p state0
}
})
ko.applyBindings(viewModel);
</script>

pass ID when button is clicked to Action link

I want to assign a certain value for an ID when button/url is clicked.
So that I can display a dynamic list based on this id by passing the id to action link.
Sample of my code (button)
<a class="" href="/LaborerSearchByName/Index">
<img src="/Content/images/b7.png" id="b7"
onclick="bb7();"
onmouseover="bigImg(this)"
onmouseout="normalImg(this)">
</a>
The call for action link
#Html.Action("Menu", "MenuItem", new { id = "MenuId"})
"MenuId" must by a dynamic value based on which button is clicked.
Here goes my solution, use Html.ActionLink() -
#Html.ActionLink("Menu Text", "Menu" ,"MenuItem", new { id = "MenuId" }, new { #id = "MenuId" })
Then say you have image control like this -
<img src="/Content/images/b7.png" id="b7"/>
Then you have simple JQuery script to replace query string in this way -
<script>
$(document).ready(function () {
$("#b7").click(function () {
$("#MenuId").attr("href","/MenuItem/Menu/" + this.id);
});
});
</script>
In the above script, when you click on the image element, its id (b7) will be used to formulate the anchor tag url. so now when image was clicked, a new url will be assigned to anchor tag on the client side using JQuery. So the final url should be something like this -
/MenuItem/Menu/b7
UPDATE: As per your comment, I am presenting a simple demonstration on how to use JQUERY AJAX to make a GET request with a parameter and get results back on to the UI.
Lets say you have a controller which returns Json -
public JsonResult GetJson(string MenuId)
{
List<string> urls = new List<string>();
urls.Add("https://google.com");
urls.Add("https://bing.com");
return Json(urls, JsonRequestBehavior.AllowGet);
}
Then you can call this controller action in a button click using JQuery Ajax in the following way. In your implementation you should get that dynamic value instead of input text control. For demo purpose I used Input text to get a value and pass it to controller action.
<input type="text" id="Menu" />
Click me
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#ClickMe").click(function () {
var o = new Object();
o.MenuId = $("#Menu").val();
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) {ou parse data
// This is how we parse returned json string
$.each(data, function (i, item) {
alert(data[i]);
});
},
failure: function (errMsg) { alert(errMsg); }
});
});
});
</script>
When you run the code, you should see following view -
When you enter the value and click on anchor tag -
And as a result, you will get all the results parsed -
You can pass this using your function onclick="bb7(this);"
then in JavaScript part use setAttribute in you function: bb2(this){this.setAttribute("id","someID");}

showing velue from php file in div in html file

Basicly, In my html I have a form that consists of 2 selects and 2 text inputs. I would like to send values from that form into a php file called solve.php. This file will produce a variable called $cenaCelkom. I want to show the value of that variable in one of my divs.
I have to send tvalues from my form without redirecting to the solve.php. I have this for sending values to my php, but I cant find out if it works.
<script type="text/javascript">
$(document).ready( function () {
$('form').submit( function () {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "solve.php",
data: formdata
});
return false;
});
});
If this is ok, I would like to know how to get the value from my php after executing it. BTW: I am not an experienced js or jquery programmer, so please go easy on me :)
Thank you.
<div id="myresult"><div>
<script type="text/javascript">
$(document).ready( function () {
$('form').submit( function (e) {
e.preventDefault();
var formdata = $(this).serialize();
$.post('solve.php', $(this).serialize(), function(result){
$('#myresult').html(result);
});
});
});
You can grab the values of the inputs by using $_POST['inputnamehere'] from your solve.php page.
You can use $.load() method in jQuery
<script type="text/javascript">
$(document).ready( function () {
$('form').submit( function () {
$( "#yourDivId" ).load(
'solve.php',
$('form').serialize(),
complete(responseText, textStatus, XMLHttpRequest){
//do whatever after ajax operation
}))
return false;
});
});
</script>
On solve.php simply get the values via $_GET and use print() for output:
<?php
print( $_GET['val1'] + $_GET['val2']) // Show a summation of two numbers
?>

Categories

Resources