I want to create a javascript for checking value of textbox so if the textbox blank, it won't proceed to next page. AND after checking (if all condition is true) it will return the result of textbox.
I've created this javascript:
function cekdata(myform)
{
var id = document.myform.clientid.value;
var nama = document.myform.nama.value;
var divisi = document.myform.divisi.value;
var way = document.getElementById('twoway').value;
var ori = document.myform.lokasi.value;
var desti = document.myform.tujuan.value;
var ket = document.myform.keterangan.value;
var tpergi = document.myform.tglb.value;
var jpergi = document.myform.jamb.value;
var mpergi = document.myform.menitb.value;
var pegi = tpergi+', '+jpergi+':'+mpergi;
var tplg = document.myform.tglp.value;
var jplg = document.myform.jamp.value;
var mplg = document.myform.menitp.value;
var plg = tplg+', '+jplg+':'+mplg;
if (document.myform.clientid.value == "")
{
alert("Please Fill Your ID");
myform.clientid.focus();
return false;
}
else
if (document.myform.nama.value == "")
{
alert("Please Fill Passenger Name");
myform.nama.focus();
return false;
}
else
if (document.myform.lokasi.value == "")
{
alert("Please Fill Origin Location");
myform.lokasi.focus();
return false;
}
else
if (document.myform.tujuan.value == "")
{
alert("Please Fill Your Destination");
myform.tujuan.focus();
return false;
}
else
if (document.myform.tglb.value == "")
{
alert("Please Fill Departure Date");
myform.tglb.focus();
return false;
}
else
if (document.myform.novehicle.value == "")
{
alert("Please Fill Vehicle Number");
myform.novehicle.focus();
return false;
}
else
if (document.myform.driverid.value == "")
{
alert("Please Fill Driver ID");
myform.driverid.focus();
return false;
}
else
if(document.getElementById('twoway').checked)
{
if (document.myform.tglp.value == "")
{
alert("Please Fill Return Date");
myform.tglp.focus();
return false;
}
else
if (document.myform.tglb.value > document.myform.tglp.value)
{
alert("Return date must bigger than departure date");
myform.tglp.focus();
return false;
}
}
else
{
var a = window.confirm("CONFIRMATION :\nID : " +id+"\nName : "+nama+"\nDivision : "+divisi+"\nOne Way : "+way+"\nOrigin : "+ori+"\nDestination : "+desti+"\nNotes : "+ket+"\nDeparture : "+pegi+"\nArrived :"+plg);
if (a==true)
{
return true;
}
else
{
return false;
}
}
}
And I called this function like this:
<form name="myform" onsubmit="return cekdata(this);" method="POST" action="<?php $_SERVER["PHP_SELF"]; ?>">
But what I got is the confirm box never show up, and it returns true (and go to next page). So, how to change this condition so my confirmation box showed up first, then after click OK, it go to next page, and if CANCEL, do nothing?
*Just make slight changes in your javascript just passevent on form submit*
<input type="submit" value="Submit" name="submit" onClick="return cekdata(this,event);" />
and when your textbox is empty or null write event.preventDefault() instead of return false;
function cekdata(myform,evt)
{
var id = document.myform.clientid.value;
var nama = document.myform.nama.value;
var divisi = document.myform.divisi.value;
var way = document.getElementById('twoway').value;
var ori = document.myform.lokasi.value;
var desti = document.myform.tujuan.value;
var ket = document.myform.keterangan.value;
var tpergi = document.myform.tglb.value;
var jpergi = document.myform.jamb.value;
var mpergi = document.myform.menitb.value;
var pegi = tpergi+', '+jpergi+':'+mpergi;
var tplg = document.myform.tglp.value;
var jplg = document.myform.jamp.value;
var mplg = document.myform.menitp.value;
var plg = tplg+', '+jplg+':'+mplg;
if (document.myform.clientid.value == "")
{
alert("Please Fill Your ID");
myform.clientid.focus();
evt.preventDefault();
}
Try this:
Remove your last else part and paste below lines at the end of your javascript function.
Remove below lines :
var a = window.confirm("CONFIRMATION :\nID : " +id+"\nName : "+nama+"\nDivision : "+divisi+"\nOne Way : "+way+"\nOrigin : "+ori+"\nDestination : "+desti+"\nNotes : "+ket+"\nDeparture : "+pegi+"\nArrived :"+plg);
instead use this,
var a = window.confirm("Are you sure?");
if (a==true)
{
return true;
}
else
{
return false;
}
I would better suggest you to place that cekdata(this) in your submit tag rather than form tag. Like
<input type="submit" value="Submit" name="submit" onClick="return cekdata();" />
And also when you have done this
var id = document.myform.clientid.value;
Then why you are using again the same
if (document.myform.clientid.value == "")
Better use
var id = document.myform.clientid;
if (id.value == "")
{
alert("Please Fill Your ID");
id.focus();
return false;
}
Changing code like this:
function cekdata(myform)
{
var id = document.myform.clientid.value;
var nama = document.myform.nama.value;
var divisi = document.myform.divisi.value;
var way = document.getElementById('twoway').value;
var ori = document.myform.lokasi.value;
var desti = document.myform.tujuan.value;
var ket = document.myform.keterangan.value;
var tpergi = document.myform.tglb.value;
var jpergi = document.myform.jamb.value;
var mpergi = document.myform.menitb.value;
var pegi = tpergi+', '+jpergi+':'+mpergi;
var tplg = document.myform.tglp.value;
var jplg = document.myform.jamp.value;
var mplg = document.myform.menitp.value;
var plg = tplg+', '+jplg+':'+mplg;
if (id == "")
{
alert("Please Fill Your ID");
myform.clientid.focus();
return false;
}
else
if (nama == "")
{
alert("Please Fill Passenger Name");
myform.nama.focus();
return false;
}
else
if (ori == "")
{
alert("Please Fill Origin Location");
myform.lokasi.focus();
return false;
}
else
if (desti == "")
{
alert("Please Fill Your Destination");
myform.tujuan.focus();
return false;
}
else
if (tpergi == "")
{
alert("Please Fill Departure Date");
myform.tglb.focus();
return false;
}
else
if(document.getElementById('twoway').checked)
{
if (tplg == "")
{
alert("Please Fill Return Date");
myform.tglp.focus();
return false;
}
else
if (tpergi > tplg)
{
alert("Return date must bigger than departure date");
myform.tglp.focus();
return false;
}
}
else
{
var a = window.confirm("CONFIRMATION :\nID : " +id+"\nName : "+nama+"\nDivision : "+divisi+"\nOne Way : "+way+"\nOrigin : "+ori+"\nDestination : "+desti+"\nNotes : "+ket+"\nDeparture : "+pegi+"\nArrived :"+plg);
if (a==true)
{
return true;
}
else
{
return false;
}
}
}
then it works...
I would recommend using Jquery insead of Javascript.
Here is the short & sweet code I have made just for you, feel free to use it!
JQUERY CODE
$(document).ready(function() {
$('#submit').click(function(){
var id = $('#id').val();
var dataString = 'id='+ id;
if(id==''){
alert("Please Fill Your ID");
$('#id').focus();
return false;
}
else if(confirm("Are you sure? Your id = "+id))
{
$.ajax({
type: "POST",
url: "ajxRegistration.php",
data: dataString,
cache: false,
success: function(e)
{
e.stopImmediatePropagation();
}
});
return false;
}
});
})
Try this -
if(confirm('Are you sure?'))
return true;
else
return false;
Related
I have a HTML form that when posted fires an JQuery script to check a validation function before sending data to an ajax call to insert the data into a mySQL database.
It works as it should, except when it is running an ajax check to see if the posted email address already exists in the database.
I need the email_error var to return true if the response from the ajax call is not 'success'. My code:
function validate_add_relative() {
var check_error = false;
var email_error = false;
var title = document.forms["add_relative_form"]["title"].value;
if (title == null || title == "") {
check_error = true;
}
var first_name = document.forms["add_relative_form"]["first_name"].value;
if (first_name == null || first_name == "") {
check_error = true;
}
var surname = document.forms["add_relative_form"]["surname"].value;
if (surname == null || surname == "") {
check_error = true;
}
var phone = document.forms["add_relative_form"]["phone"].value;
if (phone == null || phone == "") {
check_error = true;
}
var email = document.forms["add_relative_form"]["email"].value;
if (email == null || email == "") {
check_error = true;
}
var address = document.forms["add_relative_form"]["address"].value;
if (address == null || address == "") {
check_error = true;
}
var postData = $(this).serializeArray();
$.ajax(
{
url : '<?php echo WEB_URL . 'controllers/ajax/check_relative_email.php'; ?>',
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR) {
if(data == 'success') {
email_error = false;
return true;
}
else {
alert('test');
email_error = true;
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Email is already in use. Please choose another.');
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Error. Please try again later.');
email_error = true;
}
});
if (email_error == true) {
alert("Please choose another email address, that one is already in use.");
return false;
}
if (check_error == true) {
alert("Please ensure you fill in all mandatory fields.");
return false;
}
if (email_error == false && check_error == false) {
return true;
}
}
$('.add_relative_form').submit(function(e) {
e.preventDefault();
if(validate_add_relative()) {
var ajaxurl = '<?php echo WEB_URL; ?>controllers/ajax/add_relative.php',
form_data = $('.add_relative_form').serialize();
$.post(ajaxurl, form_data, function (response) {
//location.reload();
});
}
});
When running the above code, the first part (Form validation) works as it should, and it also gives the alert and does the class hiding after. But it carries on and is not catching the fact that email_error is set to true after the alert line. So it continues through the code and adds the entry through the last ajax post controllers/ajax/add_relative.php
add complete function after error and write your code inside that function
complete:function(data, textStatus, jqXHR) {
if(data == 'success') {
email_error = false;
return true;
}
else {
alert('test');
email_error = true;
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Email is already in use. Please choose another.');
}
},
JavaScript is asynchronous in the sense that it can make, for example, Ajax calls. Hence your outer conditions will get mislead. Try to add return statement inside AJAX response for expected result.
Please try following solution
function validate_add_relative() {
var check_error = false;
var email_error = false;
var title = document.forms["add_relative_form"]["title"].value;
if (title == null || title == "") {
check_error = true;
}
var first_name = document.forms["add_relative_form"]["first_name"].value;
if (first_name == null || first_name == "") {
check_error = true;
}
var surname = document.forms["add_relative_form"]["surname"].value;
if (surname == null || surname == "") {
check_error = true;
}
var phone = document.forms["add_relative_form"]["phone"].value;
if (phone == null || phone == "") {
check_error = true;
}
var email = document.forms["add_relative_form"]["email"].value;
if (email == null || email == "") {
check_error = true;
}
var address = document.forms["add_relative_form"]["address"].value;
if (address == null || address == "") {
check_error = true;
}
if(check_error===false){
var postData = $(this).serializeArray();
$.ajax(
{
url : '<?php echo WEB_URL . 'controllers/ajax/check_relative_email.php'; ?>',
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR) {
if(data == 'success') {
return true;
}
else {
alert('test');
return false;
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Email is already in use. Please choose another.');
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Error. Please try again later.');
return false;
}
});
}
else{
return false;
}
}
$('.add_relative_form').submit(function(e) {
e.preventDefault();
if(validate_add_relative()) {
var ajaxurl = '<?php echo WEB_URL; ?>controllers/ajax/add_relative.php',
form_data = $('.add_relative_form').serialize();
$.post(ajaxurl, form_data, function (response) {
//location.reload();
});
}
});
UPDATES
change following code :
if(data == 'success') {
return true;
}
else {
alert('test');
return false;
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Email is already in use. Please choose another.');
}
To
if(data == 'success') {
return true;
}
else {
alert('test');
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Email is already in use. Please choose another.');
return false;
}
You can check, if the email already exists by using .blur() as soon after the user enters their email, you send AJAX call to check if the email exists and disable the submit button and show proper message to the user.
Form
<form action="" name="add_relative_form" class="add_relative_form">
<input type="text" name="title">
<input type="text" name="first_name">
<input type="text" name="surname">
<input type="text" name="phone">
<input type="text" id="email" name="email"> <!-- give email an id -->
<input type="text" name="address">
<input type="submit" id="sub" value="Sub"> <!-- give submit an id -->
Javascript
function validate_add_relative() {
var check_error = false;
var email_error = false;
var title = document.forms["add_relative_form"]["title"].value;
if (title == null || title == "") {
check_error = true;
}
var first_name = document.forms["add_relative_form"]["first_name"].value;
if (first_name == null || first_name == "") {
check_error = true;
}
var surname = document.forms["add_relative_form"]["surname"].value;
if (surname == null || surname == "") {
check_error = true;
}
var phone = document.forms["add_relative_form"]["phone"].value;
if (phone == null || phone == "") {
check_error = true;
}
var email = document.forms["add_relative_form"]["email"].value;
if (email == null || email == "") {
check_error = true;
}
var address = document.forms["add_relative_form"]["address"].value;
if (address == null || address == "") {
check_error = true;
}
if (email_error == true) {
alert("Please choose another email address, that one is already in use.");
return false;
}
if (check_error == true) {
alert("Please ensure you fill in all mandatory fields.");
return false;
}
if (email_error == false && check_error == false) {
return true;
}
}
$('.add_relative_form').submit(function (e) {
e.preventDefault();
if (validate_add_relative()) {
var ajaxurl = '<?php echo WEB_URL; ?>controllers/ajax/add_relative.php',
form_data = $('.add_relative_form').serialize();
$.post(ajaxurl, form_data, function (response) {
//location.reload();
console.log(response)
});
}
});
$('#email').on('blur', function () {
$.ajax({
url: '<?php echo WEB_URL . 'controllers/ajax/check_relative_email.php'; ?>',
type: "POST",
data: {email: $(this).val()},
success: function (data, textStatus, jqXHR) {
if (data == 'success') {
$('#sub').prop('disabled', false);
}
else {
$('.relative_email_error').show();
$('.relative_email_error').html('Email is already in use. Please choose another.');
$('#sub').prop('disabled', true);
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('.relative_email_error').removeClass('hidden');
$('.relative_email_error').html('Error. Please try again later.');
}
});
})
Then in your PHP get the email from post
<?php
$email = $_POST['email'];
// your SQL code here
How can i push variable to ajax function in php file (witch refers to ajax )
if i have $v in my php . if all is ok it's echo "ok" in php file .So what should i do next
if ($_POST){
for ($j=0; $j< count($row);$j++){
mysql_query("INSERT INTO `".PREFIX_USR."delivery_address` (`id_personl_data`,`country`,`province`,`city`,`street`,`house`,`apartment`)
VALUES ( '12','".$row[$j][0]."','".$row[$j][1]."','".$row[$j][2]."','".$row[$j][3]."','".$row[$j][4]."','".$row[$j][5]."') ");
var count = query['id']; // just an example of what i need to push
}
echo "ok";
}
js
(function(){
function changeData(){
var name = d.getElementById('new_name').value,
surname = d.getElementById('new_surname').value,
email = d.getElementById('new_email').value,
telephone = d.getElementById('new_phone').value,
robot = d.getElementById('spam_change').value,
xml = eventsObj.getXmlHttp();
var arr = [].map.call(document.querySelectorAll('.parent_clone'), function(block) {
return [].map.call(block.querySelectorAll('.left_info_address'), function(inp) {
return inp.value;
});
});
for (var i = 0; i<arr.length-1;i++){
arr[i].push('/');
}
console.log(arr);
if(name === "" || surname === "" || email === "" || (telephone === "")){
alert("fill the fields");
}
else {
xml.open("POST",path_ajax_files+"edit_personal_data.php",true);
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("name="+encodeURIComponent(name)+
"&surname="+encodeURIComponent(surname)+
"&email="+encodeURIComponent(email)+
"&telephone="+encodeURIComponent(telephone)+
"&robot="+encodeURIComponent(robot)+
"&arr="+encodeURI(arr));
xml.onreadystatechange = function(){
if(xml.readyState === 4){
if(xml.status === 200){
if(xml.responseText !== ""){
alert(xml.responseText);
if(xml.responseText === "ok"){
alert("data will be changed");
}
} else {
alert('try again later');
}
}
}
};
}
}
eventsObj.addEvent(saveData, "click", changeData, false);
})();
I wrote a javascript function that checks if a username is available in a database. If the username is NOT available the ajax send a text response back which changes some css and adds an error message. When the username is available the ajax doesn't send a response, which is fine but I just need to know what is being returned from ajax.responseText since there is no value. I've tried '' and null.
function _(x) {
return document.getElementById(x);
}
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
function verifyEmail(){
var email = _("email").value;
var status = _("estatus");
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.signupform.email.value.search(emailRegEx) == -1) {
_("emaildiv").style.border = "1px solid #d33e3e";
_("emaildiv").style.backgroundColor = "#fadede";
status.innerHTML = "<br />Please enter a valid email address";
} else {
_("emaildiv").style.border = "";
_("emaildiv").style.backgroundColor = "";
status.innerHTML = "";
if (email != "") {
status.innerHTML = "checking. . . ";
var ajax = ajaxObj("POST", "fan_signup_local.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
status.innerHTML = ajax.responseText;
console.log(status.innerHTML);
if (status.innerHTML !== '') {
_("emaildiv").style.border = "1px solid #d33e3e";
_("emaildiv").style.backgroundColor = "#fadede";
console.log(ajax.responseText);
} else {
_("emaildiv").style.border = "";
_("emaildiv").style.backgroundColor = "";
}
}
}
ajax.send("email="+email);
}
}
}
There's always a response, unless the request times out. If the server script exits without printing anything, the response will be an empty string.
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 am trying to use fancybox iframe to call a PHP program for payment processing from a javascript program as part of a landing page. The page also calls another PHP program that writes date to a file. I tried to simulate a click to start the fancybox function but never got it to work. I keep getting this error - $("a.hiddenclicker").fancybox is not a function. I'm not sure whether to attempt to just add this logic to the PHP file or figure out how to get fancybox to work. Here is my page. The call to fancybox is in ProcessForm().
function WriteData(url) {
var j1 = document.getElementById("hiddenclicker");
var Request2 = false;
if (window.XMLHttpRequest) {
Request2 = new XMLHttpRequest();
} else if (window.ActiveXObject) {
Request2 = new ActiveXObject("Microsoft.XMLHTTP");
}
if (Request2) {
Request2.open("GET", url, true);
Request2.onreadystatechange = function() {
if (Request2.readyState == 4 && Request2.status == 200) {
}
}
Request2.send(null);
}
}
function ProcessForm(form) {
var j1 = document.getElementById("hiddenclicker");
var firstname = "";
var lastname = "";
var payment = "";
var email = "";
var phone = "";
var donation = "";
firstname = form.firstname.value;
lastname = form.lastname.value;
email = form.email.value;
phone = form.phone.value;
donation = form.donation.value;
if (firstname == "") {
alert("You must fill in the first name");
form.firstname.focus();
return false;
}
else {
if (lastname == "") {
alert("You must fill in last name");
form.lastname.focus();
return false;
}
else {
if (email == "") {
alert("You must fill in email address");
form.email.focus();
return false; }
}
}
WriteData("writedata.php?firstname=" + firstname + "&lastname=" + lastname + "&email=" + email + "&phone=" + phone + "&donation=" + donation);
if (donation == "now") {
jQuery(document).ready(function(){
$("a.hiddenclicker").fancybox(
{
'width' : 600,
'height' : 400,
'hideOnContentClick' : false,
'type' : 'iframe'
});
});
j1.href = "http://www.ccyakids.org/donation_logic/donation_start.php#form";
$('#hiddenclicker').trigger('click');
}
}
// End hiding JavaScript statements -->
HTML needed to trigger hiddenclicker
Hidden Clicker
After looking at your code you reference your link 2 different ways:
$("a.hiddenclicker") // class
$('#hiddenclicker') // ID
Which is it? Make them both the same and i am sure your problem goes away.
Hope this helps