dropdown menu populated from a database in a client side page - javascript

I want to populate the data from a database using client side programming either HTML or javascript. I looked online and got lot of sites giving examples on server side i.e. JSP,ASP or PHP for creating the dropdown menu. I know the simple syntax for creating the HTML dropdown menu and in other languages. But I don't know how to populate that HTML dropdown menu values from the database. Any technique which either gets the data from the JSP page which fetches the data from the database and on selecting a single item triggers a query to JSP page which again fetches data from the database can work for me.
Problem: I want to access the database fields from a html page. The dropdown list of html page should be populate from the database and on selecting a specific value it should get data specific to that option.
Any ideas or links to the sources I should look at.

Just so you can get a general idea of the mechanism: How about an Ajax-call triggered by an event listener like this (could also use click event or whatever):
After the html-document is loaded, add an event listener to the watched element (here onchange) and call a function when the event is triggered:
$(document).ready(function() {
$('#watchedElement').change(callAjaxFunction());
});
Function for Ajax-call:
In the data variable you can send information to the server to decide there which options to send back. Easiest way (though quick and dirty) would be to return (like "echo" in php) the option values in plain text/html and replace the old option-elements with this. I prefer the JSON-ways described in the link from your question's comment, since you have a lot more control on the data but for a first impression you could try if the mechanism works for you in general:
function callAjaxFunction() {
$.ajax({
type: "POST",
url: url,
data: { "selectedValue": $('#watchedElement').val() }
success: function(data) {
$("#idOfSelectElement").html(data);
}
dataType: "HTML"
});
}
Just for testing purposes without any evaluation of the value sent to the server you could send back two dummy options like this (example is php file for simplicity and you even could use an html-file that only contains the text itself):
<?php
echo "<option value='test1'>Test1</option>" .
"<option value="test2">Test2</option>";
?>
Still it's probably better to go the JSON way and add element by element, which makes dbugging and stuff way easier later on.

Related

How to display ajax list response on html using jquery?

So I currently have a search box that the user can search for managers. When the manager is searched and selected, they can choose to show direct report employees via a button that triggers a Javascript function that sends an Ajax post to the backend to query the database. Upon receiving a success response, I would like to display a table with general info of the employee (such as First, Last name, Position, etc.) We have previously used Jquery to pull the data upon load, but I was wondering if there was a way to pull and display this data from the Ajax response and display it on page without refreshing? Another roadblock seems to be that the response is in a List fashion, in such that it returns none to many employees; a variable response. If it is more effective, we are also using a Thymeleaf template, but I doesn't appear if I can make the Thymeleaf selectors open to a live update such as this
In order to set the Ajax Response in your HTML page, Do something like this :-
1.) Use your HTML element's id and then append the response fro your ajax Success function.
Suppose there's a text box in which you want to set the response.
<input type="text" id="inputText" >
2.) Now, in your ajax success Response , get the id of this element and then append the response like this :- -
$.ajax({
url: //your url,
success(data){
$('#inputText').val(""); //clear the text box on each call so that it won't append the data on every request
$('#inputText').val(data); //get the text-box id and append the response
},
error(data){
console.log(JSON.stringify(data));
}
});
See my comment first. The post response if possible should be a JSON list of objects I'm assuming employees. Then after success use jquery to manipulate(add or remove) the table rows and if that sounds complex. House the whole table in a div with id, when ajax returns recreate the table by replacing all said divs HTML with the new table. No need to refresh. However, since a request can take long or fail you need some animation (perhaps blockUI) to show activity and even handle failures

Insert PHP functions into Javascript

