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.
Related
I am trying the following code to update external content inside a div named "content1"
ajax.js:
var ajaxdestination="";
function getdata(what,where) { // get data from source (what)
try {
xmlhttp = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { /* do nothing */ }
document.getElementById(where).innerHTML ="<center><img src='loading.gif'></center>"; // Define the destination DIV id, must be stored in global variable (ajaxdestination)
ajaxdestination=where;
xmlhttp.onreadystatechange = triggered; // when request finished, call the function to put result to destination DIV
xmlhttp.open("GET", what);
xmlhttp.send(null);
return false;
}
function triggered() { // put data returned by requested URL to selected DIV
if (xmlhttp.readyState == 4) if (xmlhttp.status == 200)
document.getElementById(ajaxdestination).innerHTML =xmlhttp.responseText;
}
Inside my div I include 'page1a.php' with php, wich outputs a value from my database and contains a link to 'code1a.php' where I have a php code that updates this value. (This is just a test and will do more than update a value in the future).
update value
Inside code1a.php where I have a php code that updates my database, after the database has been updated, is there a way to update my div (content1) with 'page1a.php' again?
I have tried everything i could think of and search the web for a few days, but not found a solution to my problem.
The script can be found on: http://www.battrewebbsida.se/index2.php
There are many variants to do this, your solution isn't best to do it, but here's the modified your javascript code, which is that what you want.
By Javascript
var ajaxdestination="";
var tmpcache = '';
function getdata(what,where) { // get data from source (what)
try {
xmlhttp = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { /* do nothing */ }
tmpcache = document.getElementById(where).innerHTML;
document.getElementById(where).innerHTML ="<center><img src='loading.gif'></center>"; // Define the destination DIV id, must be stored in global variable (ajaxdestination)
ajaxdestination=where;
xmlhttp.onreadystatechange = triggered; // when request finished, call the function to put result to destination DIV
xmlhttp.open("GET", what);
xmlhttp.send(null);
return false;
}
function triggered() { // put data returned by requested URL to selected DIV
if (xmlhttp.readyState == 4) if (xmlhttp.status == 200)
document.getElementById(ajaxdestination).innerHTML =tmpcache;
}
By PHP
after doing your updates in 'code1a.php' send header location to your first 'page1a.php' file
header("Location: ".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'/page1a.php');
NOTE: dont forget about ob_start() at the top of script.
I have a simple jquery function that sends a post request to a PHP file like this:
$.post('/file.php',
{
action: 'send'
},
function(data, textStatus)
{
alert(data);
});
And a PHP file:
<?php
/* Some SQL queries here */
echo 'action done';
/* echo response back to jquery and continue other actions here */
?>
jQuery by default waits till executing the whole PHP script before giving the alert. Is there a way to alert the action done before executing the rest of the PHP file??
Thanks
It is possible with plain Javascript ajax. The onreadystatechange event will fire with a readyState of 3, when data is received before the request is complete.
In the example below, newData will contain the new piece of data. We have to do some processing because the XHR actually gives us the entire data so far in responseText and so if we only want to know the new data, we have to keep a record of the last index.
var httpRequest, lastIndex = 0;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState === 3) {
var newData = httpRequest.responseText.substring(lastIndex);
lastIndex = httpRequest.responseText.length;
console.log(newData);
}
};
httpRequest.open('POST', '/file.php');
httpRequest.send('action=send');
As for jQuery ajax, this answer suggests jQuery lets you bind to the readystatechange but I haven't tested it.
i am having trouble making this part of code to work, basically i want to call this function which sends a variable to a php page. Ive tested that the variable is there and also tested that my php page is accepting information as it should be , however i cant make this Ajax thing work.
function ajaxRequest(myname) {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest)
{ // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else
{ // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null)
{ // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
AJAX.onreadystatechange = function()
{ // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete")
{ // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
} // End Ajax readystate check.
}
alert("Alert1");
var url='http://localhost/main.php?Name=myname';
AJAX.open("POST", url, true); // Open the url this object was set-up with.
alert("Alert2");
AJAX.send(); // Send the request.
}
This is my php part which should accept the variable
<?php
$var=$_GET['Name'];
echo $var;
?>
Okay firstly you need to change your request to GET from POST
like
AJAX.open("GET", url, true); // Open the url this object was set-up with.
and you also need to update this line
from
var url='http://localhost/main.php?Name=myname';
to
var url='http://localhost/main.php?Name='+myname;
my full script is:
<script type="text/javascript">
function ajaxRequest(myname) {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest)
{ // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else { // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null)
{ // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
AJAX.onreadystatechange = function()
{ // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete")
{ // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
} // End Ajax readystate check.
}
alert("Alert1");
var url='http://localhost/main.php?Name='+myname;
AJAX.open("GET", url, true); // Open the url this object was set-up with.
alert("Alert2");
AJAX.send(); // Send the request.
}
</script>
you might also be missing the callback function so add it so that it looks like this
function callback(x, y) {
alert(x);
}
And call your AJAX function by
ajaxRequest("ashley");
Here is your required main.php code (even though this isn't what you should be using AJAX for
<?php
session_start();
if(isset($_GET["Name"])) {
$_SESSION["Name"] = $_GET["Name"];
}
if(isset($_SESSION["Name"])) {
echo $_SESSION["Name"];
} else {
echo "The AJAX has not been run!";
}
?>
There are two ways to send an ajax request to server
Either GET or POST
1. GET Method:
var url='http://localhost/main.php?Name='+myname; // you can add any numner of vars here
AJAX.open("GET", url, true);
AJAX.send();
Code in main.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_GET['Name'];
}
2. POST Method:
AJAX.open("POST","ajax_test.asp",true);
AJAX.setRequestHeader("Content-type","application/x-www-form-urlencoded");
AJAX.send("Name="+myname);
Code in main.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_POST['Name'];
}
I created function to send email with a back link to my site, I'm using codeigniter framework
after user click that particular link (back link) on email, user redirects to my page which has an iframe.
i used that iframe to submit a form with file input, with out page refreshing.
When user coming through that link using gmail in IE9 browser the form.submit() function fails, in other browsers it works properly and other email(except gmail) too.
pleas help me to find solution
thank you.
update
actually I'm using the ajaxupload jquery library, it fails on the line form.submit(); at above scenario
/* Creates form, that will be submitted to iframe
* #param {Element} iframe Where to submit
* #return {Element} form
*/
_createForm: function(iframe){
var settings = this._settings;
// We can't use the following code in IE6
// var form = document.createElement('form');
// form.setAttribute('method', 'post');
// form.setAttribute('enctype', 'multipart/form-data');
// Because in this case file won't be attached to request
var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
form.setAttribute('action', settings.action);
form.setAttribute('target', iframe.name);
form.style.display = 'none';
document.body.appendChild(form);
// Create hidden input element for each data key
for (var prop in settings.data) {
if (settings.data.hasOwnProperty(prop)){
var el = document.createElement("input");
el.setAttribute('type', 'hidden');
el.setAttribute('name', prop);
el.setAttribute('value', settings.data[prop]);
form.appendChild(el);
}
}
return form;
},
/**
* Gets response from iframe and fires onComplete event when ready
* #param iframe
* #param file Filename to use in onComplete callback
*/
_getResponse : function(iframe, file){
// getting response
var toDeleteFlag = false, self = this, settings = this._settings;
addEvent(iframe, 'load', function(){
if (// For Safari
iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
// For FF, IE
iframe.src == "javascript:'<html></html>';"){
// First time around, do not delete.
// We reload to blank page, so that reloading main page
// does not re-submit the post.
if (toDeleteFlag) {
// Fix busy state in FF3
setTimeout(function(){
removeNode(iframe);
}, 0);
}
return;
}
var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
// fixing Opera 9.26,10.00
if (doc.readyState && doc.readyState != 'complete') {
// Opera fires load event multiple times
// Even when the DOM is not ready yet
// this fix should not affect other browsers
return;
}
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false") {
// In Opera 9.64 event was fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
return;
}
var response;
if (doc.XMLDocument) {
// response is a xml document Internet Explorer property
response = doc.XMLDocument;
} else if (doc.body){
// response is html document or plain text
response = doc.body.innerHTML;
if (settings.responseType && settings.responseType.toLowerCase() == 'json') {
// If the document was sent as 'application/javascript' or
// 'text/javascript', then the browser wraps the text in a <pre>
// tag and performs html encoding on the contents. In this case,
// we need to pull the original text content from the text node's
// nodeValue property to retrieve the unmangled content.
// Note that IE6 only understands text/html
if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
doc.normalize();
response = doc.body.firstChild.firstChild.nodeValue;
}
if (response) {
response = eval("(" + response + ")");
} else {
response = {};
}
}
} else {
// response is a xml document
response = doc;
}
settings.onComplete.call(self, file, response);
// Reload blank page, so that reloading main page
// does not re-submit the post. Also, remember to
// delete the frame
toDeleteFlag = true;
// Fix IE mixed content issue
iframe.src = "javascript:'<html></html>';";
});
},
/**
* Upload file contained in this._input
*/
submit: function(){
var self = this, settings = this._settings;
if ( ! this._input || this._input.value === ''){
return;
}
var file = fileFromPath(this._input.value);
// user returned false to cancel upload
if (false === settings.onSubmit.call(this, file, getExt(file))){
this._clearInput();
return;
}
// sending request
var iframe = this._createIframe();
var form = this._createForm(iframe);
// assuming following structure
// div -> input type='file'
removeNode(this._input.parentNode);
removeClass(self._button, self._settings.hoverClass);
removeClass(self._button, self._settings.focusClass);
form.appendChild(this._input);
form.submit();
// request set, clean up
removeNode(form); form = null;
removeNode(this._input); this._input = null;
// Get response from iframe and fire onComplete event when ready
this._getResponse(iframe, file);
// get ready for next request
this._createInput();
}
};
Check the the code is in iframe if not specify the iframe in form.submit(), i.e.
document.iframename.form.submit();
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.