I am using this code for validating the form input fields using ajax and jquery.... On this page : http://www.kbay.in/ajaxform/index.php
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var phone = $('input[name=phone]');
var package_name = $('input[name=package_name]');
var comment = $('input[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (phone.val()=='') {
phone.addClass('hightlight');
return false;
} else phone.removeClass('hightlight');
if (package_name.val()=='') {
package_name.addClass('hightlight');
return false;
} else package_name.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&phone=' + phone.val() + '&package_name=' +
package_name.val() + '&comment=' + encodeURIComponent(comment.val());
But i have add a check box but dont know how to validate it using this script...any ideas....?
You could use is(":checked"):
var commentChecked = $("input[name='comment']").is(':checked'); //returns true or false
var commentVal; //define variable for storing comment value
and
if (!commentChecked) {
commentVal = "";
comment.addClass('hightlight');
return false;
} else {
comment.removeClass('hightlight');
commentVal = comment.val();;
}
And
var data = 'name=' + name.val() + '&phone=' + phone.val() + '&package_name=' +
package_name.val() + '&comment=' + encodeURIComponent(commentVal);
Add a checkbox to your HTML... something like this:
<input type="checkbox" id="ch1">
and your jQuery code to check whether it's checked or not should be like the following:
if ($("#ch1").prop("checked")) {
alert("is checked");
}
else {
alert("is not checked");
}
Related
I have a website, and all its files (html/js/css/php) are on the same remote host. I have a button on the site, when clicked it sends a httprequest to a PHP file, waiting for a response.
My site works perfect almost everywhere, but there is one place which when I connect to the wi-fi, when clicking the button it return whit the error ERR_EMPTY_RESPONSE. Other buttons and PHP files work. It is only this specific button and in this specific wi-fi.
Does anyone know why does it happen and how to fix it?
details:
the button is <button class="btn btn-default col-sm-5" type="submit">
the onClick function:
function search() {
var param = "";
var firstParam = true;
var form = document.getElementById("formCS");
var name = document.getElementById("songName").value.trim();
if (name != "") {
firstParam = false;
param += "name=" + name;
}
var creator = document.getElementById("creator").value.trim();
if (creator != "") {
if (firstParam) {
param += "creator=" + creator;
firstParam = false;
} else {
param += "&creator=" + creator;
}
}
var type;
if (document.getElementById("partners").checked) {
type = "partners";
} else if (document.getElementById("circle").checked) {
type = "circle";
} else if (document.getElementById("lines").checked) {
type = "lines";
} else if (document.getElementById("none").checked) {
type = "";
}
if (type != "") {
if (firstParam) {
param += "type=" + type;
firstParam = false;
} else {
param += "&type=" + type;
}
}
var year = document.getElementById("year").value;
if (year != "none") {
if (firstParam) {
param += "year=" + year;
} else {
param += "&year=" + year;
}
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
handleResponse(xhttp.response);
}
};
xhttp.open("GET", "search.php?" + param, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
the search.php file connects to a DB on the remote host and runs a sql query. nothing different from other buttons on the site.
the wi-fi is a free wi-fi provided by an academic institue.
after clicking the button there is an error in the console:
GET http://rikudim.info/search.php? net::ERR_EMPTY_REPONSE
I am creating a form where the user selects check boxes of "services" that they might be interested in, then the form gets emailed to me. The problem is weather a box is checked or not, all of the results are being filled in. How do I properly do this?
There are about 25, but here is just a few:
$services = array();
if($_POST['master_planning']) {$services[] = "Master planning";}
if($_POST['snow_plowing']) {$services[] = "Snow plowing";}
if($_POST['fine_gardening']) {$services[] = "Fine Gardening";}
if($_POST['deer_protection']) {$services[] = "Deer Protection";}
$interested = implode(", ", $services);
I know it is a very basic thing, but I can't seem to solve it on my own
HTML is like:
<li><label for="planting"><input type="checkbox" name="planting" id="planting" value="x" /> Planting</label></li>
Ok, I figured (I think) out why all the values are returning true, even if the checkboxes arent clicked, now how do I solve it....
I guess I should of mentioned that this is page 2 of the form (process.php), the actual form is index.php, and I am using an ajax script to pass values.
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var name = $('input[name=name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var master_plan = $('input[name=master_plan]');
var front_foundation = $('input[name=front_foundation]');
var backyard_plan = $('input[name=backyard_plan]');
var specialty_garden = $('input[name=specialty_garden]');
var lawn_cutting = $('input[name=lawn_cutting]');
var lawn_plant_health_care = $('input[name=lawn_plant_health_care]');
var organic_property_care = $('input[name=organic_property_care]');
var seasonal_clean_ups = $('input[name=seasonal_clean_ups]');
var pruning = $('input[name=pruning]');
var fine_gardening = $('input[name=fine_gardening]');
var deer_protection = $('input[name=deer_protection]');
var snow_plowing = $('input[name=snow_plowing]');
var planting = $('input[name=planting]');
var walk = $('input[name=walk]');
var terrace = $('input[name=terrace]');
var wall = $('input[name=wall]');
var outdoor_kitchen = $('input[name=outdoor_kitchen]');
var fireplace = $('input[name=fireplace]');
var driveway = $('input[name=driveway]');
var fencing = $('input[name=fencing]');
var pergola = $('input[name=pergola]');
var swimming_pool = $('input[name=swimming_pool]');
var irrigation = $('input[name=irrigation]');
var lighting = $('input[name=lighting]');
var grading_drainage = $('input[name=grading_drainage]');
var newsletter = $('input[name=newsletter]');
var comments = $('textarea[name=comments]');
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
var data =
'name=' + name.val() +
'&phone=' + phone.val() +
'&email=' + email.val() +
'&master_plan=' + master_plan.val()+
'&front_foundation=' + front_foundation.val()+
'&backyard_plan=' + backyard_plan.val()+
'&specialty_garden=' + specialty_garden.val()+
'&lawn_cutting=' + lawn_cutting.val()+
'&lawn_plant_health_care=' + lawn_plant_health_care.val()+
'&organic_property_care=' + organic_property_care.val()+
'&seasional_clean_ups=' + seasional_clean_ups.val()+
'&pruning=' + pruning.val()+
'&fine_gardening=' + fine_gardening.val()+
'&deer_protection=' + deer_protection.val()+
'&snow_plowing=' + snow_plowing.val()+
'&planting=' + planting.val()+
'&walk=' + walk.val()+
'&terrace=' + terrace.val()+
'&wall=' + wall.val()+
'&outdoor_kitchen=' + outdoor_kitchen.val()+
'&fireplace=' + fireplace.val()+
'&driveway=' + driveway.val()+
'&fencing=' + fencing.val()+
'&pergola=' + pergola.val()+
'&swimming_pool=' + swimming_pool.val()+
'&irrigation=' + irrigation.val()+
'&lighting=' + lighting.val()+
'&grading_drainage=' + grading_drainage.val()+
'&newsletter=' + newsletter.val() +
'&comments=' + encodeURIComponent(comments.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
if (html==1) {
$('.form').fadeOut('slow');
$('.done').fadeIn('slow');
} else alert('Sorry, unexpected error. Please try again later.');
}
});
return false;
});
});
</script>
Could this be why every result is displaying?
The check you have is incorrect. Lets assume you have this HTML code for the checkbox inside your form:
<input type="checkbox" name="master_planning" value="yes" />
Then on your PHP you want do the check like this:
if(isset($_POST['master_planning']) && $_POST['master_planning'] == 'yes'){
array_push($services, "Master planning"];
}
The function array_push adds the given element or elements at the end of the array, so that would be an easy way to "dynamically" populates an array.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JQuery validate e-mail address regex
hi i have an input filed in a form referencing to an email input field , and when the user clicked the submit button i want to ensure that the email input field value has the formal like this
example#hotmail.com
or
example#gmail.com
or
example#yahoo.com
and the input field is this
<p>
<label>Email</label>
<input type="text" name="Email"/>
<span class="errorMessage"></span>
</p>
jquery code
$(document).ready(function(){
$('#suform').on('submit', function(e){
e.preventDefault();
var errorCount = 0;
$('span.errorMessage').text(''); // reset all error mesaage
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text(); // take the input field from label
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
if(errorCount === 0){
var mobileNumber = $('input[name=MNumber]');
var email = $('input[name=Email]');
if(isNaN(parseFloat(mobileNumber )) && !isFinite(mobileNumber )) {
var error = 'Mobile number incorect.';
$('input[name=MNumber]').next('span').text(error);
errorCount = errorCount + 1;
}else{
var password= $('input[name="Password"]').val();
var repass= $('input[name="RePassword"]').val();
if(password!=repass){ // ensrue the two passwords are the same
var error2 = 'Password not matching';
$('input[name="RePassword"]').next('span').text(error2)
errorCount = errorCount + 1;
}else{
$(this)[0].submit(); // submit form if no error
}
}
}
});
});
my html , css and jquery code is here
code
If I understand you correctly, you want to validate the email address filled on the form:
ADD TO YOUR FUNCTION
// validate proper email address
var reg = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
if (reg.test(value) == false) {
// email invalid, do stuff
} else {
// email valid, do stuff
}
This Regular expression checks the email provided for many many many issues!
EDITED:
You're function had some typos, here it is fully functional: and a working Fiddle!
$(document).ready(function(){
// form submit
$('#suform').on('submit', function(e){
// prevent default behavior
e.preventDefault();
// reset errors counter
var errorCount = 0;
// clear error message
$('span.errorMessage').text('');
// run by each input field to check if they are filled
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
// take the input field from label
var error = 'Please fill ' + $this.prev('label').text();
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
// no errors so far, let continue and validate the contents
if(errorCount === 0){
// get mobile number
var mobileNumber = $('input[name=MNumber]').val();
// get email address
var email = $('input[name=Email]').val();
// get password and password repeat
var password= $('input[name="Password"]').val();
var repass= $('input[name="RePassword"]').val();
// regular expression to validate the email address
var reg = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
// try to validate the email
if (reg.test(email) == false) {
$('input[name=Email]').next('span').text('Email address is invalid!');
errorCount = errorCount + 1;
} else {
if(isNaN(parseFloat(mobileNumber )) && !isFinite(mobileNumber )) {
var error = 'Mobile number incorect.';
$('input[name=MNumber]').next('span').text(error);
errorCount = errorCount + 1;
} else {
// ensrue the two passwords are the same
if(password!=repass){
var error2 = 'Password not matching';
$('input[name="RePassword"]').next('span').text(error2);
errorCount = errorCount + 1;
}else{
$(this)[0].submit(); // submit form if no error
}
}
}
}
});
});
Regular expression is one way to validate :
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\
".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
Pass a user entered email to this function it will check its formate and return true or false accordingly
You can use this function:
function validateEmail(email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test( email ) ) {
return false;
} else {
return true;
}
}
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.
I would like to make a bus seating plan. I have seating plan chart using javascript function.I have two radio button named Bus_1 and Bus_2 queried from databases. When I clicked one of radio button, I would like to get available seats to show on the seating plan. Problem is I can't write how to carry radio value and to show database result on seating plan. Please help me.
<SCRIPT type="text/javascript">
$(function () {
var settings = { rowCssPrefix: 'row-', colCssPrefix: 'col-', seatWidth: 35, seatHeight: 35, seatCss: 'seat', selectedSeatCss: 'selectedSeat', selectingSeatCss: 'selectingSeat' };
var init = function (reservedSeat) {
var str = [], seatNo, className;
var shaSeat = [1,5,9,13,17,21,25,29,33,37,41,'#',2,6,10,14,18,22,26,30,34,38,42,'#','$','$','$','$','$','$','$','$','$','$',43,'#',3,7,11,15,19,23,27,31,35,39,44,'#',4,8,12,16,20,24,28,32,36,40,45];
var spr=0;
var spc=0;
for (i = 0; i<shaSeat.length; i++) {
if(shaSeat[i]=='#') {
spr++;
spc=0;
}
else if(shaSeat[i]=='$') {
spc++;
}
else {
seatNo = shaSeat[i];
className = settings.seatCss + ' ' + settings.rowCssPrefix + spr.toString() + ' ' + settings.colCssPrefix + spc.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) { className += ' ' + settings.selectedSeatCss; }
str.push('<li class="' + className + '"' +'style="top:' + (spr * settings.seatHeight).toString() + 'px;left:' + (spc * settings.seatWidth).toString() + 'px">' +'<a title="' + seatNo + '">' + seatNo + '</a>' +'</li>');
spc++;
}
}
$('#place').html(str.join(''));
}; //case I: Show from starting //init();
//Case II: If already booked
var bookedSeats = [2,3,4,5]; //**I don't know how to get query result in this array.This is problem for me **
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
// ---- kmh-----
var label = $('#busprice');
var sprice = label.attr('pi');
//---- kmh ----
// var sprice= $("form.ss pri");
if ($(this).hasClass(settings.selectedSeatCss)){ alert('This seat is already reserved'); }
else {
$(this).toggleClass(settings.selectingSeatCss);
//--- sha ---
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
var selSeat = document.getElementById("selectedseat");
selSeat.value = str.join(',');
//var amount = document.getElementById("price");
// amount.value = sprice*str.length;
document.getElementById('price').innerHTML = sprice*str.length;
return true;
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () { // selected seat
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
alert(str.join(','));
})
});
</SCRIPT>
You can use the onclick to tell AJAX to get your information and then what to do with it using jQuery.
<input type="radio" name="radio" onclick="ajaxFunction()" />
function ajaxFunction()
{
$.ajax({
type: "POST",
url: "you_script_page.php",
data: "post_data=posted",
success: function(data) {
//YOUR JQUERY HERE
}
});
}
Data is not needed if you are not passing any variables.
I use jQuery's .load() function to grab in an external php page, with the output from the database on it.
//In your jQuery on the main page (better example below):
$('#divtoloadinto').load('ajax.php?bus=1');
// in the ajax.php page
<?php
if($_GET['bus']==1){
// query database here
$sql = "SELECT * FROM bus_seats WHERE bus = 1";
$qry = mysql_query($sql);
while ($row = mysql_fetch_assoc($qry)) {
// output the results in a div with echo
echo $row['seat_name_field'].'<br />';
// NOTE: .load() takes this HTML and loads it into the other page's div.
}
}
Then, just create a jQuery call like this for each time each radio button is clicked.
$('#radio1').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=1');
}
);
$('#radio2').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=2');
}
);