Success/Failure Message in Fancybox after Form Submission - javascript

I am trying to craft an AJAX form to display a success/failure/share message via a Fancybox once a user submits their email address on a form. Currently, the code throws the response up to the top of the page.
I have attempted a few variations from other answers provided here here, and here on Stack Overflow, but to no avail, as upon insertion the entire form ceases to load.
My current init.js is as follows:
$("#form").submit(function(e){
e.preventDefault();
leSubmitLoader();
dataString = $("#form").serialize();
var templateURL = $('#templateURL').attr('value');
var blogURL = $('#blogURL').attr('value');
$.ajax({
type: "POST",
url: templateURL + "/post.php",
data: dataString,
dataType: "json",
success:
function(data) {
$.fancybox(
'<p>Content of the box in HTML</p>',
{
padding:15,
closeBtn:true
}
);
function leSubmit(returning){
$.fancybox(
);
$('#form, #error, #presignup-content').hide();
$('#success').fadeIn(function(){
var successScroll = $('#signup-body').offset().top - 20;
$('html,body').animate({scrollTop:successScroll}, 300);
});
if (returning == true) {
$('#returninguser, #returninguserurl').show();
var refCode = data.returncode;
$('#returninguser span.user').text(data.email);
$('#returninguser span.clicks').text(data.clicks);
$('#returninguser span.conversions').text(data.conversions);
$('#returninguserurl input#returningcode').attr('value', blogURL + '/?ref=' + refCode);
} else {
$('#success-content, #newuser').show();
var refCode = data.code;
$('#newuser input#successcode').attr('value', blogURL + '/?ref=' + refCode);
if(data.pass_thru_error == "blocked"){
$('#pass_thru_error').fadeIn();
$('#pass_thru_error').html('AWeber Sync Error: Email Blocked.');
} else if (data.pass_thru_error.AWeberAPIException != undefined){
err = data.pass_thru_error.AWeberAPIException;
$('#pass_thru_error').fadeIn();
$('#pass_thru_error').html(err.type+': '+err.msg);
}
}
// Referral URL
var refUrl = blogURL + '/?ref=' + refCode;
// Twitter (note: refUrl might not show up in share box on localhost)
var tweetUrl = 'http://twitter.com/intent?url=' + encodeURIComponent(refUrl);
var tweetMessage = $('input#twitterMessage').attr('value');
$('#tweetblock').html('Tweet<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>');
// Facebook (note: won't work on localhost)
$("#fblikeblock").html('<div class="fb-like" data-ref="'+refCode+'" data-href="'+refUrl+'" data-send="false" data-width="75" data-show-faces="false" data-font="arial" data-layout="button_count"></div>');
// Google +
function renderPlusone() {
gapi.plusone.render('plusoneblock', {'href':refUrl, 'size':'tall', 'annotation':'none'});
}
renderPlusone();
// Tumblr
var tumblr_button = document.createElement("a");
tumblr_button.setAttribute("href", "http://www.tumblr.com/share/link?url=" + encodeURIComponent(refUrl) + "&name=" + encodeURIComponent(tumblr_link_name) + "&description=" + encodeURIComponent(tumblr_link_description));
tumblr_button.setAttribute("title", "Share on Tumblr");
tumblr_button.setAttribute("onclick", "window.open(this.href, 'tumblr', 'width=460,height=400'); return false;");
tumblr_button.setAttribute("style", "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('http://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
tumblr_button.innerHTML = "Share on Tumblr";
document.getElementById("tumblrblock").appendChild(tumblr_button);
// RinkedIn
$('#linkinblock').html('<script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="'+refUrl+'"></script>');
}
if(data.email_check == "invalid") {
leSubmitLoaderStop();
$('#error').html('This email address is invalid.').fadeIn();
}
else if(data.required.length) {
leSubmitLoaderStop();
$('.error').hide();
$d = String(data.required).split(",");
$.each($d, function(k, v){
$("#" + v + ".error").fadeIn();
});
}
else {
if(data.reuser == "true") {
leSubmit(true);
FB.XFBML.parse(document.getElementById('fblikeblock'));
} else {
leSubmit(false);
FB.XFBML.parse(document.getElementById('fblikeblock'));
}
$('body').addClass('submission-success');
}
}
});
});

I am not trying to fix your code but why you don't use this ajax format to handle success/failure ?
$.ajax({
type: "POST",
url: templateURL + "/post.php",
data: dataString,
dataType: "json"
}).done(function () {
//success
$.fancybox("success", {
// options
});
}).fail(function () {
//error
$.fancybox("failure", {
// options
});
}).always(function () {
// optional after ajax is completed
$.fancybox("else", {
// options
});
});

Related

Ajax submit an ajax loaded form

I load replies to comments asynchronously in php like in youtube comments.
The ajax handler for forms (ie reply forms) loaded like this is not working. e.preventDefault() is not working. The forms are submitted to the action page itself and page is redirected to action url. If i edit a reply. It works but page is redirected to the action url. This happens only for the ajax loaded replies. The same handler is used for regular comments and it works fine.
A comment :
A comment with loaded replies :
When a reply is edited it just goes to /path/to/submit.php and shows the value of json output like this
result on submitting a reply form
Ajax to show or hide replies:
//load or hide replies
function loadmore(id) {
var val = $('#' + id).data("value");
var count = $('#' + id).data("count");
$.ajax({
type: 'post',
url: '/path/to/submit.php',
data: {
replyof: val
},
success: function(response) {
var content = document.getElementById("show" + val);
content.innerHTML = response;
var clicknum = $('#' + id).data("clicknum");
$('#' + id).data("clicknum", 2);
if (!$("#show" + val).is(":hidden") && clicknum != 1) {
document.getElementById(id).innerHTML =
' View all ' + count + ' replies <i class="fas fa-angle-down"></i>';
$("#show" + val).hide();
} else {
document.getElementById(id).innerHTML =
'Hide all replies <i class="fas fa-angle-up"></i>';
$('#show' + val).show();
}
}
});
}
I use the same class for comments as well as replies and ajax submit the form to the same page /path/to/submit.php using
eg
<form class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
The form handler
$(".replyform").submit(function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
The .replyform render by ajax so use on instead of traditional way
$(document).on("submit", ".replyform",function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
I think your calling your form wrong. You need an id attribute. I don't think you can call it by it's class name like that.
<form id="myForm" class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
$("#myForm").submit(function(e) {
...rest of script.

wordpress ajax returning zero instead of string message

My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);

Change cache if language is changed

I have method who populate menu, it be like:
function MenuPopulate(url, listname, target) {
var lang = "Espanol";
if ((window.location.href.indexOf("lang=en") > 0)) {
lang = "English";
}
$(function () {
$.ajax({
url: "https://myapi.company.com/api/myapi/getmenu?idioma=" + lang ,
async: false,
type: 'GET',
dataType: "json",
success: function (data) {
console.log(data);
completeMenu(data, target)
//localStorage.setItem('data', JSON.stringify(data))
},
error: function (response) {
failureMenu(response, target)
}
});
});
}
function completeMenu(data, target) {
var prefix = "<ul class='nav navbar-nav navbar-right'>";
var sufix = "</ul>";
var items = data;
var menu = "";
for (item in items) {
if(items[item].Titile == "JOIN US" ){
menu += "<li><a href='#mymodal' data-toggle='modal' data-target='#mymodal'>" + items[item].Titile + "</a></li><li class='divider-vertical'></li>"
}
else if(items[item].Titile == "CONTACT US"){
menu += "<li><a href='#mymodal2' data-toggle='modal' data-target='#mymodal2'>" + items[item].Titile + "</a></li><li class='divider-vertical'></li>"
}
else{
menu += "<li>" + items[item].Titile + "</li><li class='divider-vertical'></li>";
}
}
$(target).html(prefix + menu + sufix);
}
function failureMenu(data, target) {
console.log(data);
$(target).text("Ocurrió un error en la carga del menú. Por favor revise la consola para más información");
}
And it runs perfectly except for the time to load page, so now I store methods in cache with localStorage , so I made this class:
$(document).ready(function() {
GetGlobal();
});
function GetGlobal() {
var lang = "Espanol";
if ((window.location.href.indexOf("lang=en") > 0)) {
lang = "English";
}
var page = window.location.pathname.replace("/SitePages/", "");
if (localStorage.getItem("Menu") == null) {
$.ajax({
url: "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
async: false,
type: 'GET',
dataType: "json",
success: function(data) {
CompleteGlobal(data);
//alert("Cargo con exito");
},
error: function(data) {
//failureGlobal(data);
alert("No cargo");
}
})
} else {
// alert("la cookie esta cargada");
CargaGlobal();
//localStorage.getItem("Menu")
}
}
function CargaMenu() {
$.ajax({
url: "https://myapi.company.com/api/myapi/getmenu?idioma=" + lang,
async: false,
cache:true,
type: 'GET',
dataType: "json",
success: function(data) {
console.log(data);
completeMenu(data, target)
},
error: function(response) {
failureMenu(response, target)
}
});
}
function CompleteGlobal(data) {
data.Menu //lista de menus
data.Pie // lista pie de pagina
data.Mapa
data.Ligas
localStorage.setItem("Menu", JSON.stringify(data.Menu));
localStorage.setItem("Pie", JSON.stringify(data.Pie));
localStorage.setItem("Mapa", JSON.stringify(data.Mapa));
localStorage.setItem("Ligas", JSON.stringify(data.Ligas));
localStorage.setItem("Enlace", JSON.stringify(data.Enlace));
CargaGlobal();
}
function CargaGlobal() {
completeMenu(JSON.parse(localStorage.getItem("Menu")), "#BarraNavegacion");
completeSiteMap(JSON.parse(localStorage.getItem("Mapa")), "#MapaSitio");
completeImgLinks(JSON.parse(localStorage.getItem("Enlace")), "#EnlacesImagen");
completeFooter(JSON.parse(localStorage.getItem("Pie")), "#Footer");
}
function completeBanner3(target) {
var items = localStorage.getItem("Menu");
var menu = "";
for (var item in items) {
menu += "<div class='col-md-4 text-center'><div><a href='" + items[item].Enlace + "'><img src='" + items[item].Imagen + "' class='img-responsive img-center' /></a></div><div class='t02 text-center'>" + items[item].Titulo + "</div><div class='t03 text-center'>" + items[item].Descripcion + "</div></div>";
}
$(target).html(menu);
}
But when I change language of my site it just no load the other language menu, and I think to load cookie again if language is different to "Espanol" so I think I can do something like
if (localStorage.getItem("Menu") == null && lang == "Espanol") {
$.ajax({
url: "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
async: false,
type: 'GET',
dataType: "json",
success: function(data) {
CompleteGlobal(data);
//alert("Cargo con exito");
}else if(localStorage.getItem("Menu") == null && lang == "English"){
$.ajax({
url: "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
async: false,
type: 'GET',
dataType: "json",
success: function(data) {
CompleteGlobal(data);
},
error: function(data) {
alert("No cargo");
}
})
} else {
CargaGlobal();
}
}
But it doesn´t works, any idea what I need to do in this case? Regards
Instead of saving individual parts to the localStorage, sometimes it's easier just to get and fetch an object by using JSON.parse and JSON.stringify.
This is a rather long example, but I commented it a lot to try to make it easier to follow. It's an illustration of various concepts so it doesn't exactly solve your problem, but I believe it will get you closer to a solution.
EDIT: The StackOverflow script runner does not like localStorage. Here's a JSFiddle to see it in action: https://jsfiddle.net/subterrane/9prr5ks6/
EDIT, EDIT: Also, I don't speak Spanish, so blame Google Translate for the silly menu button labels.
var lang = "Espanol";
if ((window.location.href.indexOf("lang=en") > 0)) {
lang = "English";
}
// function to getMenuData
function getMenuData() {
// get the saved data from localStorage
var menuData = JSON.parse(localStorage.getItem('menuData'));
// if it doesn't exist, or if our language is missing, fetch the data from the server
if (menuData == null || menuData[lang] == null) {
// this is a stub function. Pretend it's doing an ajax request
// the second argument here is a callback function. It would be
// the ajax success function.
fetchMenuData(lang, function(data) {
// if we did have some of the data, use it, or start with an empty object
menuData = menuData || {};
// set the server response to the menuData object
menuData[lang] = data;
// stringify the object and stash it in localStorage
localStorage.setItem('menuData', JSON.stringify(menuData));
// display the menu
displayMenu(menuData);
});
} else {
// we go the data from the cache, so display the menu
displayMenu(menuData);
}
}
// this is a fake function that pretends to get menuData from a server
function fetchMenuData(lang, callback) {
// wait 2 seconds, then call the response function
setTimeout(response, 2000);
// response function sends some data back to the callback depending on the requested language
function response() {
callback(lang == "Espanol" ? [{
name: 'Casa',
link: 'something.html'
}, {
name: 'Lejos',
link: 'somethingelse.html'
}] : [{
name: 'Home',
link: 'something.html'
}, {
name: 'Away',
link: 'somethingelse.html'
}]);
}
}
// function to display the menu
function displayMenu(data) {
// update the text in some of the buttons
document.getElementById('home').innerHTML = data[lang][0].name;
document.getElementById('away').innerHTML = data[lang][1].name;
// looks kinda funny, but this just puts the opposite of the current language
// on the button to make it feel like a toggle button
document.getElementById('toggle').innerHTML = lang == "Espanol" ? "English" : "Espanol";
// show the menu now that it's filled in
document.getElementById('menu').classList.remove('hide');
}
// set up a click handler on the language toggle button
document.getElementById('toggle').addEventListener('click', function() {
// hide the menu while we mess with it. Could take a while to get the menu
// data back from our 'server'
document.getElementById('menu').classList.add('hide');
// set the language to the opposite of whatever it was before
lang = lang == "Espanol" ? "English" : "Espanol";
// get the menu data from the cache or server
getMenuData();
});
// kick it all off by getting the menu data from the server
getMenuData();
.hide {
display: none;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<div class="container">
<div id="menu" class="hide">
<button id="home"></button>
<button id="away"></button>
<button id="toggle"></button>
</div>
</div>

select child at beginning of function jquery

I can't appear to select the child form of a div I have for some reason.
For the matter, I am trying to find a way that I can have a function select the child form of a div since I have it changing for a toggling function at my site.
$(document).ready(function(){
$("#soundToggle, #soundOffForm").submit(function(event){
/*var r = new XMLHttpRequest();
r.open("POST", "sessionsetter.php", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
r.send("a=1&b=2&c=3");*/
alert("post");
event.preventDefault();
$.ajax({
type: "POST",
url: "sessionsetter.php",
data: {
sound : '0',
},
success: function(data) {
//alert("Sound toggled successfully: " + data);
$('#soundToggle').load(location.href + " #soundOnForm");
},
error: function(data) {
alert("Error in processing request: " + data);
}
});
});
$("#soundToggle, #soundOnForm").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "sessionsetter.php",
data: {
sound : '1',
},
success: function(data) {
//alert("Sound toggled successfully: " + data);
$('#soundToggle').load(location.href + " #soundOffForm");
},
error: function(data) {
alert("Error in processing request: " + data);
}
});
});
});
Anyone have any suggestions on how I can make this a possibility? Thanks. When I don't select the child of a form, the handler is destroyed as I replace the form in my DOM.
The jquery binding will be lost if the Dom is reconstructed after page loads, you may want to use this:
Assumption here is #soundToggle is the div that contains form
$("#soundToggle, #soundToggle form").submit(function(event){
if($("#soundToggle form").attr('id') == "soundOnForm"){
//do on functionality
} else if($("#soundToggle form").attr('id') == "soundOffForm"){
//do off functionality
}
}

Showing page when submit form via ajax - Jquery mobile

I am using JQuery Mobile for creating mobile application and i have index.html in this html page i have 2 pages(search_form, search_result). I want to submit search form from search_form page and then it should shows the search_result page. The following is my js code:
var formURL = "http://10.0.2.2/jobs/mobile/home/searchJobs/";
$.ajax(
{
url : formURL,
type: "POST",
data : $("#search_frm").serialize(),
//data : "&data=90",
beforeSend: function() {
showLoader();
},
success:function(result)
{
var list = '';
var data = $.parseJSON(result);
//$("#ulListview1").html($.parseJSON(result));
$.each(data,function(i,item){
if(item.id=='0')
{
list += "<li><span style='color:red;'>Record not found!</span></li>";
}
else
{
list += "<li><a data-transition='slide' href='#job_details_page' onclick='getJobDetails("+item.id+");'>" + item.job_title +"<p style='display:inline;'> at "+item.company+"</p><br><p><span><strong>Expiring On:</strong> "+item.expire_date+"</span> <br><span><strong>Job Location:</strong> "+item.location+"</span></p>"+"</a></li>";
}
//alert(data[i]["id"] + " " + data[i]["username"]);
});
//hide loader
hideLoader();
$("#search_list").html(list);
$("#search_list").listview("refresh");
$("#search_result").css("display","block");
},
error: function(jqXHR,status)
{
alert(status);
//alert($.parseJSON(jqXHR));
}
});
Could you please help to fix this problem?

Categories