Executing Javascript to populate a drop down before HTML page loads - javascript

I have 2 Drop Downs in a HTML form. The first dropdown needs to be populated with a list of usernames present in the DATABASE.
Secondly, Depending upon the selection made in the first drop down, I then need to run another JS script to make another call to the DB to retrieve the list of associated addresses to that username.
Can you please let me know whats the best way to achieve this objective?
1) How can I run a JSscript before the HTML form loads to return that list?
2) Should I get both the usernames and associated addresses in one Db call or just get the usernames first and then use onChange event on the first dropdown to execute the second call?
Any code would be most appreciated.
Thanks

well if you have all the info in same table then why dont you get all data in one go by querying as to the DB and then sort and put up data in the elements the way you want.
the other way will need to query DB 2 times.

here you can create your HTML to server call OR you can make HTML locally.
i have created options for selectbox at server and innerhtml to locally.
<select id="selectbox1" onchange="getData(this)"></select>
<select id="selectbox1"></select>
$(document).ready(function() {
$.ajax({
url: 'http://localhost/getUsername.php',
success: function(data) {
$('#selectbox1').html(data);
alert('Load was performed.');
}
});
});
function getData(selData) {
$.ajax({
url: 'http://localhost/getSecoundCall.php?id='+selData,
success: function(data) {
$('#selectbox2').html(data);
alert('Load was performed.');
}
});
}

Related

Populate Select element with Jquery and AJAX and without async:false attribute

