jQuery AJAX not working on Firefox - php

I have a function and an AJAX call. After clicking it gets the function and function works fine, on alert it shows the data, but after that it does not send the data to PHP. Any ideas why this happens on Firefox? It works well in IE and Chrome.
function siparisolustur() {
var toplamsiparis = $('.urunrow').length;
var i = null;
var siparisid = $("#siparis_id").text();
var name = $("#siparisad").val();
var surname = $("#siparissoyad").val();
var tel = $("#siparistel").val();
var adres = $("#sepetadres").val();
var semt = $("#sepetilce").val();
var sehir = $("#sepetsehir").val();
var notlar = $("#siparisnotu").val();
var odeme = $('input[name="odemeyontemi"]:checked').attr("id");
bilgiDataString = '&siparisid=' + siparisid + '&name=' + name + '&surname=' + surname + '&tel=' + tel + '&adres=' + adres + '&semt=' + semt + '&sehir=' + sehir + '&notlar=' + notlar + '&odeme=' + odeme;
alert(bilgiDataString);
$.ajax({
type: "POST",
url: "https://www.xxxxx.com/procc/xxxxxxxxxx.php",
data: bilgiDataString,
cache: false,
success: function (html) {
}
});
$("#payForm").submit(function (e) {
var siparisdurdur = 0;
var ad = $("#siparisad").val();
var soyad = $("#siparissoyad").val();
var tel = $("#siparistel").val();
var adres = $("#sepetadres").val();
var ilce = $("#sepetilce").val();
var sehir = $("#sepetsehir").val();
var sepeturunadetget = parseInt($("#sepeturunsayisi").text());
if (ad == "" || soyad == "" || tel == "" || adres == "" || ilce == "" || sehir == "" || sepeturunadetget < 1) {
siparisdurdur = 1;
}
if (ad == "") {
e.preventDefault();
$("#siparisad").css("border- color", "#cd2828")
} else {
$("#siparisad").css("border-color", "#d1d2e6");
}
if (soyad == "") {
e.preventDefault();
$("#siparissoyad").css("border-color", "#cd2828")
} else {
$("#siparissoyad").css("border-color", "#d1d2e6");
}
if (tel == "") {
e.preventDefault();
$("#siparistel").css("border-color", "#cd2828")
} else {
$("#siparistel").css("border-color", "#d1d2e6");
}
if (adres == "") {
e.preventDefault();
$("#sepetadres").css("border-color", "#cd2828")
} else {
$("#sepetadres").css("border-color", "#d1d2e6");
}
if (ilce == "") {
e.preventDefault();
$("#sepetilce").css("border-color", "#cd2828")
} else {
$("#sepetilce").css("border-color", "#d1d2e6")
}
if (sehir == "") {
e.preventDefault();
$("#sepetsehir").css("border-color", "#cd2828")
} else {
$("#sepetsehir").css("border-color", "#d1d2e6")
}
if (blocksubmit == 1) {
e.preventDefault();
$("#personalinfosubmit").fadeOut("fast").fadeIn("fast").fadeOut("fast").fadeIn("fast");
}
if (sepeturunadetget < 1) {
e.preventDefault();
$("#shoppingcost").css("color", "#cd2828");
$("#shoppingcost").fadeOut("fast").fadeIn("fast").fadeOut("fast").fadeIn("fast");
}
if (blocksubmit == 0 && siparisdurdur == 0) {
siparisolustur();
}
});

I solved the problem.. Submit goes to other page before ajax is done proessing the data.. I delayed the redirect for like half second and it worked.. Its about speed of FF

I see that you've posted a solution already:
Submit goes to other page before ajax is done proessing the data.. I delayed the redirect for like half second and it worked.
Seriously, you should not be relying on a solution like this.
Timing issues like this are known as a "race condition", ie where two events are effectively in a race to see which one will finish first; you're expecting one to always win, and you get a bug if they finish in the wrong order.
It's a very well defined category of bug (even if Ajax is fairly new, situations like this have existed since the begining of computer science), and the solution is not to slow down one of the events in the hope that you'll force it to always lose. That is always the wrong solution.
The correct solution is usually to trigger the second event only after the first one has finished. In your case, this would mean firing the submit event from inside the ajax success method.

Related

what can be used in place of window.location.replace to avoid page reloading?

I am using product filtering in a site like Flipkart. And I do not want to reload the page after filtering data. This is my jquery code for filtering data. Filter class is used in all the filters. Give some suggestions plz.
$('.filter').click(function() {
var typef = '';
var currentURL = location.protocol + '//' + location.host + location.pathname;
if (window.location.href.indexOf("search") > -1) {
var searchParams = new URLSearchParams(window.location.search);
var aquery = searchParams.get('query');
typef = 'search';
}
var brands = [];
var colors = [];
var price = [];
if ($(this).is(":checked")) {
$("input:checkbox[name=brand_check]:checked").each(function() {
brands.push($(this).val());
});
$("input:checkbox[name=color_check]:checked").each(function() {
colors.push($(this).val());
});
$("input:radio[name=price_check]:checked").each(function() {
price.push($(this).val());
});
var filterdata = {
brands: jQuery.unique(brands),
color: jQuery.unique(colors),
price: jQuery.unique(price)
};
var filteruri = jQuery.param(filterdata);
if (typef == 'search' && typeof aquery !== "undefined" && aquery !== '') {
window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery) + '&f=' + encodeURIComponent(filteruri));
} else {
window.location.replace(currentURL + '?f=' + encodeURIComponent(filteruri));
}
} else {
$('input:checkbox[value="' + $(this).val() + '"]').attr('checked', false);
$("input:checkbox[name=brand_check]:checked").each(function() {
brands.push($(this).val());
});
$("input:checkbox[name=color_check]:checked").each(function() {
colors.push($(this).val());
});
$("input:radio[name=price_check]:checked").each(function() {
price.push($(this).val());
});
var filterdata = {
brands: jQuery.unique(brands),
color: jQuery.unique(colors),
price: jQuery.unique(price)
};
var filteruri = jQuery.param(filterdata);
if (typef == 'search' && typeof aquery !== "undefined" && aquery !== '') {
if (filteruri.length > 0) {
window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery) + '&f=' + encodeURIComponent(filteruri));
} else {
window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery));
}
} else {
if (filteruri.length > 0) {
window.location.replace(currentURL + '?f=' + encodeURIComponent(filteruri));
} else {
window.location.replace(currentURL);
}
}
}
});
If I understood correctly, you want to change url without page reloading.
Read some about manipulating browser history (https://developer.mozilla.org/en-US/docs/Web/API/History_API), in particular: pushState.
In your case you can use window.history.pushState (https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method).
Instead window.location.replace you can write something like this one:
window.history.pushState({ page: filteruri }, 'Page title', currentURL + '?somethingnew');

err_empty_response error when clicking a button

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

JavaScript AJAX PHP issue

Ok. I need help with this. For some reason the onreadystatechange is fired multiple times. I really need to get this figured out tonight. It's the last task I have left and I don't know what to do or what's causing it. Please help.
I'm using AJAX (ndhr) to send over JSON 'Y-m-d h:i:s' to PHP to use the strtotime() function to return 'm-d-Y' back through AJAX. The JSON and PHP work great, but when the onreadystatechange is fired it does it multiple times. Almost like the readyState == 4 more times than it does.
var divs_d = ["d_2009", "d_2010", "d_2011"];
function ajax_get_json(cdiv,ocdv,ed){
var hr = new XMLHttpRequest();
hr.open("GET", "/json/sample.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
cdiv.innerHTML = "";
var data = JSON.parse(hr.responseText);
var cad = data.comm_archive;
var rndate;
var nda = new Array();
var ndac = 0;
var ec = 0;
for (ni = 0; ni < cad.length; ni++) {
if (cad[ni].year == ocdv) {
ec = ec + 1;
ed.innerHTML = '<h4>' + ocdv + ' (' + ec + ' entries)</h4>';
var ndhr = new XMLHttpRequest();
var url = "/inc/strtotime.php";
var vars = "ndate=" + cad[ni].publish_date;
ndhr.open("POST", url, true);
ndhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ndhr.onreadystatechange = function () {
if (ndhr.readyState == 4 && ndhr.status == 200) {
nda[ndac] = ndhr.responseText;
ndac = ndac + 1;
}
}
ndhr.send(vars);
}
}
nda.sort(function (a, b) { return b - a });
for (ndai = 0; ndai < ndac; ndai++) {
cdiv.innerHTML += '<h4>' + nda[ndai] + '</h4>';
}
}
}
hr.send(null);
}
function optionCchange() {
var ocdv = document.getElementById("optionCdate").value;
var ed = document.getElementById("ediv");
for (i = 0; i < divs_d.length; i++) {
var cdiv = document.getElementById(divs_d[i]);
if (divs_d[i] == "d_" + ocdv) {
cdiv.className = "bddiv show";
ajax_get_json(cdiv,ocdv,ed);
} else {
cdiv.className = "bddiv hide";
}
}
}
In your ndhr.onreadystatechange function ndhr represents the last ndhr created in the loop not the calling one, to reference the calling object use this.
ndhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
nda[ndac] = this.responseText;
ndac = ndac + 1;
}
}
The the last for(ndai = 0; ndai < ndac; ndai++) is behaving as you expect because of the asynchronous nature of ajax, by the time that code is executed the ajax requests have not finished yet. You'll have to execute this code in the on ready change state callback. Just use a counter to check if all the ajax requests have finished then execute the code.
If you need run the code once, you don't have to be anxious about how many times readystate 4 was fired. Simply use a boolean variable to check if the block of code has been executed.
Here's a pseudocode example of my idea.
executed = false;
if (readystate && (executed == false))
{
blablabla;
executed = true;
}
else
{
sry your code has been executed;
}

Login Form > Overlay Closes on Form Error

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.

Call PHP program as popup overlay?

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

Categories