Currently I have my chained select menus working great.
However currently when the page loads the first dropdown menu is completely empty.
I would prefer to populate the menu initially with ALL the results from:
SELECT * FROM employees and then if the user chooses an option from 2nd dropdown, it would then initiate the AJAX and filter the results based on the selection.
Is this possible?
Here are my files:
dept_form.html (HTML Form) :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Employees by Department</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script src="ajax.js" type="text/javascript"></script>
<script src="dept.js" type="text/javascript"></script>
<style type="text/css" media="all">#import "style.css";</style>
</head>
<body>
<!-- dept_form_ajax.html -->
<p>Select a department and click 'GO' to see the employees in that department.</p>
<form action="" method="get" id="dept_form">
<select id="results"></select>
<p>
<select id="did" name="did">
<option value="1">Human Resources</option>
<option value="2">Accounting</option>
<option value="3">Marketing</option>
<option value="4">Redundancy Department</option>
</select>
</p>
</form>
</body>
</html>
ajax.js :
// ajax.js
/* This page defines a function for creating an Ajax request object.
* This page should be included by other pages that
* need to perform an XMLHttpRequest.
*/
/* Function for creating the XMLHttpRequest object.
* Function takes no arguments.
* Function returns a browser-specific XMLHttpRequest object
* or returns the Boolean value false.
*/
function getXMLHttpRequestObject() {
// Initialize the object:
var ajax = false;
// Choose object type based upon what's supported:
if (window.XMLHttpRequest) {
// IE 7, Mozilla, Safari, Firefox, Opera, most browsers:
ajax = new XMLHttpRequest();
} else if (window.ActiveXObject) { // Older IE browsers
// Create type Msxml2.XMLHTTP, if possible:
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) { // Create the older type instead:
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { }
}
} // End of main IF-ELSE IF.
// Return the value:
return ajax;
} // End of getXMLHttpRequestObject() function.
dept.js :
// dept.js
/* This page does all the magic for applying
* Ajax to an employees listing form.
* The department_id is sent to a PHP
* script which will return data in HTML format.
*/
// Have a function run after the page loads:
window.onload = init;
// Function that adds the Ajax layer:
function init() {
// Get an XMLHttpRequest object:
var ajax = getXMLHttpRequestObject();
// Attach the function call to the form submission, if supported:
if (ajax) {
// Check for DOM support:
if (document.getElementById('results')) {
// Add an onsubmit event handler to the form:
$('#did').change(function() {
// Call the PHP script.
// Use the GET method.
// Pass the department_id in the URL.
// Get the department_id:
var did = document.getElementById('did').value;
// Open the connection:
ajax.open('get', 'dept_results_ajax.php?did=' + encodeURIComponent(did));
// Function that handles the response:
ajax.onreadystatechange = function() {
// Pass it this request object:
handleResponse(ajax);
}
// Send the request:
ajax.send(null);
return false; // So form isn't submitted.
} // End of anonymous function.
)} // End of DOM check.
} // End of ajax IF.
} // End of init() function.
// Function that handles the response from the PHP script:
function handleResponse(ajax) {
// Check that the transaction is complete:
if (ajax.readyState == 4) {
// Check for a valid HTTP status code:
if ((ajax.status == 200) || (ajax.status == 304) ) {
// Put the received response in the DOM:
var results = document.getElementById('results');
results.innerHTML = ajax.responseText;
// Make the results box visible:
results.style.display = 'block';
} else { // Bad status code, submit the form.
document.getElementById('dept_form').submit();
}
} // End of readyState IF.
} // End of handleResponse() function.
dept_results_ajax.php
<?php # dept_results_ajax.php
// No need to make a full HTML document!
// Validate the received department ID:
$did = 0; // Initialized value.
if (isset($_GET['did'])) { // Received by the page.
$did = (int) $_GET['did']; // Type-cast to int.
}
// Make sure the department ID is a positive integer:
if ($did > 0) {
// Get the employees from the database...
// Include the database connection script:
require_once('mysql.inc.php');
// Query the database:
$q = "SELECT * FROM employees WHERE department_id=$did ORDER BY last_name, first_name";
$r = mysql_query($q, $dbc);
// Check that some results were returned:
if (mysql_num_rows($r) > 0) {
// Retrieve the results:
while ($row = mysql_fetch_array($r, MYSQL_ASSOC)) {
?>
<option value="<?php echo $row['last_name']; ?>"><?php echo $row['last_name']; ?></option>
<?php
} // End of WHILE loop.
} else { // No employees.
echo '<p class="error">There are no employees listed for the given department.</p>';
}
// Close the database connection.
mysql_close($dbc);
} else { // Invalid department ID!
echo '<p class="error">Please select a valid department from the drop-down menu in order to view its employees.</p>';
}
?>
Can someone explain the change I need to make in my scripts to achieve what I require.
Many thanks for any pointers. Very much appreciated.
You can do this in two ways: first, you can have a PHP script generate dept_form.html (which would then become a .php file, of course) and put all the results from your MySQL query into the menu; the second (and preferred, especially for large data sets) approach would be to insert a few lines after if (document.getElementById('results')) { in dept.js to load all the data, so even before setting the function on $('#did').change events. These lines would then simply make an AJAX call to the PHP script and get all the data you need.
By the way, you may want to consider using jQuery, which will make your life a lot easier in terms of AJAX calls. Hope this helps a bit.
EDIT
Try using something like this:
// Open the connection:
ajax.open('get', 'dept_results_ajax.php');
// Function that handles the response:
ajax.onreadystatechange = function() {
// Pass it this request object:
handleResponse(ajax);
}
// Send the request:
ajax.send(null);
Then, in your PHP script, just put the same code you already have under the else clause, except for the parts that are needed for processing the department ID, so pretty much whenever you have $did or a WHERE clause.
Related
Is there any way for an ajax call to, if a desired result wasn't met, extract a value and keep repeating itself every X seconds (or on user request) until it reaches said desired result?
The response of the call is presented as a json-serialized array. I'd like the ajax call to keep repeating itself until $status_code is 1 or the response == "error_bad_api_call".
snipped old code
UPDATE: (Answer)
PHP script we're going to call (10% chance to provide expected result):
<?php
$retArr = array();
$rand = rand(1, 1000);
if($rand < 100)
{
$retArr["status_code"] = 1;
echo json_encode($retArr);
}
else
{
$retArr["status_code"] = 0;
echo json_encode($retArr);
}
?>
The javascript + html:
<html>
<head>
<script src="include/jquery-1.7.2.min.js"></script>
<script src="include/jquery.json-2.3.min.js"></script>
<script type="text/javascript">
//Clean all elements on button click
function dosubmitClean(tries)
{
document.getElementById("resultsHere").innerHTML="";
document.getElementById("temp").innerHTML="";
document.getElementById("tries").innerHTML="";
dosubmit(tries); //Do actual work
}
function dosubmit(tries)
{
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var resp = xmlhttp.responseText; //Get response
document.getElementById("temp").innerHTML+="resp: "+xmlhttp.responseText+"<br/>"; //Show in event log
var status_code = $.evalJSON(resp).status_code; //Get status code
document.getElementById("temp").innerHTML+="status_code: "+status_code+"<br/>"; //Show in event log
document.getElementById("temp").innerHTML+="Checking status code <br/>"; //Show in event log
if(status_code == "1"){
document.getElementById("resultsHere").innerHTML+="status_code: is one <br/>"; //Show final result
document.getElementById("temp").innerHTML+="status_code: is one <br/>"; //Show in event log
document.getElementById("tries").innerHTML="Amount of tries: "+tries+"<br/><br/>Event log:<br/>"; //Show amount of tries
}
else{
document.getElementById("temp").innerHTML+="status_code: is NOT one <br/>"; //Show in event log
tries++; //Tries + 1
dosubmit(tries,"someval"); //Loop
}
document.getElementById("temp").innerHTML+="Done checking status code <br/><br/>"; //Show in event log
}
}
xmlhttp.open("GET","json_repeat_php.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="submit" value="submit" id="postDataSubmit" onClick="dosubmitClean(<?php echo 1; ?>);return false;">
<div id="resultsHere"></div>
<div id="tries"></div>
<div id="temp"></div>
</body>
</html>
Example Output:
status_code: is one
Amount of tries: 2
Event log:
resp: {"status_code":0}
status_code: 0
Checking status code
status_code: is NOT one
Done checking status code
resp: {"status_code":1}
status_code: 1
Checking status code
status_code: is one
Done checking status code
This is pretty easy. You already have your callback function, waiting for the result.
Now instead of returning the result as html as you currently do, return it as JSON, so you can easily evaluate it on clientside.
Include your necessary queueCodes in the elseif{...} of your php-code.
This could be something like this (Attention, this is pseudocode only!):
your json = { success : 0|1 , resultarray [item,item] /* only if success=1 */ , someMoreInfo : <queueCode> }
if ( success ){
// populate your html with the resulting items
}
else{
//perhaps wait some time, then
// call your ajax function again, with your queuecode as parameter
dosubmit( json.someMoreInfo );
}
and your dosubmit function sends the queuecode to your server.
A timeout might be useful, either on the server or client, whatever suits you more.
Additionally, you might want to take a look at JSONP
sidenotes:
using a switch in the elseif branch in your php might be more appropriate. Also, try to avoid writing the { on a newline in your javascript-code but rather always write function(){ or else{. This potentially saves you some trouble with javascript compilers trying to evaluate your code.
example:
return{
object
}
// returns the object
should be the same, but is not the same as:
return // comiler will add a ; after your return, thus your object won't be returned
{
object
}
Yes, you can do it recursively.
function send_request()
{
// perform ajax here and have a callback
// if value from callback indicates not successful call send_request() again
send_request();
// you may want to keep a count of how many times it fails, if it fails say, more than a set number of times then you can take the appropriate action
}
send_request();
Don't know where the problem is, but if I understood you correctly it's enough fro you to make:
function gather(queue) {
data = $('form#foo').serialize();
if (typeof queue != 'undefined') {
data += '&queue=' + queue;
} else {
queue = 0;
}
$.ajax('/frontend_test.php', data, function(r) {
var result = $.parseJSON(r);
if (typeof result.status_code == 'undefined' || result.status_code != 1) {
gather(++queue);
} else {
// Success, do whatever you need to.
}
});
And using it just by calling... it result wouldn't be reached - it goes to recursive call with incremented queue, first call doesn't need to be with any arguments.
Hope that's exactly what you need.
I have the following HTML.
Currently it relies on the user hitting the 'Go' button to Submit the Form.
Is it possible to change this so it submits each time the user selects a dropdown option?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Employees by Department</title>
<script src="ajax.js" type="text/javascript"></script>
<script src="dept.js" type="text/javascript"></script>
<style type="text/css" media="all">#import "style.css";</style>
</head>
<body>
<!-- dept_form_ajax.html -->
<p>Select a department and click 'GO' to see the employees in that department.</p>
<form action="dept_results.php" method="get" id="dept_form">
<p>
<select id="did" name="did">
<option value="1">Human Resources</option>
<option value="2">Accounting</option>
<option value="3">Marketing</option>
<option value="4">Redundancy Department</option>
</select>
<input name="go" type="submit" value="GO" />
</p>
</form>
<select id="results"></select>
</body>
</html>
For the record, here is my dept.js file contents:
// dept.js
/* This page does all the magic for applying
* Ajax to an employees listing form.
* The department_id is sent to a PHP
* script which will return data in HTML format.
*/
// Have a function run after the page loads:
window.onload = init;
// Function that adds the Ajax layer:
function init() {
// Get an XMLHttpRequest object:
var ajax = getXMLHttpRequestObject();
// Attach the function call to the form submission, if supported:
if (ajax) {
// Check for DOM support:
if (document.getElementById('results')) {
// Add an onsubmit event handler to the form:
document.getElementById('dept_form').onsubmit = function() {
// Call the PHP script.
// Use the GET method.
// Pass the department_id in the URL.
// Get the department_id:
var did = document.getElementById('did').value;
// Open the connection:
ajax.open('get', 'dept_results_ajax.php?did=' + encodeURIComponent(did));
// Function that handles the response:
ajax.onreadystatechange = function() {
// Pass it this request object:
handleResponse(ajax);
}
// Send the request:
ajax.send(null);
return false; // So form isn't submitted.
} // End of anonymous function.
} // End of DOM check.
} // End of ajax IF.
} // End of init() function.
// Function that handles the response from the PHP script:
function handleResponse(ajax) {
// Check that the transaction is complete:
if (ajax.readyState == 4) {
// Check for a valid HTTP status code:
if ((ajax.status == 200) || (ajax.status == 304) ) {
// Put the received response in the DOM:
var results = document.getElementById('results');
results.innerHTML = ajax.responseText;
// Make the results box visible:
results.style.display = 'block';
} else { // Bad status code, submit the form.
document.getElementById('dept_form').submit();
}
} // End of readyState IF.
} // End of handleResponse() function.
Many thanks for any pointers here.
This might give you an idea.
replace:
document.getElementById('dept_form').onsubmit = function() {
with this:
$('#did').change(function () {
or rather with this:
document.getElementById('did').onchange = function() {
You can try to use in select:
<select id="did" name="did" onchange="this.form.submit();">
I am currently using the following script to run a PHP script each time a dropdown menu option is selected. It works great.
It then returns the results from a SQL query and places it in a 2nd dropdown.
However, I would also like to run a PHP script when the web page initially loads.
Basically, I hope my select menu ("2nd dropdown") will be populated with the results of the PHP script when the page first loads. And the user can then filter the results down by using the first dropdown menu.
Here is my current Javascript file. I'm not using jQuery.
// Have a function run after the page loads:
window.onload = init;
/* ------------------------------------------------------------------------
* Can I run this...
* ajax.open('get', 'dept_results_ajax.php');
* ... as soon as my page loads and return the results?
* ------------------------------------------------------------------------
*/
// Function that adds the Ajax layer:
function init() {
// Get an XMLHttpRequest object:
var ajax = getXMLHttpRequestObject();
// Attach the function call to the form submission, if supported:
if (ajax) {
// Check for DOM support:
if (document.getElementById('results')) {
// Add an onsubmit event handler to the form:
$('#did').change(function() {
// Call the PHP script.
// Use the GET method.
// Pass the department_id in the URL.
// Get the department_id:
var did = document.getElementById('did').value;
// Open the connection:
ajax.open('get', 'dept_results_ajax.php?did=' + encodeURIComponent(did));
// Function that handles the response:
ajax.onreadystatechange = function() {
// Pass it this request object:
handleResponse(ajax);
}
// Send the request:
ajax.send(null);
return false; // So form isn't submitted.
} // End of anonymous function.
)} // End of DOM check.
} // End of ajax IF.
} // End of init() function.
// Function that handles the response from the PHP script:
function handleResponse(ajax) {
// Check that the transaction is complete:
if (ajax.readyState == 4) {
// Check for a valid HTTP status code:
if ((ajax.status == 200) || (ajax.status == 304) ) {
// Put the received response in the DOM:
var results = document.getElementById('results');
results.innerHTML = ajax.responseText;
// Make the results box visible:
results.style.display = 'block';
} else { // Bad status code, submit the form.
document.getElementById('dept_form').submit();
}
} // End of readyState IF.
} // End of handleResponse() function.
EDIT
// ajax.js
/* This page defines a function for creating an Ajax request object.
* This page should be included by other pages that
* need to perform an XMLHttpRequest.
*/
/* Function for creating the XMLHttpRequest object.
* Function takes no arguments.
* Function returns a browser-specific XMLHttpRequest object
* or returns the Boolean value false.
*/
function getXMLHttpRequestObject() {
// Initialize the object:
var ajax = false;
// Choose object type based upon what's supported:
if (window.XMLHttpRequest) {
// IE 7, Mozilla, Safari, Firefox, Opera, most browsers:
ajax = new XMLHttpRequest();
} else if (window.ActiveXObject) { // Older IE browsers
// Create type Msxml2.XMLHTTP, if possible:
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) { // Create the older type instead:
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { }
}
} // End of main IF-ELSE IF.
// Return the value:
return ajax;
} // End of getXMLHttpRequestObject() function.
Many thanks for any pointers here.
How can I limit the count of multiselect? Like I want the user to select atmost 3 elements from multiselect. If more than 3 are selected then I ll throw him an error...
Here is a complete example, showing the HTML of a simple form and the PHP that only allows up to three options being selected - and an added bonus of client-side JavaScript to explain how the user can be informed of their error before the form is submitted.
You can use JavaScript to stop the user checking more than three options, but note that client-side validation can easily be avoided, so you will still need to use PHP to verify on the server.
HTML
<!doctype html>
<head>
<meta charset="utf-8">
<title>Multiselect example</title>
</head>
<p>Please make a selection below (maximum three options!)</p>
<form method="post">
<select name="selection[]" multiple="multiple">
<!-- Put <option> elements here -->
</select>
<input type="submit">
</form>
<script src="Script.js"></script>
JavaScript (in Script.js):
var formChange = function(e) {
var i,
num = 0,
// Obtain a list of all selected options:
nodeList = this["selection[]"];
// Loop over all options, count how many are selected.
for(i = 0; i < nodeList.length; i++) {
if(nodeList[i].selected) {
num ++;
}
}
if(num > 3) {
alert("Please do not select more than three options");
e.preventDefault();
}
};
// Attach the same function to the change and submit event.
// This will alert the user of more than three selections
// as the fourth is selected, or as the form is submitted.
// ... it will also not allow the form to submit with
// more than three checked boxes.
document.forms[0].addEventListener("change", formChange);
document.forms[0].addEventListener("submit", formChange);
PHP:
if(isset($_POST["selection"])) {
if(count($_POST["selection"]) > 3) {
die("Error: More than three check boxes were checked.");
}
// $_POST["selection"] is an array of the checked values.
}
A multiselect element in PHP returns an array, so it's simply a matter of comparing the count() of the returned array against the maximum value you want to allow and generating some kind of error if the count exceeds the limit (throw an exception, trigger an error, etc).
If you want to do it server-side, look at the count() function. E.g.,
HTML:
<form ...>
<select name="options[]" multiple="multiple">
<!-- options here ... -->
</select>
...
</form>
PHP:
<?php
if (isset($_POST['options']) && count($_POST['options']) <= 3) {
// OK
} else {
// Not OK
}
?>
Take a look at this js function, suppose your multiselect object is "muSelect"
function checkSelected() {
var i;
var count = 0;
for (i=0; i<muSelect.options.length; i++) {
if (muSelect.options[i].selected) {
count++;
}
if (count > 3) {
alert("cant select more than three options";
// any other additionnal processing
}
}
}
and then you can add this function as onClick event
I know that this is an old question but if someone is trying to do the same thing now and looking for answers is best to write a current answer for this one. The best way at the moment is with AJAX (as long as I know):
HTML: form.html
<form id="myForm" action="validate.php?q=1">
<select name="options[]" multiple="multiple">
<!-- options here ... -->
</select>
...
</form>
PHP: validate.php
<?php
switch($_REQUEST['q']){
case 0:
if(isset($_REQUEST['options']) && count($_REQUEST['options']) <=3){
echo true;
}else{
echo false;
}
break;
case 1:
if(isset($_POST['options']) && !empty($_POST['options'])){
if(count($_POST['options']) <= 3){
//OK
}else{
//NOT OK
}
}
break;
}
?>
JavaScript(jQuery): script.js
var form = $("#myForm");
var options = $("#select_menu option")
var selected = [];
$(options).each(function(key,option){
if(option.selected){
selected[key] = option;
}
});
$.ajax({
url: "validate.php",
method: "GET",
data: {
options: selected,
q: 0
},
success: function(Response){
if(Response === true){
//OK
}else{
//NOT OK
}
}
});
Please correct me if I have error somewhere.
So i have a simple question, but i cant find the answer to it.
I have a form in which a user types something into the textfield and clicks the submit button with the value "Add". There will be list to the right and every time the user clicks add, there will be element added to the list on the right with a fade in animation.
I'm using php to make it so that every time the user clicks add, it queries the databse and finds what the user is looking for. And if it isnt in the database, then insert it into the database.
I'm using javascript/jquery to have the fade in animation when the user clicks "Add".
I know how to do these things individually, but when i click the Add button (the submit button), the entire page refreshes, php works fine, but there was no animation.
I try using preventDefault() on jquery, and the animation works fine, but the php code didnt register? How would i make it so that the php and javascript dont cut each other off? Does this have anything to do with ajax? Thanks
You need to use the jquery Ajax functions. These are especially made so that you can call php scripts without page refresh.
Click Here for the official documentation on Ajax post functions, and how to use them.
Here is an example that I came up with. Hopefully that can be helpful to you.
Content of index.php
This is where your form is and where added items will be displayed.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Page Title</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
<!--
jQuery(function($) {
// Declare DOM elements for quick access
var itemsList = $('#items-list'),
searchInput = $('#search-input');
// click event handler for the 'Add' button
$('#add-btn').click(function(e) {
// Prevent the form from being sent
e.preventDefault();
var searchValue = searchInput.val();
// Send the AJAX request with the search parameter
$.post('search.php', {
search: searchValue
},
function(data, textStatus) {
// data is returned as a json object
if (data.found) {
// Create a new hidden element into the list
// and make it fade in
$('<p class="item">'+searchValue+'</p>').hide()
.appendTo(itemsList)
.fadeIn();
}
}, 'json'
});
});
});
//-->
</script>
</head>
<body>
<form action="index.php" method="post" id="search-form">
<div>
<input type="text" name="search" id="search-input">
<input type="submit" id="add-btn" value="Add">
<div id="items-list"></div>
</div>
</form>
</body>
</html>
Content of search.php
<?php
// AJAX Request?
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// Prepare the reponse
$response = array('found' => FALSE);
// Check that the search parameter was provided
$search = filter_input(INPUT_POST, 'search', FILTER_SANITIZE_STRING);
if (!empty($search)) {
// Note: We'll assume a connection to a MySQL database
// with the following constant already declared
$mysqli = new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Make sure that the connection was successful
if (!$mysqli->connect_error) {
$query = "SELECT id, keyword FROM search_table WHERE keyword = ?";
// Check if the search keyword already exists
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $search);
$stmt->execute();
// Create a new entry if not found
if (0 == $stmt->num_rows()) {
$query = "INSERT INTO search_table(keyword) VALUES(?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $search);
$response['found'] = $stmt->execute();
}
else {
$response['found'] = TRUE;
}
}
}
echo json_encode($response);
}
This is not tested so let me know if you encounter any issues.
Cheers,