Does anyone know how I could get the select options in the following to be populated from a SQL DB?:
var cell2 = row.insertCell(1);
var sel = document.createElement('select');
sel.name = 'selRow' + rowCount;
sel.options[0] = new Option('text zero', 'value0');
sel.options[1] = new Option('text one', 'value1');
cell2.appendChild(sel);
Thanks,
B.
Either take the long and inelegant route of outputting each of the sel.options[x] lines when the page is generated, or if you want to do it based on other information on the form, using AJAX is the way.
Javascript can't directly connect to a database, you're going to need some server-side (PHP, ASP, Coldfusion, etc.) code to do that.
UPDATE:
1. In PHP create a page that reads the database & outputs XML or JSON or even the HTML code itself
2. In Javascript make an AJAX call to that PHP page
3. Use Javascript parse the XML/JSON/HTML response to update the page.
Using a library like JQuery will make this much easier to code. Let's assume your generating the HTML code in PHP & using JQuery, you could make & parse the AJAX call like this:
$.get("YourPHPPage.php", function(data){
$('.DynamicSelect').html(data);
});
That will make an ajax call to the PHP page, and insert the result into your select box.
Related
I'm trying to fetch data from a MySQL database relevant to the selected date_time.
I have extracted the date_time from the database and displayed it on a page and now the thing I want to do is that "When I select a date the data on that date should be display without refreshing the page".
you have to create an other .php page containing calling your date_time and call it in ajax after ward.
your ajax request should looks like :
$("#Button_get_date").onclick ( function () {
$("#div_to_display").load("/date.php", {"date= (#optiondate#.val));
})
the other page php should contain
$data = $ddb ->query("select * from tableinfodate where date = ".$_POST["date"].");
after i think you know what to do but remember to make your display in your in the loaded page.
have a look at the function load :http://www.w3schools.com/jquery/jquery_ajax_load.asp and also at GET and POST method in php. More over i think it is better to try hard on js before trying to do loaded function as this one.
I hope it helps a bit.
Okay, so I have this function in PHP that gets an attribute and returns an array. Something like this:
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
Everytime the parent select changes, the function getProvinces() should be executed with the new ID and the arrayWithProvince should be included as options in the child select.
I'm using jquery to handle the events, as I found somewhere. I need to do something like this.
$("#selectCountry").change(function() {
var parent = $(this).val(); //get option value from parent
var prov = <?php echo json_encode($pagina->getProvinces( <PARENT> )); ?>;
list(prov);
My problem is that I don't know how to tell the getProvinces($countryID) php function which is the new value of the parent.
Thanks in advance.
You should use javascript for that in order to refresh part of your page with dynamic content.Below is an example using jquery's ajax function.When the select with id #parent_select changes you call your php script and you append the returned data (the html of the child select in the example) in a div you want.
Javascript part would be something like this:
$("#parent_select").change(function() {
$.ajax({
url: "your_script.php?cid="+$(this).val(),
success: function(html){
$("#child_select_container").append(html);
}
});
});
And your_script.php code would look something like :
<?php
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
$countryID=(int)$_GET['cid'];
$provinces=getProvinces($countryID);
echo '<select id="child_select">';
foreach($provinces as $key=>$province){
echo '<option id="'.$key.'">'.$province.'</option>';
}
echo '</select>;
I havent tested the example.It is just a basic how to example.You should be able to work your way from here.But if you have any problems let me know.
As far as I know, you cannot execute the function without reloading entire page (I mean php should recompile it and pass it to the client).
You should use only JavaScript for that purpose. Store you arraylist in JS code, and validate it once upon form submission (just to be sure).
You need to make an Ajax request to the server.
Look at it this way: Your Javascript/jQuery is running on the client side (web browser) and you PHP is running on your web server.
So to communicate between the browser(jQuery) and the server(PHP) you need to make a Ajax request.
jQuery has a ajax function you could use, your best bet is to do some research on the subject as Ajax is something you will use all the time and understanding how it works is crucial.
I would like to add in a with JS from a JSP variable that contains the result of a SQL query.
This is my two inputs :
<tr>
<td><label>Code postal* :</label></td>
<td><input type="number" name="cp" placeholder="CP du lieu de résidence" required /></td>
<td><label>Ville* :</label></td>
<td><select name="ville" required disabled/></select></td>
</tr>
And ths is my JS and JSTL query:
<sql:query dataSource="jdbc/Referentiel" var="communeCp" >
SELECT code_postal, nom_commune_min, insee_commune FROM commune
</sql:query>
<script>
$('input[name=cp]').keyup(function(){
if ($(this).val().length == 5)
{
$('select[name=ville]').prop('disabled', false);
var communeListe = "${communeCp}";
for (var i in communeListe)
{
var currentCp = communeListe[i][code_postal];
var currentVille = communeListe[i][nom_commune_min];
if($('input[name=cp]').val() == currentCp)
{
$('select[name=ville]').append('<option value="'+ currentVille +'">'+ currentVille +'</option>');
}
}
}
else
{
$('select[name=ville]').prop('disabled', true);
}
});
</script>
My navigator say "code_postal is not defined".
I am forced to use ajax to do this ? I really don't know ajax. :/
"code_postal is not defined" happens because of this line of javascript:
var currentCp = communeListe[i][code_postal];
Javascript thinks code_postal is the name of a variable, but there's no "var codePostal = ..." anywhere in your javascript.
Here's what's going on with your JSP page:
First, your JSP is rendered. JSP invokes the SQL query and stores the result in the communeCp variable (an object of type javax.servlet.jsp.jstl.sql.Result).
JSP then replaces this line:
var communeListe = "${communeCp}";
with the result of evaluating "communeCp.toString()". I don't know what that is, but it might be something as simple as the default Object.toString implementation, so this is the actual javascript that would be rendered to the page:
var communeListe = "javax.servlet.jsp.jstl.sql.Result#123456".
Now that the JSP has been rendered, the browser executes the javascript. It fails to even evaluate because you have the undefined code_postal reference, but if for some reason that wasn't a problem, it would fail because you are trying to do a for each loop over the communeListe, but javascript sees that communeListe is just a simple string, so it doesn't make sense to do a for loop over that.
Now, with that understood, I'll try to explain how you could achieve the behavior you want without AJAX.
From your code, it looks like you want the following behavior: A user needs to enter a postal code and select a ville in that postal code. After they've entered 5 characters of their postal code, enable the "ville" dropdown and populate it with the possible villa choices for that postal code.
You have the basic idea for one way to achieve this: Do a query in JSP that gets all postal codes and all villes, then, when the postal code is entered, look through this data somehow in javascript and populate the ville dropdown with the villes that are in that postal code.
The problem is in making the data from the SQL query available to the javascript. Here's how you might do that without AJAX. The basic idea is to initialize a javascript array of objects using a literal which is generated by rendering your JSP:
<sql:query dataSource="jdbc/Referentiel" var="communeCp" >
SELECT code_postal, nom_commune_min, insee_commune FROM commune
</sql:query>
<script>
var communeListe= [];
<c:forEach var="row" items="${communeCp.rows}">
communeListe.push({
code_postal: '${row.code_postal}',
nom_commune_min: '${row.nom_commune_min}',
insee_commune: '${row.insee_commune}'
});
</c:forEach>
$('input[name=cp]').keyup(function(){
if ($(this).val().length == 5)
{
$('select[name=ville]').prop('disabled', false);
$.each(communeListe, function(index, currentRow) {
var currentCp = currentRow.code_postal;
var currentVille = currentRow.nom_commune_min;
if($('input[name=cp]').val() == currentCp)
{
$('select[name=ville]').append('<option value="'+ currentVille +'">'+ currentVille +'</option>');
}
});
}
else
{
$('select[name=ville]').prop('disabled', true);
}
});
</script>
Be warned! This has the potential to make the page very slow to load if you have a lot of rows in the commune table, because you are sending the text of every single row to the user's browser.
For you use case, it would almost certainly be a better overall design to use AJAX. The way this would improve load speeds is that it would only query for the villes that it needs and it would only need to send back a small subset of all possible villes to the user's browser. I can provide a bit of guidance on that:
Basically, you will first need to develop a server-side webservice. You can probably just make this using a Java servlet since you are already using JSP. This servlet will need to accept a postal code as a request parameter and will do a query to the commune database on that postal code (so it should only get rows where postal_code == the postal code request parameter value). It will then return JSON containing an array of objects representing those rows from the commune database, so something like this:
//assume this is the request coming to your webservice
/get_villes?postalCode=12345
//This would be the JSON response returned by your webservice
[
{
'nom_commune_min': 'ville name 1',
'insee_commune': 'insee_commune 1'
},
{
'nom_commune_min': 'ville name 2',
'insee_commune': 'insee_commune 3'
},
... and so on depending on how many villes have that postal code
]
To implement this webservice you could make a simple java object called something like Commune and give it nom_commune_min and insee_commune as fields. Then you could use a simple JSON serialization library like Jackson to serialize that object to a string and return that from your servlet as the body of your HTTP response.
On the frontend side, you'll need to change your javascript so that, when the postal code is entered, it uses $.ajax({ ... }) and invokes that webservice, you made passing it the value of the postal code to lookup.
The call to $.ajax might look something like this (I would probably use $.get just because it's a simpler version of $.ajax):
$.get({
url: "/get_villes?postalCode=" + postalCode,
success: function(communeCp){
$.forEach(communeCp,function(index,currentRow){
//put code here to populate the dropdown list using
//currentRow.postal_code, just like the previous code I provided
});
},
});
Another thing to consider is that, since this is asynchronous, when the browser performs this query, the dropdown is going to be blank for a small time while that query runs (but the user will still be free to interact with the page and might be confused by the blank enabled ville dropdown). So, you need to communicate to the user that you are waiting for results from the webservice when that javascript ajax query runs. So, you could do something like show a "Loading..." text somewhere when they enter the 5 digits of their postal code, and then hide that text in the success function of that $.get (after the dropdown is populated).
Other than that, I would suggest you take some time to wrap your mind around how AJAX and webservices work and look at some tutorials and examples. Webservices, ajax, and everything related to building dynamic websites are a vital part of modern web development.
I am calling another application context from window.showModalDialog but confused with following work. Same code to pass parameter within showModalDialg.
var myArguments = new Object();
myArguments.param1 = "Hello World :)";
window.showModalDialog("java2sTarget.html", myArguments, '');
and i can read these myArguments(parameters) in generated HTML using following code:
<script>
document.write(window.dialogArguments.param1);//Hello World :)
</script>
I can't use query string & i am sending myArguments(parameter) because i want to hide parameter from Application user.
Now i am calling servlet from showModalDialog(..)
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
But as per my knowledge
Servlet --> Servlet container --> HTML+JS+CSS
so JS will be available at last phase, but i want to use in first phase(Servlet).
Now, i need to make some Decision in servelt code based on myArguments(parameter).
is there any way to read these myArguments(parameters) in servlet code?
Pass it as a request parameter in the query string.
var queryString = "param1=" + encodeURIComponent("Hello World :)");
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test?' + queryString, myArguments, '');"
No, there's no other alternative. The request URL is not visible in the modal dialog anyway.
As main objective is to hide query string from User to avoid misuse of those parameters.
I tried following work around.
Developers send hidden parameters to get relative information form source(e.g.:DataBase). And we also know that we can send hidden information in Window.showModalDialog using dialogArguments
Work Around:
(i) I got relative information from server one-step before calling Window.showModalDialog using jQuery.getJSON()
(ii) i used google-gson API at servlet side to convert JavaBeans into Json strings.Solution 1 Solution 2
(iii) Convert JSON into javascript object using jQuery.parseJSON
var args = jQuery.parseJSON(json);
window.showModalDialog("pages/"+args.pageName, args, '');
i used args.pageName to make things dynamic
Please suggest improvements in this work-around. Thanks
Hello people
I'm trying to figured this out, but I still can't do it.
I have a rails 3 app, I'm working with invoices and payments. In the form for payments I have a collection_select where I display all the invoices number (extracted from a postgres database), and what I'm trying to do is when i select an invoice autopopulate others text_fields (provider, address, etc.) without reloading the page, in the same form.
I know I should use ajax, js, jquery, but I'm a beginner in these languages, so i don't know how or where to start
hope you can help me... thanks
What you are going to want to do is route an ajax call to a controller, which will respond with json containing the information. you will then use jquery to populate the different fields.
In your routes:
get "invoice/:id/get_json", :controller=>"invoice", :action=>"get_json"
In your invoice_controller:
def get_json
invoice = Invoice.find(params[:invoice_id])
render :text => invoice.to_json
end
In your invoice model (if the default to_json method is not sufficent):
def to_json
json = "{"
json += "id:'#{self.id}'"
json += ",date_created:'#{self.date}'"
... //add other data you want to have here later
json += "}"
end
In your javascript file,
$("#invoice_selecter").change(function(){ //calls this function when the selected value changes
$.get("/invoice/"+$(this).val()+"/get_json",function(data, status, xhr){ //does ajax call to the invoice route we set up above
data = eval(data); //turn the response text into a javascript object
$("#field_1").val(data.date_created); //sets the value of the fields to the data returned
...
});
});
You are probably going to run into a few issues, i would highly recommend downloading and installing fire bug if you are not on google chrome.. and if you are, make sure you are using the development tools. I believe you can open them up by right clicking and hitting inspect element. Through this, you should be able to monitor the ajax request, and whether or not it succeeded and things.