I am trying to populate a select element from database, I need to pass some variable from my Jquery script first (id of a button). For this purpose I used AJAX call and passed variables to PHP file, made SQL query, fetched data... Everything turned out to be fine... but when I created html code and then passed from PHP to AJAX. The Jquery variable html was not taking any data from AJAX call... Then I read about using async:false attribute within AJAX call.. But I know it is not a good solution... I am new to web development.. I want you to suggest me what should I do...
Example of my code is as below
'''
<span id="span_product_details"></span>
<script type="text/javascript">
$(document).ready(function(){
var v1=1; //actually id of a button will be saved in this variable which is necessary to make database query
var v2=2;
var v3=3;
var html='';
html += '<select name="abc" id="abc" class="form-control selectpicker" data-live-search="true" required>';
$.ajax({
url:"practice.php",
method:"POST",
data:{v1:v1,v2:v3,v3:v3},
dataType:"html",
success:function(data)
{
html += data;
}
});
html += '</select>';
$('#span_product_details').append(html);
$('.selectpicker').selectpicker();
});
</script>
<?php
//example code of practice.php file (a seperate file)
//$query = (based on $_POST['v1'], $_POST['v2'] and $_POST['v3'])
$str='<option value="1">Hello</option>'; //data obtained from database
$str.='<option value="2">Hi</option>'; //data obtained from database
echo $str;
?>
'''
For more detailed understanding I am explaining the problem with more details..
I have a table each row of that table has 4 columns,
ProcessID, ProcessDate, Edit_btn, Delete_btn
during each process multiple parts were processed lets say part No. A1, A2, A3
ID of Edit button is also same as ProcessID.
Now When Edit button is pressed, a modal will open, an AJAX call is performed and that modal shows
rows with data as follows,
(select element with Part number) (part status accepted, rejected etc) (remarks)
Now while Editing user must be able to add more parts to the same process... For this purpose there is an (Add button)
With first row of modal,
Now When Add button is pressed, a new row will be added to the modal,
that row must have a select element which should be populated with a list of already processed parts
and parts which were not processed...
For this purpose I had to make an AJAX call, which will pass the EDIT_BTN id (to fetch already processed parts under this.processID)
to php file,
And get the options for select element. During this operation I am having the above stated issues...
One way is to use async:false which will work.
the other way is to append basic html first, the load data
or you can just write your select html in modal and on modal show event, load data,
p.s. data v1,v2,v3 you use it your way, i just outlined the solution,
$(document).ready(function(){
var v1=1; //actually id of a button will be saved in this variable which is necessary to make database query
var v2=2;
var v3=3;
var html='';
html += '<select name="abc" id="abc" class="form-control selectpicker" data-live-search="true" required>';
html += '</select>';
$('#span_product_details').append(html);
load_dropdown(v1,v2,v3);
}
// use v1,v2,v3 however you have, either in function or global, param, or any other way
function load_dropdown(v1,v2,v3) {
$.ajax({
url:"practice.php",
method:"POST",
data:{v1:v1,v2:v3,v3:v3},
success:function(data)
{
console.log(data); // if in console it display html then fine,else check format
$('#abc').append(data); // or use .selectpicker as selector if its unique
$('.selectpicker').selectpicker();
}
});
}

how to display different div when i returned from servlet?

i have a jsp file with different div. First i display a div with login page after logged in it goes to servlet page and return back to same jsp page. My question how to display the different div after returning from the servlet?
Code snippets would have helped.
From what i get, you are trying to display the same JSP to the user, before & after logging him in, but providing a different view/div.
You can leverage the fact that once a user is logged-in, a flag/user object is usually added to the session/response(or you can add the same). You can then use this to block/display your div respectively.
First make the div display none
Then send data using ajax to ur sevlet
$('#button id').click(function() {
$.ajax({
type: 'POST',
url: '..yourservlet',
data:your data,
success: function(data)
{
$('#div id you want to display').style.visibility = visible:// this will display ur div
}
});
});

Form doesn't serialize after Ajax insertion

Tearing my hair out over this. I have a 40 rows of simple forms that are being generated dynamically from a mysql database. Each form has a unique ID based on the database ID. After clicking submit the results get updated in the database and inserted into the div (#result).
Works the first time perfectly. However after the first time the script won't serialize the updated form data. The ID is fine (checked via alert) but the formData is empty (also checked via alert).
Thinking I need to re-target the form somehow? Any help would be greatly appreciated. Thanks.
$('#result').on('click', '.submitform', function () {
var id = $(this).attr('id');
var formData = $('#'+id+'-form').serialize();
$.ajax({
type: "POST",
url: "ajax-process-form.php",
data: formData,
cache: false,
success: function(server_response){
$("#result").html(server_response).show();
}
});
return false;
});
Just reasoning... I might be wrong...
This code
$('#result').on('click', '.submitform'
binds to the click event on result and filters .submitform, then executes with this being the .submitform
when the success comes from the server, you are rewriting #result
$("#result").html(server_response)
if server_response does not contain a .submitform then next calls to the first onclick event will not execute because .submitform does not exist anymore inside #result
If this is the error, then to solve, use another div to show the result instead of #result or bind click to another separated, not contained within div
Arrgh - it was the structure after all. Although it worked the first time the table structure prevented it from working a second time. I have no idea why ... but there you go. Thanks for the help!

Populate multiple dropdownlists from sql and previous selected value

I have code in php to query database and populate records in a dropdown list which a user will pick. I also have javascript which populates the second dropdown list based on the selection of the first box.
How do I tie these two together so user selects value "x" from dropdown list, and the php will query the database "WHERE.... = SselectedValue"
Are there any examples online? I can't seem to find any.
Write an ajax/phpquery call to second dropdown on change method of first dropdown. Eg-
$("#firstDdwn").on('change',function(){
var val=$(this).val();
//php will query the database "WHERE.... = val"
//on success of data received from query, populate second dropdown
})
Ajax code is supposed to look something like this-
$.ajax(
{
url:"your_controller_URL",
data: val
success:function(result){
//populate 2nd dropdown with result
},
error:function(){
alert("No data received");
}
});
Link for brief info on jquery ajax --- http://www.w3schools.com/jquery/ajax_ajax.asp

Populating JScript Array for reuse on SELECTs

Forgive me if this is already 'somewhere' on StackOverflow, but I don't 100% know exactly what it would come under...
I'm trying to retrieve information from a WebService, store this in an array, and then for each <select> within my ASP.Net Datalist, populate it with the array AND have binding attached to an OnChange event.
In other words, I have an array which contains "Yes, No, Maybe"
I've an ASP.Net Datalist with ten items, therefore I'd have 10 <Select>s each one having "Yes, No, Maybe" as a selectable item.
When the user changes one of those <Select>s, an event is fired for me to write back to the database.
I know I can use the [ID=^ but don't know how to:
a) Get the page to populate the <Select> as it's created with the array
b) Assign a Change function per <Select> so I can write back (the writing back I can do easy, it's just binding the event).
Any thoughts on this?
I have built a simple example that demonstrates, I think, what you are attempting to accomplish. I don't have an ASP.Net server for building examples, so I have instead used Yahoo's YQL to simulate the remote datasource you would be getting from your server.
Example page => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource.html
Example steps:
query datasource to get array of select questions
build HTML of selects
append HTML to page
attach change event listener to selects
on select value change submit value
Example jQuery:
// get list of questions
$.ajax({
url: url,
dataType: "jsonp",
success: function(data) {
// build string of HTML of selects to append to page
var selectHtml = "";
$(data.query.results.p).each(function(index, element) {
selectHtml += '<select class="auto" name="question'+index+'"><option value="Yes">Yes</option><option value="No">No</option><option value="Maybe">Maybe</option></select> '+element+'<br/>';
});
// append HTML to page
$(document.body).append(selectHtml);
// bind change event to submit data
$("select.auto").change(function() {
var name = $(this).attr("name");
var val = $(this).val();
// replace the following with real submit code
$(document.body).append("<p>Submitting "+name+" with value of "+val+"</p>");
});
}
});
Example datasource => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource-datasource.html
Example loaded:
Example select value changed:

Categories

Resources