I got really confused when trying to get PHP functions into javascript.
In my scenario, I just extract some lines from XML file in PHP and convert it into a table, and the presentation of the whole table is in the function getNews(). Into the function are echo sentences like
function getNews(){
$xmlResponse = new SimpleXMLElement('xml.addr',0,TRUE);
foreach($xmlResponse -> children()as $contents){
echo "<table id ='news'>";
echo "<a href='".$links."'>".$contents -> item[$num] -> title."</a>";
HTML tags are involved to build a news table.
Then I was asked to implement a button, when clicking on the button, the button image changes and the table should be shown below. Obviously the onclick function should be written using javascript, when click on it, I need to call the anotherButton() function and show the news table
echo "<script>function anotherButton(){
document.getElementById('news').innerHTML='<div class='newStyle'
onclick='anotherButton1()'>click to hide stock news
<img src='http://image-addr'></div>';
}</script>";
All these things were done in PHP and I need to insert function getNews()
somewhere in the above echo, so how I can put the function in it ?
Thanks in advance.
What you need is the following:
Javascript sends the data to server using AJAX in the client's browser.
PHP decodes the request, processes it then responds with the information requested.
Javascript receives the response and displays it accordingly.
Using Asynchronous Javascript And XML (or AJAX for short); you can essentially fetch data from the server dynamically without the client performing a browser refresh.
Here is a video by Codecourse which will get you started in the right direction.

Updating multiple areas with ajax

I've started learning ajax and javascript recently, and still getting a handle on it. But I have a simple goal I'm trying to achieve, and I'm half way there.
For example. I am working on the ability to manage bookmarks saved by one user to be used by other members. I have the code built where I can add, edit, and delete the item live on the page. But how I learned how to do the edit part is a 'click the field area' to start the edit, then 'click out of the field area', to finish the update. I'd really like to change that to a way to click a button to submit the edit.
Also on the page it has a "View Bookmark" button right next to the delete option, but I am not sure how to update that link when I update the text area of it without refreshing the page.
So essentially I want to learn a more efficient way to do live updates via ajax, and then when the update is completed, update all the instances of that same item on the page (which is only two areas).
Any help would be greatly appreciated.
I can post my original code but I think I might be better to learn from someone who knows better. lol
This is a generic question so I will answer generic answer.
If you have, for example, 2 divs
<div id="area1"></div>
<div id="area2"></div>
And you want to call the server and get 2 data's for each div, So it will looks like this: (I'm using jQuery for the example..
$.ajax({
url:'server_url',
method: 'post',
success: function(data) {
$('#area1').html(data.objForArea1);
$('#area2').html(data.objForArea2);
}
});
The JSON that return from the server (for example)
{
objForArea1: '<div class="list-item">item 1</div>...'
objForArea2: '<div class="list-item">item 1</div>...'
}
So you read the response from the object that return from the ajax call, then you put the data wherever you want.

How to make link test if desired page exists, then go to it if it does?

Alright so I am not the most astute javascript/jQuery user, but here it goes.
I want to make a series of html pages that will each link to the next/prev page and will loop once they reach the end of those pages ('page1' and 'lastpage.html'). I know I could do that with just html, but I don't want to have to continually go and revise each page, as I plan on adding pages to that bank/series of pages, so the amount of pages cycling will increase.
The one solution I have thought up of is to test if the 'next' link will exist like this
$(document).ready(function(e) {
$('#next').click(function(){
.preventDefault();
.ajax({
type: 'HEAD',
url: 'art_2.html',
success: function() {
window.location.href = "art_2.html";
},
error: function() {
window.location.href = "art_1.html";
}
});
});
});
So basically how do I make this work, or am I trying to use a tool where I could be using a power-tool?
also added in a prevent default just remembered...
and guess what? Cannot use PHP :/ so yeah...
ALSO I'm kinda lack necessary intelligence to do a good deal of the things with the coding. Entirely self taught...
This is a broken "fix" at most. You should have a server-side script that updates the list regardless of which page you are viewing.
An example of decent implementation would be a mySQL database with a table that contains each page id (auto increment), page url, and optionally a page name. Then dynamically create the "next" and "previous" page based on the results returned form the sql queries.
Keep all pages you want in the cycle/loop in a folder in project
Write a class that reads directory structure
Manipulate file names as you want to link name and store these into a data structure
In UI, based on current page name, get the next one.
I hope this helps.
You could store the data structure in session to access via UI.

Need sample JavaScript to query MySQL and display result upon combo box update

I have a combo box that will be loaded with a list of choices. When the user selects a choice, I need a JavaScript to simply run a query of MySql (obviously based on the user choice in the combo box) which will return a simple, discrete value that then needs to be displayed on the page next to the combo box.
The query is nothing more than SELECT foo FROM tblexample WHERE id = blah (where blah is the combo box value). The value will be a simple number. If the user chooses a new value, then it should just re-query and display the result.
I'm open to reading the whole table in upon page load into an array or something too. I work in PHP but I don't know Javascript; I was only hoping for a sample code bit; I can read and extrapolate most of the time.
I just didn't want to put a submit button in a form and force the user to do that each time they look at a new combo box choice. I wanted a more seamless, quick display for them.
JavaScript is a client-side language. It will not run MySQL queries (safely, at least). Use PHP to dynamically create the HTML and JavaScript for the combo box.
PHP has an entire section of their documentation reserved for MySQL.
I think you are actually looking for a reference in Ajax programming using PHP on the backend and javascript on the front end.
My recommendation would be to look at using one of the excellent Javascript development frameworks. Great candidates would be JQuery or Prototype. They both give you solid libraries to simplify programming in javascript.
Rather than working with sample code, you'll probably get a lot further by developing javascript expertise. Ajax is complicated, and you'll need to at least get basic skills together before you can start to integrate javascript and PHP.
Here's a good query to get started- I'd recommend beginning with JQuery if you have to pick one.
http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=ajax+php+jquery+tutorial
Once you get started on jQuery as Tim mentioned you could do this,
The select box,
<form name="formName" action="" method="">
<select name="selName">
<option value={uniqueId}>Option 1</option>
</select>
</form>
<p class="displayMsg">No message to display.... yet</p>
The javascript and jQuery in a script tag of the head tag,
$(document).ready(function() {
$('select[name=selName]').change(function() {
function processData(data, success) {
...do something with the query results echoed into var data...such as
$('p.displayMsg').txt(data); // which will update the text node of the p tag class displayMsg
} // end function processData
var formData = $('form[name=formName]').serialize(); // this will encode the variables from the form to pass into post headers. You can access in your ajax called script with $_POST['selName']
$.post('phpAjaxProcessScript.php',formData,processDataClose); // sends data to script and when it's done it calls function processData
}); // end select change event function call
}); // end document ready event function call

Categories

Resources