When the user types something into the search bar I would like the results bellow to link to a page when you click it instead of filling the search bar with whatever you clicked. I'm very new to Jquery and I found this tutorial online but it isn't doing exactly what I wanted it to.
Index.php (Just showing some of the head and the body)
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
</script>
</head>
<body>
<label>Tag:</label>
<input name="tag" type="text" id="tag" size="20" style="width:541px; height:23px; font-size:16px; text-indent:5px;" placeholder="Search foods, shopping lists, meal plans and recipes" />
</body>
autocomplete.php (Even with the and tags I was unable to achieve the linking to another page.)
<?php
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
include ("connect.php");
$sql="SELECT id, name, description, foodgroup FROM foods WHERE name LIKE '%$my_data%' ORDER BY name";
$result = mysql_query($sql);
if($result) {
while($row=mysql_fetch_array($result)) {
print "<a href='food.php?foodGroup=" . $row['foodgroup'] . "&name=" . $row['name'] . "&desc=" . $row['description'] . "&foodID=" . $row['id'] . "'><div id='resultContainerDiv'><span id='resultText'>" . $row['name'] . " - " . $row['description'] . "</span></div></a>\n";
}
}
?>
lastly, jquery.autocomplete.js
/* * jQuery Autocomplete plugin 1.1 * * Copyright (c) 2009 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $ */
;(function($) { $.fn.extend({ autocomplete: function(urlOrData, options) { var isUrl = typeof urlOrData == "string"; options = $.extend({}, $.Autocompleter.defaults, { url: isUrl ? urlOrData : null, data: isUrl ? null : urlOrData, delay: isUrl ? $.Autocompleter.defaults.delay : 10, max: options && !options.scroll ? 10 : 150 }, options);
// if highlight is set to false, replace it with a do-nothing function options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() { new $.Autocompleter(this, options); }); }, result: function(handler) { return this.bind("result", handler); }, search: function(handler) { return this.trigger("search", [handler]); }, flushCache: function() { return this.trigger("flushCache"); }, setOptions: function(options){ return this.trigger("setOptions", [options]); }, unautocomplete: function() { return this.trigger("unautocomplete"); } });
$.Autocompleter = function(input, options) {
var KEY = { UP: 38, DOWN: 40, DEL: 46, TAB: 9, RETURN: 13, ESC: 27, COMMA: 188, PAGEUP: 33, PAGEDOWN: 34, BACKSPACE: 8 };
// Create $ object for input element var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
var timeout; var previousValue = ""; var cache = $.Autocompleter.Cache(options); var hasFocus = 0; var lastKeyPressCode; var config = { mouseDownOnSelect: false }; var select = $.Autocompleter.Select(options, input, selectCurrent, config); var blockSubmit; // prevent form submit in opera when selecting with return key $.browser.opera && $(input.form).bind("submit.autocomplete", function() { if (blockSubmit) { blockSubmit = false; return false; } }); // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) { // a keypress means the input has focus // avoids issue where input had focus before the autocomplete was applied hasFocus = 1; // track last key pressed lastKeyPressCode = event.keyCode; switch(event.keyCode) {
case KEY.UP:
event.preventDefault();
if ( select.visible() ) {
select.prev();
} else {
onChange(0, true);
}
break;
case KEY.DOWN:
event.preventDefault();
if ( select.visible() ) {
select.next();
} else {
onChange(0, true);
}
break;
case KEY.PAGEUP:
event.preventDefault();
if ( select.visible() ) {
select.pageUp();
} else {
onChange(0, true);
}
break;
case KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
// matches also semicolon case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA: case KEY.TAB: case KEY.RETURN:
if( selectCurrent() ) {
// stop default to prevent a form submit, Opera needs special handling
event.preventDefault();
blockSubmit = true;
return false;
}
break;
case KEY.ESC:
select.hide();
break;
default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break; } }).focus(function(){ // track whether the field has focus, we shouldn't process any // results if the field no longer has focus hasFocus++; }).blur(function() { hasFocus = 0; if (!config.mouseDownOnSelect) { hideResults(); } }).click(function() { // show select when clicking in a focused field if ( hasFocus++ > 1 && !select.visible() ) { onChange(0, true); } }).bind("search", function() { // TODO why not just specifying both arguments? var fn = (arguments.length > 1) ? arguments[1] : null; function findValueCallback(q, data) { var result; if( data && data.length ) {
for (var i=0; i < data.length; i++) {
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
result = data[i];
break;
}
} } if( typeof fn == "function" ) fn(result); else $input.trigger("result", result && [result.data, result.value]); } $.each(trimWords($input.val()), function(i, value) { request(value, findValueCallback, findValueCallback); }); }).bind("flushCache", function() { cache.flush(); }).bind("setOptions", function() { $.extend(options, arguments[1]); // if we've updated the data, repopulate if ( "data" in arguments[1] ) cache.populate(); }).bind("unautocomplete", function() { select.unbind(); $input.unbind(); $(input.form).unbind(".autocomplete"); });
function selectCurrent() { var selected = select.selected(); if( !selected ) return false;
var v = selected.result; previousValue = v;
if ( options.multiple ) { var words = trimWords($input.val()); if ( words.length > 1 ) {
var seperator = options.multipleSeparator.length;
var cursorAt = $(input).selection().start;
var wordAt, progress = 0;
$.each(words, function(i, word) {
progress += word.length;
if (cursorAt <= progress) {
wordAt = i;
return false;
}
progress += seperator;
});
words[wordAt] = v;
// TODO this should set the cursor to the right position, but it gets overriden somewhere
//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
v = words.join( options.multipleSeparator ); } v += options.multipleSeparator; }
$input.val(v); hideResultsNow(); $input.trigger("result", [selected.data, selected.value]); return true; } function onChange(crap, skipPrevCheck) { if( lastKeyPressCode == KEY.DEL ) { select.hide(); return; }
var currentValue = $input.val();
if ( !skipPrevCheck && currentValue == previousValue ) return;
previousValue = currentValue;
currentValue = lastWord(currentValue); if ( currentValue.length >= options.minChars) { $input.addClass(options.loadingClass); if (!options.matchCase)
currentValue = currentValue.toLowerCase(); request(currentValue, receiveData, hideResultsNow); } else { stopLoading(); select.hide(); } }; function trimWords(value) { if (!value) return [""]; if (!options.multiple) return [$.trim(value)]; return $.map(value.split(options.multipleSeparator), function(word) { return $.trim(value).length ? $.trim(word) : null; }); } function lastWord(value) { if ( !options.multiple ) return value; var words = trimWords(value); if (words.length == 1) return words[0]; var cursorAt = $(input).selection().start; if (cursorAt == value.length) { words = trimWords(value) } else { words = trimWords(value.replace(value.substring(cursorAt), "")); } return words[words.length - 1]; } // fills in the input box w/the first match (assumed to be the best match) // q: the term entered // sValue: the first matching result function autoFill(q, sValue){ // autofill in the complete box w/the first match as long as the user hasn't entered in more data // if the last user key pressed was backspace, don't autofill if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) { // fill in the value (keep the case the user has typed) $input.val($input.val() + sValue.substring(lastWord(previousValue).length)); // select the portion of the value not typed by the user (so the next character will erase) $(input).selection(previousValue.length, previousValue.length + sValue.length); } };
function hideResults() { clearTimeout(timeout); timeout = setTimeout(hideResultsNow, 200); };
function hideResultsNow() { var wasVisible = select.visible(); select.hide(); clearTimeout(timeout); stopLoading(); if (options.mustMatch) { // call search and run callback $input.search(
function (result){
// if no value found, clear the input box
if( !result ) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, -1);
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
}
else {
$input.val( "" );
$input.trigger("result", null);
}
}
} ); } };
function receiveData(q, data) { if ( data && data.length && hasFocus ) { stopLoading(); select.display(data, q); autoFill(q, data[0].value); select.show(); } else { hideResultsNow(); } };
function request(term, success, failure) { if (!options.matchCase) term = term.toLowerCase(); var data = cache.load(term); // recieve the cached data if (data && data.length) { success(term, data); // if an AJAX url has been supplied, try loading the data now } else if( (typeof options.url == "string") && (options.url.length > 0) ){
var extraParams = {
timestamp: +new Date() }; $.each(options.extraParams, function(key, param) {
extraParams[key] = typeof param == "function" ? param() : param; });
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
} }); } else { // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match select.emptyList(); failure(term); } }; function parse(data) { var parsed = []; var rows = data.split("\n"); for (var i=0; i < rows.length; i++) { var row = $.trim(rows[i]); if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
}; } } return parsed; };
function stopLoading() { $input.removeClass(options.loadingClass); };
};
$.Autocompleter.defaults = { inputClass: "ac_input", resultsClass: "ac_results", loadingClass: "ac_loading", minChars: 1, delay: 400, matchCase: false, matchSubset: true, matchContains: false, cacheLength: 10, max: 100, mustMatch: false, extraParams: {}, selectFirst: true, formatItem: function(row) { return row[0]; }, formatMatch: null, autoFill: false, width: 0, multiple: false, multipleSeparator: ", ", highlight: function(value, term) { return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"); },
scroll: true,
scrollHeight: 180 };
$.Autocompleter.Cache = function(options) {
var data = {}; var length = 0; function matchSubset(s, sub) { if (!options.matchCase) s = s.toLowerCase(); var i = s.indexOf(sub); if (options.matchContains == "word"){ i = s.toLowerCase().search("\\b" + sub.toLowerCase()); } if (i == -1) return false; return i == 0 || options.matchContains; }; function add(q, value) { if (length > options.cacheLength){ flush(); } if (!data[q]){ length++; } data[q] = value; } function populate(){ if( !options.data ) return false; // track the matches var stMatchSets = {}, nullData = 0;
// no url was specified, we need to adjust the cache length to make sure it fits the local data store if( !options.url ) options.cacheLength = 1;
// track all options for minChars = 0 stMatchSets[""] = [];
// loop through the array and create a lookup structure for ( var i = 0, ol = options.data.length; i < ol; i++ ) { var rawValue = options.data[i]; // if rawValue is a string, make an array otherwise just reference the array rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
var value = options.formatMatch(rawValue, i+1, options.data.length); if ( value === false )
continue;
var firstChar = value.charAt(0).toLowerCase(); // if no lookup array for this character exists, look it up now if( !stMatchSets[firstChar] )
stMatchSets[firstChar] = [];
// if the match is a string var row = {
value: value,
data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value };
// push the current match into the set list stMatchSets[firstChar].push(row);
// keep track of minChars zero items if ( nullData++ < options.max ) {
stMatchSets[""].push(row); } };
// add the data items to the cache $.each(stMatchSets, function(i, value) { // increase the cache size options.cacheLength++; // add to the cache add(i, value); }); } // populate any existing data setTimeout(populate, 25); function flush(){ data = {}; length = 0; } return { flush: flush, add: add, populate: populate, load: function(q) { if (!options.cacheLength || !length)
return null; /*
* if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches
*/ if( !options.url && options.matchContains ){
// track all matches
var csub = [];
// loop through all the data grids for matches
for( var k in data ){
// don't search through the stMatchSets[""] (minChars: 0) cache
// this prevents duplicates
if( k.length > 0 ){
var c = data[k];
$.each(c, function(i, x) {
// if we've got a match, add it to the array
if (matchSubset(x.value, q)) {
csub.push(x);
}
});
}
}
return csub; } else // if the exact item exists, use it if (data[q]){
return data[q]; } else if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var c = data[q.substr(0, i)];
if (c) {
var csub = [];
$.each(c, function(i, x) {
if (matchSubset(x.value, q)) {
csub[csub.length] = x;
}
});
return csub;
}
} } return null; } }; };
$.Autocompleter.Select = function (options, input, select, config) { var CLASSES = { ACTIVE: "ac_over" }; var listItems, active =
-1, data, term = "", needsInit = true, element, list; // Create results function init() { if (!needsInit) return; element = $("<div/>") .hide() .addClass(options.resultsClass) .css("position", "absolute") .appendTo(document.body);
list = $("<ul/>").appendTo(element).mouseover( function(event) { if(target(event).nodeName && target(event).nodeName.toUpperCase()
== 'LI') {
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE);
} }).click(function(event) { $(target(event)).addClass(CLASSES.ACTIVE); select(); // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus input.focus(); return false; }).mousedown(function() { config.mouseDownOnSelect = true; }).mouseup(function() { config.mouseDownOnSelect = false; });
if( options.width > 0 ) element.css("width", options.width);
needsInit = false; } function target(event) { var element = event.target; while(element && element.tagName != "LI") element = element.parentNode; // more fun with IE, sometimes event.target is empty, just ignore it then if(!element) return []; return element; }
function moveSelect(step) { listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE); movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if(options.scroll) {
var offset = 0;
listItems.slice(0, active).each(function() {
offset += this.offsetHeight; });
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
} else if(offset < list.scrollTop()) {
list.scrollTop(offset);
}
} }; function movePosition(step) { active += step; if (active < 0) { active = listItems.size() - 1; } else if (active
>= listItems.size()) { active = 0; } } function limitNumberOfItems(available) { return options.max && options.max < available ? options.max : available; } function fillList() { list.empty(); var max = limitNumberOfItems(data.length); for (var i=0; i < max; i++) { if (!data[i])
continue; var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term); if ( formatted === false )
continue; var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0]; $.data(li, "ac_data", data[i]); } listItems = list.find("li"); if ( options.selectFirst ) { listItems.slice(0, 1).addClass(CLASSES.ACTIVE); active = 0; } // apply bgiframe if available if ( $.fn.bgiframe ) list.bgiframe(); } return { display: function(d, q) { init(); data = d; term = q; fillList(); }, next: function() { moveSelect(1); }, prev: function() { moveSelect(-1); }, pageUp: function() { if (active != 0 && active - 8 < 0) {
moveSelect( -active ); } else {
moveSelect(-8); } }, pageDown: function() { if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
moveSelect( listItems.size() - 1 - active ); } else {
moveSelect(8); } }, hide: function() { element && element.hide(); listItems && listItems.removeClass(CLASSES.ACTIVE); active = -1; }, visible : function() { return element && element.is(":visible"); }, current: function() { return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]); }, show: function() { var offset = $(input).offset(); element.css({
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
top: offset.top + input.offsetHeight,
left: offset.left }).show();
if(options.scroll) {
list.scrollTop(0);
list.css({
maxHeight: options.scrollHeight,
overflow: 'auto'
});
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0;
listItems.each(function() {
listHeight += this.offsetHeight;
});
var scrollbarsVisible = listHeight > options.scrollHeight;
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
if (!scrollbarsVisible) {
// IE doesn't recalculate width when scrollbar disappears
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
}
}
} }, selected: function() { var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE); return selected && selected.length && $.data(selected[0], "ac_data"); }, emptyList: function (){ list && list.empty(); }, unbind: function() { element && element.remove(); } }; };
$.fn.selection = function(start, end) { if (start !== undefined) { return this.each(function() { if( this.createTextRange ){
var selRange = this.createTextRange();
if (end === undefined || start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
} } else if( this.setSelectionRange ){
this.setSelectionRange(start, end); } else if( this.selectionStart ){
this.selectionStart = start;
this.selectionEnd = end; } }); } var field = this[0]; if ( field.createTextRange ) { var range = document.selection.createRange(), orig = field.value, teststring
= "<->", textLength = range.text.length; range.text = teststring; var caretAt = field.value.indexOf(teststring); field.value = orig; this.selection(caretAt, caretAt + textLength); return { start: caretAt, end: caretAt + textLength } } else if( field.selectionStart !== undefined ){ return { start: field.selectionStart, end: field.selectionEnd } } };
})(jQuery);
Thank you,
Ryan
In the search script you have an error:
<?php
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
include ("connect.php");
mysql_real_escape_string will return false (the equivalent of an empty string) if there is no database connection yet so you are effectively emptying your search string.
You need to switch that around:
<?php
$q=$_GET['q'];
include ("connect.php");
$my_data=mysql_real_escape_string($q);
You should also add error handling to your database calls and move to PDO or mysqli if possible as the mysql_* functions are deprecated.
I am using the below code to create a YUI datatable with dynamic data(columns). But am facing a issue in server side pagination. As of now it is working fine with client side pagination, but I need server side pagination, so that my page loading time will get reduced. Can you help me on this to fix the issue. Since I'm struggling in this area for past 2 days.Server side pagination with AJAX to render the data is my expectation.
Here is the code I Used
DataProvider.prototype = {
url:null,
data:null,
ds:null,
getData:function() {return this.data},
initialize:function(){
var str = generateRequest();
var newUrl = this.url+str;
YAHOO.util.Connect.asyncRequest('GET', newUrl, this);
},
success:function(response){
var responseVal = YAHOO.lang.JSON.parse(response.responseText);
var columnList = responseVal.columnList;
var sortedBy = responseVal.sortedBy;
this.data = responseVal.results;
if(this.data == '') {
$('#dynamicdata').html('<font style="color:red;"> No Data Found!</font>');
} else {
this.ds = new YAHOO.util.FunctionDataSource(function(){return this.dataProvider.getData()});
this.ds.responseSchema = {
resultsList:"results",
fields:columnList,
// Access to values in the server response
metaFields: {
totalRecords: "totalRecords",
startIndex: "startIndex"
}
}
this.ds.dataProvider = this;
// DataTable configuration
var myConfigs = {
paginator: new YAHOO.widget.Paginator({ rowsPerPage:20 }), // Enables pagination
width:"80%", height:"auto"
};
// FORMATTING CELL COLOUR BASED ON THEIR VALUES
var myCustomFormatter = function(elLiner, oRecord, oColumn, oData) {
var columnKey = oColumn.getKey();
var frmCurrentPeroid = $('#from').val();
//var frmCurrentPeroid = '2013-03-13';
var defaultLabels = ['Product type','Total 1','Total 2','Change'];
if (isDate(columnKey) && $.inArray(columnKey, defaultLabels) === -1) {
if(columnKey < frmCurrentPeroid) {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
} else {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
}
} else {
if(columnKey == 'Total 1') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Total 2') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Change') {
split_data = oData.toString().split('_');
var fieldData = null;
var fieldFormatter = null;
fieldData = split_data[0];
fieldFormatter = split_data[1];
if(fieldFormatter == 'green') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'green');
elLiner.innerHTML = fieldData;
}
if(fieldFormatter == 'red') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'red');
elLiner.innerHTML = fieldData;
}
}
else if(columnKey == 'Product Name') {
var filterStr = oData.substring(0,30);
elLiner.innerHTML = ''+filterStr+'';
//alert('blue');
}
else {
elLiner.innerHTML = oData;
}
}
};
// Add the custom formatter to the shortcuts
YAHOO.widget.DataTable.Formatter.myCustom = myCustomFormatter;
//YAHOO.widget.DataTable.formatLink = formatLink;
/* make call to initialize your table using the data set */
var myDataTable = new YAHOO.widget.DataTable("dynamicdata", columnList, this.ds, myConfigs);
}
}
}
Followed the code posted in this page
Click here
Thanks in Advance,
Raja
I haven't been doing YUI2 for quite some time so I am no longer able to help you directly. Perhaps this example can help: http://www.satyam.com.ar/yui/#ServerDriven . I do remember that there were big changes in 2.6 and this examples are marked 2.4, perhaps they no longer work.
I'm wrestling with an issue involving a log in form which is fetched using Ajax then displayed in a jQuery overlay. The overlay works perfectly, the issue is that when I click submit (using incorrect details) a the overlay closes instead of displaying the appropriate errors. The PHP code is on the login page (admin/index.php).
Button HTML:
<input name="Submit" type="submit" value="Log In" class="submit" />
Form tag HTML:
<form id="loginForm" method="post" action="">
PHP code:
ob_start();
define('INCLUDE_CHECK',true);
include '../includes/config.php';
session_name('cmsLogin');
session_set_cookie_params(2*7*24*60*60);
session_start();
if($_SESSION['id'] && !isset($_COOKIE['cmsRemember']) && !$_SESSION['rememberMe']) {
$_SESSION = array();
session_destroy();
}
if($_SESSION['id'] && isset($_COOKIE['cmsRemember'])) {
header("Location: loggedIn.php");
}
if($_POST['formName']=='login') {
$err = array();
if(!$_POST['email'] || !$_POST['password'])
$err[] = '<strong>Error:</strong> Please ensure the email & password fields have been completed.';
if(!count($err)) {
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
$row = mysql_fetch_assoc(mysql_query("SELECT * FROM cms_members WHERE email='{$_POST['email']}' AND password='".md5($_POST['password'])."'"));
if($row['email']) {
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['email'] = $row['email'];
setcookie('cmsRemember',$_POST['rememberMe']);
}
else $err[]='<strong>Error:</strong> The email and/or password you have entered is invalid.';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
header("Location: index.php");
exit;
}
else {
header("Location: loggedIn.php");
}
}
else {
}
$script = '';
Javascript:
(function($){
//closeDOMWindow
$.fn.closeDOMWindow = function(settings){
if(!settings){settings={};}
var run = function(passingThis){
if(settings.anchoredClassName){
var $anchorClassName = $('.'+settings.anchoredClassName);
$anchorClassName.fadeOut('fast',function(){
if($.fn.draggable){
$anchorClassName.draggable('destory').trigger("unload").remove();
}else{
$anchorClassName.trigger("unload").remove();
}
});
if(settings.functionCallOnClose){settings.functionCallAfterClose();}
}else{
var $DOMWindowOverlay = $('#DOMWindowOverlay');
var $DOMWindow = $('#DOMWindow');
$DOMWindowOverlay.fadeOut('fast',function(){
$DOMWindowOverlay.trigger('unload').unbind().remove();
});
$DOMWindow.fadeOut('fast',function(){
if($.fn.draggable){
$DOMWindow.draggable("destroy").trigger("unload").remove();
}else{
$DOMWindow.trigger("unload").remove();
}
});
$(window).unbind('scroll.DOMWindow');
$(window).unbind('resize.DOMWindow');
if($.fn.openDOMWindow.isIE6){$('#DOMWindowIE6FixIframe').remove();}
if(settings.functionCallOnClose){settings.functionCallAfterClose();}
}
};
if(settings.eventType){//if used with $().
return this.each(function(index){
$(this).bind(settings.eventType, function(){
run(this);
return false;
});
});
}else{//else called as $.function
run();
}
};
//allow for public call, pass settings
$.closeDOMWindow = function(s){$.fn.closeDOMWindow(s);};
//openDOMWindow
$.fn.openDOMWindow = function(instanceSettings){
var shortcut = $.fn.openDOMWindow;
//default settings combined with callerSettings////////////////////////////////////////////////////////////////////////
shortcut.defaultsSettings = {
anchoredClassName:'',
anchoredSelector:'',
borderColor:'#FFFFFF',
borderSize:'0',
draggable:0,
eventType:'click', //click, blur, change, dblclick, error, focus, load, mousedown, mouseout, mouseup etc...
fixedWindowY:20,
functionCallOnOpen:null,
functionCallOnClose:null,
height:340,
loader:1,
loaderHeight:32,
loaderImagePath:'images/icon_loader.gif',
loaderWidth:32,
modal:0,
overlay:1,
overlayColor:'#000',
overlayOpacity:'75',
positionLeft:0,
positionTop:10,
positionType:'centered', // centered, anchored, absolute, fixed
width:280,
windowBGColor:'',
windowBGImage:null, // http path
windowHTTPType:'get',
windowPadding:0,
windowSource:'ajax', //inline, ajax, iframe
windowSourceID:'',
windowSourceURL:'',
windowSourceAttrURL:'href'
};
var settings = $.extend({}, $.fn.openDOMWindow.defaultsSettings , instanceSettings || {});
//Public functions
shortcut.viewPortHeight = function(){ return self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;};
shortcut.viewPortWidth = function(){ return self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;};
shortcut.scrollOffsetHeight = function(){ return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;};
shortcut.scrollOffsetWidth = function(){ return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;};
shortcut.isIE6 = typeof document.body.style.maxHeight === "undefined";
//Private Functions/////////////////////////////////////////////////////////////////////////////////////////////////////////
var sizeOverlay = function(){
var $DOMWindowOverlay = $('#DOMWindowOverlay');
if(shortcut.isIE6){//if IE 6
var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
var overlayViewportWidth = document.documentElement.offsetWidth - 21;
$DOMWindowOverlay.css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
}else{//else Firefox, safari, opera, IE 7+
$DOMWindowOverlay.css({'height':'100%','width':'100%','position':'fixed'});
}
};
var sizeIE6Iframe = function(){
var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
var overlayViewportWidth = document.documentElement.offsetWidth - 21;
$('#DOMWindowIE6FixIframe').css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
};
var centerDOMWindow = function() {
var $DOMWindow = $('#DOMWindow');
if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
$DOMWindow.css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindow.outerWidth())/2));
}else{
$DOMWindow.css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindow.outerWidth())/2));
$DOMWindow.css('top',Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($DOMWindow.outerHeight())/2));
}
};
var centerLoader = function() {
var $DOMWindowLoader = $('#DOMWindowLoader');
if(shortcut.isIE6){//if IE 6
$DOMWindowLoader.css({'left':Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindowLoader.innerWidth())/2),'position':'absolute'});
$DOMWindowLoader.css({'top':Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($DOMWindowLoader.innerHeight())/2),'position':'absolute'});
}else{
$DOMWindowLoader.css({'left':'50%','top':'50%','position':'fixed'});
}
};
var fixedDOMWindow = function(){
var $DOMWindow = $('#DOMWindow');
$DOMWindow.css('left', settings.positionLeft + shortcut.scrollOffsetWidth());
$DOMWindow.css('top', + settings.positionTop + shortcut.scrollOffsetHeight());
};
var showDOMWindow = function(instance){
if(arguments[0]){
$('.'+instance+' #DOMWindowLoader').remove();
$('.'+instance+' #DOMWindowContent').fadeIn('fast',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}});
$('.'+instance+ '.closeDOMWindow').click(function(){
$.closeDOMWindow();
return false;
});
}else{
$('#DOMWindowLoader').remove();
$('#DOMWindow').fadeIn('fast',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}});
$('#DOMWindow .closeDOMWindow').click(function(){
$.closeDOMWindow();
return false;
});
}
};
var urlQueryToObject = function(s){
var query = {};
s.replace(/b([^&=]*)=([^&=]*)b/g, function (m, a, d) {
if (typeof query[a] != 'undefined') {
query[a] += ',' + d;
} else {
query[a] = d;
}
});
return query;
};
//Run Routine ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
var run = function(passingThis){
//get values from element clicked, or assume its passed as an option
settings.windowSourceID = $(passingThis).attr('href') || settings.windowSourceID;
settings.windowSourceURL = $(passingThis).attr(settings.windowSourceAttrURL) || settings.windowSourceURL;
settings.windowBGImage = settings.windowBGImage ? 'background-image:url('+settings.windowBGImage+')' : '';
var urlOnly, urlQueryObject;
if(settings.positionType == 'anchored'){//anchored DOM window
var anchoredPositions = $(settings.anchoredSelector).position();
var anchoredPositionX = anchoredPositions.left + settings.positionLeft;
var anchoredPositionY = anchoredPositions.top + settings.positionTop;
$('body').append('<div class="'+settings.anchoredClassName+'" style="'+settings.windowBGImage+';background-repeat:no-repeat;padding:'+settings.windowPadding+'px;overflow:auto;position:absolute;top:'+anchoredPositionY+'px;left:'+anchoredPositionX+'px;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+';z-index:10001"><div id="DOMWindowContent" style="display:none"></div></div>');
//loader
if(settings.loader && settings.loaderImagePath !== ''){
$('.'+settings.anchoredClassName).append('<div id="DOMWindowLoader" style="width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
}
if($.fn.draggable){
if(settings.draggable){$('.' + settings.anchoredClassName).draggable({cursor:'move'});}
}
switch(settings.windowSource){
case 'inline'://////////////////////////////// inline //////////////////////////////////////////
$('.' + settings.anchoredClassName+" #DOMWindowContent").append($(settings.windowSourceID).children());
$('.' + settings.anchoredClassName).unload(function(){// move elements back when you're finished
$('.' + settings.windowSourceID).append( $('.' + settings.anchoredClassName+" #DOMWindowContent").children());
});
showDOMWindow(settings.anchoredClassName);
break;
case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
$('.' + settings.anchoredClassName+" #DOMWindowContent").append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:100%;border:none;background-color:#fff;" class="'+settings.anchoredClassName+'Iframe" ></iframe>');
$('.'+settings.anchoredClassName+'Iframe').load(showDOMWindow(settings.anchoredClassName));
break;
case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////
if(settings.windowHTTPType == 'post'){
if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
urlQueryObject = urlQueryToObject(settings.windowSourceURL);
}else{
urlOnly = settings.windowSourceURL;
urlQueryObject = {};
}
$('.' + settings.anchoredClassName+" #DOMWindowContent").load(urlOnly,urlQueryObject,function(){
showDOMWindow(settings.anchoredClassName);
});
}else{
if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
settings.windowSourceURL += '?';
}
$('.' + settings.anchoredClassName+" #DOMWindowContent").load(
settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
showDOMWindow(settings.anchoredClassName);
});
}
break;
}
}else{//centered, fixed, absolute DOM window
//overlay & modal
if(settings.overlay){
$('body').append('<div id="DOMWindowOverlay" style="z-index:10000;display:none;position:absolute;top:0;left:0;background-color:'+settings.overlayColor+';filter:alpha(opacity='+settings.overlayOpacity+');-moz-opacity: 0.'+settings.overlayOpacity+';opacity: 0.'+settings.overlayOpacity+';"></div>');
if(shortcut.isIE6){//if IE 6
$('body').append('<iframe id="DOMWindowIE6FixIframe" src="blank.html" style="width:100%;height:100%;z-index:9999;position:absolute;top:0;left:0;filter:alpha(opacity=0);"></iframe>');
sizeIE6Iframe();
}
sizeOverlay();
var $DOMWindowOverlay = $('#DOMWindowOverlay');
$DOMWindowOverlay.fadeIn('fast');
if(!settings.modal){$DOMWindowOverlay.click(function(){$.closeDOMWindow();});}
}
//loader
if(settings.loader && settings.loaderImagePath !== ''){
$('body').append('<div id="DOMWindowLoader" style="z-index:10002;width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
centerLoader();
}
//add DOMwindow
$('body').append('<div id="DOMWindow" style="background-repeat:no-repeat;'+settings.windowBGImage+';overflow:auto;padding:'+settings.windowPadding+'px;display:none;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+'; position:absolute;z-index:10001"></div>');
var $DOMWindow = $('#DOMWindow');
//centered, absolute, or fixed
switch(settings.positionType){
case 'centered':
centerDOMWindow();
if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
$DOMWindow.css('top', (settings.fixedWindowY + shortcut.scrollOffsetHeight()) + 'px');
}
break;
case 'absolute':
$DOMWindow.css({'top':(settings.positionTop+shortcut.scrollOffsetHeight())+'px','left':(settings.positionLeft+shortcut.scrollOffsetWidth())+'px'});
if($.fn.draggable){
if(settings.draggable){$DOMWindow.draggable({cursor:'move'});}
}
break;
case 'fixed':
fixedDOMWindow();
break;
case 'anchoredSingleWindow':
var anchoredPositions = $(settings.anchoredSelector).position();
var anchoredPositionX = anchoredPositions.left + settings.positionLeft;
var anchoredPositionY = anchoredPositions.top + settings.positionTop;
$DOMWindow.css({'top':anchoredPositionY + 'px','left':anchoredPositionX+'px'});
break;
}
$(window).bind('scroll.DOMWindow',function(){
if(settings.overlay){sizeOverlay();}
if(shortcut.isIE6){sizeIE6Iframe();}
if(settings.positionType == 'centered'){centerDOMWindow();}
if(settings.positionType == 'fixed'){fixedDOMWindow();}
});
$(window).bind('resize.DOMWindow',function(){
if(shortcut.isIE6){sizeIE6Iframe();}
if(settings.overlay){sizeOverlay();}
if(settings.positionType == 'centered'){centerDOMWindow();}
});
switch(settings.windowSource){
case 'inline'://////////////////////////////// inline //////////////////////////////////////////
$DOMWindow.append($(settings.windowSourceID).children());
$DOMWindow.unload(function(){// move elements back when you're finished
$(settings.windowSourceID).append($DOMWindow.children());
});
showDOMWindow();
break;
case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
$DOMWindow.append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:100%;border:none;background-color:#fff;" id="DOMWindowIframe" ></iframe>');
$('#DOMWindowIframe').load(showDOMWindow());
break;
case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////
if(settings.windowHTTPType == 'post'){
if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
urlQueryObject = urlQueryToObject(settings.windowSourceURL);
}else{
urlOnly = settings.windowSourceURL;
urlQueryObject = {};
}
$DOMWindow.load(urlOnly,urlQueryObject,function(){
showDOMWindow();
});
}else{
if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
settings.windowSourceURL += '?';
}
$DOMWindow.load(
settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
showDOMWindow();
});
}
break;
}
}//end if anchored, or absolute, fixed, centered
};//end run()
if(settings.eventType){//if used with $().
return this.each(function(index){
$(this).bind(settings.eventType,function(){
run(this);
return false;
});
});
}else{//else called as $.function
run();
}
};//end function openDOMWindow
//allow for public call, pass settings
$.openDOMWindow = function(s){$.fn.openDOMWindow(s);};
})(jQuery);
Any help/ideas would be greatly appresiated.
Thanks,
#rrfive
Hi Reason that your modal closes is that when you click submit your running your backend code, this being PHP and with your PHP you are redirecting the user if the result is negative, you need to capture the response from your PHP rather than having your PHP do a redirect.
What you can do is make your submit an ajax submit and set the data response to json, then you can write a json response that your jquery can understand, this way all the validation will be done on the backend in the background without needed to redirect.