Foundation Reveal on AJAX success not working - php

Attempted to post this on the Foundation forum, but for some reason it would not post.
The first code snippet below shows the working code for my form using data-abide="ajax", and the .on('valid.fndtn.abide',function(){});. The elements are disabled etc. and the modal opens. When the modal is closed I remain on the page as desired.
I am attempting to now have this use AJAX, where the request will be to a php script handling the data insert, and the element manipulation and modal will happen on success.
The second code snippet shows that attempt, which is not working. When I run this code, the alert fires, but then the page submits, with nothing written to the console, no modal, and the page refreshing. What am I doing wrong?
I have also included partial code (third snippet), for the form and modal.
If anyone has a working example using Foundation, data-abide="ajax" and reveal-modal, where the form is submitted, an AJAX call is made to a PHP script to insert data into the DB, and on success the modal window opens, please provide a sample.
SNIPPET 1 - works
<script type="text/javascript">
$(document).ready(function () {
$("#pledge_btn").attr("disabled", true);
$(document).foundation({
abide: {
validate_on: 'manual',
patterns: {
edu_address: /\.edu$/
}
}
});
$('a.custom-close-reveal-modal').click(function(){
$('#emailModal').foundation('reveal', 'close');
});
$('#pledge_form')
.on('invalid.fndtn.abide', function() {
$("#pledge_btn").attr("disabled", true);
$("#terms").prop("checked",false);
console.log('Not Submitted');
})
.on('valid.fndtn.abide', function() {
$("#pledge_form :input").prop('readonly', true);
$("#pledge_btn").attr("disabled", true);
$("#terms").attr("disabled", true);
$("#sweeps").attr("disabled", true);
console.log('Submitted: ', data);
$('#myModal').foundation('reveal', 'open');
});
});
SNIPPET 2 - Does NOT work
<script type="text/javascript">
$(document).ready(function () {
$("#pledge_btn").attr("disabled", true);
$(document).foundation({
abide: {
validate_on: 'manual',
patterns: {
edu_address: /\.edu$/
}
}
});
$('a.custom-close-reveal-modal').click(function(){
$('#emailModal').foundation('reveal', 'close');
});
$('#pledge_form')
.on('invalid.fndtn.abide', function() {
$("#pledge_btn").attr("disabled", true);
$("#terms").prop("checked",false);
alert("Form NOT submitted");
})
.on('valid.fndtn.abide', function() {
var lname = $("#lName").val();
var dataString = 'lname=' + lname;
alert("Form submitted");
$.ajax({
url : create_pledge.php,
type : $(this).attr('method'),
data : dataString,
success : function( data ) {
$("#pledge_form :input").prop('readonly', true);
$("#pledge_btn").attr("disabled", true);
$("#terms").attr("disabled", true);
$("#sweeps").attr("disabled", true);
console.log('Submitted: ', data);
$('#myModal').foundation('reveal', 'open');
},
error : function( data, xhr, err ) {
console.log('Oops: ', data, xhr , err);
}
});
return false;
});
});
</script>
PARTIAL FORM and MODAL Code
<div class="row pledge-row">
<form data-abide="ajax" id="pledge_form" method="post" name="pledge_form">
<div class="row">
<div class="large-6 medium-12 columns">
<label class="pledge-label">First Name*</label>
<input id="fName" type="text" required pattern="[a-zA-Z]+"/>
<small class="error">First Name is required</small>
</div>
</div>
<div class="row">
<div class="large-6 medium-12 columns">
<label class="pledge-label">Last Name*</label>
<input id="lName" type="text" required pattern="[a-zA-Z]+"/>
<small class="error">Last Name is required</small>
</div>
</div>
<div class="row">
<div class="large-6 medium-12 columns">
<label class="pledge-label">Email*</label>
<input id="email" type="email" required style="margin:0 0 5px 0 !important;"/>
<small class="error">.edu email address is required</small>
<span id="email-result"></span>
<div class="valid-email">(must be a properly formatted .edu email)</div>
</div>
</div>
<!-- CODE REMOVED FOR THIS POST -->
</form>
</div>
<!-- Modal -->
<div id="myModal" class="reveal-modal" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog">
<h2 id="modalTitle">Thanks for pledging.</h2>
<p>please check your email for our confirmation/validation email.</p>
<a class="close-reveal-modal" aria-label="Close">×</a>
</div>

Found the answer. I needed to have the ajax request in the submit, not the valid event.
So this works:
$('#pledge_form')
.on('invalid.fndtn.abide', function() {
$("#pledge_btn").attr("disabled", true);
$("#terms").prop("checked",false);
// alert("Form NOT submitted");
})
.on('valid.fndtn.abide', function() {
// alert("Form submitted");
console.log('VALID');
})
.on('submit', function(e) {
var ajaxObj = $.ajax({
url : 'create_pledge.php',
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( ) {
$("#pledge_form :input").prop('readonly', true);
$("#pledge_btn").attr("disabled", true);
$("#terms").attr("disabled", true);
$("#sweeps").attr("disabled", true);
console.log('Submitted');
$('#myModal').foundation('reveal', 'open');
},
error : function( xhr, err ) {
console.log('Oops: ', xhr , err);
},
complete: function(){
console.log('COMPLETE');
}
});
});
});

I had the same problem too with fancybox and ajax check before submit.
This is my solution that works for sure
<form id="my_form" action="...." method="POST" class="popup" data-abide="ajax">
<input type="text" name="check_this_field_with_ajax" id="check_this_field_with_ajax">
....
</form>
<script type="text/javascript" src="..../js/foundation.min.js"></script>
<script type="text/javascript" src="..../js/foundation/foundation.abide.js"></script>
<script type="text/javascript">
$('#my_form')
.on('invalid.fndtn.abide', function() {
console.log('NOT Submitted');
})
.on('valid.fndtn.abide', function() {
console.log('VALID');
})
.on('submit', function(e) {
var ajaxRequest = $.ajax({
type: 'GET',
url: "....",
data: {xxx: yyy},
cache: false,
dataType: 'json',
});
....
ajaxRequest.done(function() {
if (ok) {
$('#check_this_field_with_ajax').parent().removeClass('error');
$('#my_form').attr({'submit_this_form': 'yes'});
$(document).foundation('abide', 'reflow');
$('#my_form').trigger('submit.fndtn.abide');
}
});
}
</script>
Now go to in foundation.abide.js, search line "validate : function (els, e, is_ajax) {" and add:
if (
is_ajax &&
form.attr('submit_this_form') === 'yes'
) {
return true;
}
before
if (is_ajax) {
return false;
}

Related

How to alert success message in modal form?

I'm new to ajax/jquery. I want to use sweetalert on my website, i set it up as in tutorial, but when i open modal form and click send button, it goes to another page, page send.php.
Here my form:
<form id="contactForm1" action="send.php" method="post">
<div class="field-block">
<label for="text">Message1</label>
<textarea id="message1" class="field" required name="message1" rows="4" placeholder=""></textarea>
</div>
<div class="field-block">
<label for="text">Message2</label>
<textarea id="message2" class="field" required name="message2" rows="4" placeholder=""></textarea>
</div>
<div class="field-block">
<label for="text">Message3</label>
<textarea id="message3" class="field" required name="message3" rows="4" placeholder=""></textarea>
</div>
<button id="button" class="button" type="submit">Отправить</button>
<div class="result">
<span id="answer"></span>
<span id="loader"><img src="images/loader.gif" alt=""></span>
</div>
</form>
inside this form sweetalert doesn't work, but outside of form it's working.
Here sweetalert jquery and ajax request:
<script>
$("#contactForm1").on('submit',function(event) {
event.preventDefault(); // to prevent default page reloading
var dataString = $(this).serialize(); // to get the form data
$.ajax({
type: "POST",
url: "send.php",
data: dataString,
success: function(data){
$('#contactForm1')[0].reset(); // to reset form data
}
}).done(function(data){
setTimeout(function () {
Swal.fire(
'Thank you!',
'Your request has been accepted!',
)
}, 2000);
});
});
</script>
what could be the problem? Please help
The problem is you're not sending request with AJAX.
Solution:
First remove action="send.php" from your form
then add this to your script.
<script>
$('.button').click(function(){
swal({
title:"Red Stapler",
text: "Are You Sure?",
buttons: {
cancel: true,
confirm: "Submit"
}
}).then((value) => {
<!-- When the user click submit send Ajax request -->
$.ajax({
url: "send.php",
method: "POST",
data:{
message1: $(#message1).val(),
message2: $(#message2).val(),
message3: $(#message3).val()
},
success: function(data)
{
// some actions
}
});
});
});
</script>
You can send it without ajax request also try this change
$('.button').click(function(){
to
function submitForm(){
your function will look like this:
function submitForm(){
swal({
title:"Red Stapler",
text: "Are You Sure?",
buttons: {
cancel: true,
confirm: "Submit"
}
});
}
Now in the form add
onsubmit="return submitForm()"
swal({ title: "Done", text: "Record updated successfully!", type: "success" }, function () {location.reload();});
Simply use this line code, it will automatically hide alert and reload the page when click "OK".

Cancel submit jquery

This is a part of the code from a form requesting data to check if the email alredy exist. The thing is, the program is supposed to return 0 if there is no any mail like this. It dont work properly, because the program keep sending the data, even if the mail is not correct.
If you want more info, or i am missing something let me know. Thanks in advance.
$(document).ready(function () {
$("#enviar").click(function(e) {
e.preventDefault();
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = false;
}else{
$("form").unbind('submit').submit();
}
}
});
if (error){
return false;
}
});
});
And here is my compruebaEmail.php
<?php require_once('connections/vinoteca.php'); ?>
<?php
mysql_select_db($database_vinoteca, $vinoteca);
$user = $_POST['b'];
if(!empty($user)) {
comprobar($user);
}
function comprobar($b) {
$sql = mysql_query("SELECT * FROM usuarios WHERE email = '".$b."'");
$contar = mysql_num_rows($sql);
if($contar == 0){
echo 0;
}else{
echo 1;
}
}
?>
And here goes the POST
<form method="POST" name="form1" action="validarUsu.php">
<div class="row">
<span class="center">Email</span>
</div>
<div class="row">
<input type="text" name="email" id="email2" value="" size="32" />
</div>
<div class="row">
<span class="center">Contraseña</span>
</div>
<div class="row">
<input type="password" name="password" id="id2" value="" size="32" />
</div>
<div class="row">
<span id="error"> </span>
</div>
<div class="row">
<input type="submit" value="Acceder" id="enviar" size="20">
</div>
<div class="row">
Recuperar contraseña
</div>
</form>
The problem is you're returning false from your Ajax function. You need to return false from your click function. Give this a try:
$("#enviar").click(function() {
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = true;
}
}
});
if (error)
return false;
});
If all you want is canceling the submitting event, then :
Either :
1 - Add the event arg to your click handler :
$("#enviar").click(function(event){
2 - use event.preventDefault(); when you want to cancel the submit message :)
or change the "return false;" location so that it will be triggered in the "click" handler scope and note the "success" scope e.g with a boolean that would represent if there is an error (EDIT : that is Styphon' solution)
Documentation here : http://api.jquery.com/event.preventdefault/

Ajax to php - javascript events not firing

I'm sure this will be easy for you guys but I'm struggling with this one. Just trying to do a simple ajax post request to a php file here.
I can see that the ajax request is working because I get valid data back from my php script (I verified this by echoing the result to the page). However, my ajax callbacks are not firing. See below:
Javascript:
var request;
$(document).ready(function() {
$('#loginform').submit(function(e) {
if (request)
request.abort();
var $form = $(this);
var $inputs = $form.find("input, select, button");
$inputs.prop("disabled", true);
var serializedData = $form.serialize();
request = $.ajax({
url: "/login.php",
type: "post",
data: serializedData,
timeout: 10000,
success: function() {
alert("success");
// $("#result").html('Submitted successfully');
},
error: function() {
alert("failure");
// $("#result").html('There is error while submit');
}
});
});
PHP
<?php echo 'foo'; exit(); ?>
I almost feel stupid asking this considering the number of examples there are, but I cannot get this to work for the life of me. Suggestions?
EDIT
Included html (Most of the css classes are from bootstrap btw)
<div style='background-color: #193048; width: 100%; height: 500px; background-repeat: no-repeat; background-position: center center; background-size: cover;'>
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4">
<h1 class="text-center login-title whiteFont">Sign in to continue</h1>
<div class="account-wall">
<div align='center'>
<img class="profile-img" align='center' src="https://lh5.googleusercontent.com/-b0-k99FZlyE/AAAAAAAAAAI/AAAAAAAAAAA/eu7opA4byxI/photo.jpg?sz=120"
alt="">
</div>
<form id="loginform" class="form-signin" method="post" >
<input type="text" name='emailTxt' class="form-control" placeholder="Email" required autofocus>
<input type="password" name="passTxt" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit" value="login" id="loginBtn" >
Sign in</button>
<label class="checkbox pull-left">
<input type="checkbox" value="remember-me" >
<label class="whiteFont">Remember me</label>
</label>
<label class="whiteFont">Need Help?</label><span class="clearfix"></span>
</form>
</div>
</div>
</div>
</div>
.submit is most likely causing a postback, canceling out your JS. Add preventDefault to the beginning of your function:
e.preventDefault();
You need to pass the data returned from the server as an argument to your callback
var request;
$(document).ready(function() {
$('#loginform').submit(function(e) {
if (request)
request.abort();
var $inputs = $form.find("input, select, button");
$inputs.prop("disabled", true);
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "/login.php",
type: "post",
data: serializedData,
timeout: 10000,
success: function(data, status, xhr) { // <---- changes made here
alert("success");
// $("#result").html('Submitted successfully');
},
error: function() {
alert("failure");
// $("#result").html('There is error while submit');
}
});
});

How to get Ajax to execute within an Ajax generated FancyBox?

I'm facing a problem using the FancyBox plugin. I'm trying to submit a form with Ajax and just print a nice little success message, no validation just yet, trying to get it to work. I can submit with jQuery and display the value of any input within the FancyBox. However when I try to execute Ajax it just closes the FancyBox down. I'm not an expert...
The FancyBox's content is generated using Ajax because it requires data from a database.
Here are the important code parts: (Texts are German...)
The file loaded into the FancyBox using Ajax
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
alert('Richtig.');
}
else
{
alert('Falsche Benutzername/Passwort Kombination.');
}
}
});
});
</script>
<div class="login">
<div class="widget_header">
<h4 class="widget_header_title wwIcon i_16_wysiwyg">Benutzer Bearbeiten</h4>
</div>
<div class="widget_contents lgNoPadding">
<form method="post" id="form-edit">
<p id="errormessagehere"></p>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Benutzername</span></div>
<div class="g_9 g_9M">
<input type="text" name="login" id="login" value="<?php echo getusername($_GET['u']) ?>" class="simple_field tooltip" placeholder="Benutzername" autocomplete="off"></div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Passwort</span></div>
<div class="g_9 g_9M">
********
</div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_6">Abschicken
</div>
<div class="clear"></div>
</div>
</form>
</div>
</div>
Here's how I call the Fancy box
$(document).ready(function() {
$(".fancybox").fancybox({
'scrolling' : 'no',
'padding' : 0,
'titleShow' : false
});
});
handleuseredit.php just echoes "ok" to fullfill the data variable requirement.
You can test something like this with the version 2 of fancybox (http://fancyapps.com/fancybox/):
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
$.fancybox( '<h1>Richtig.</h1>' );
}
else
{
$.fancybox( '<h1>Falsche Benutzername/Passwort Kombination.</h1>' );
}
}
});
});
</script>

Ajax not being fired?

I'm using the jquery validator plugin, and I'm trying to make my first attempt with AJAX to it.
Right now, I have the following HTML code:
<div class="grid_12" id="info">
</div>
<div class="grid_12">
<div class="block-border">
<div class="block-header">
<h1>Inserir nova página</h1><span></span>
</div>
<form id="formulario" class="block-content form" action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<div class="_100">
<p><label for="textfield">Nome da página</label><input id="page_name" name="textfield" class="required text" type="text" value="" /></p>
</div>
<div class="_100">
<p><label for="textarea">Conteúdo da página</label><textarea id="page_content" name="textarea" class="required uniform" rows="5" cols="40"></textarea></p>
</div>
<div class="block-actions">
<ul class="actions-left">
<li><a class="button red" id="reset-validate-form" href="javascript:void(0);">Limpar</a></li>
</ul>
<ul class="actions-right">
<li><input type="submit" class="button" name="send" value="Inserir"></li>
</ul>
</div>
And my JS code:
<script type="text/javascript">
$().ready(function() {
/*
* Form Validation
*/
$.validator.setDefaults({
submitHandler: function(e) {
$.jGrowl("Ação executada com sucesso.", { theme: 'success' });
$(e).parent().parent().fadeOut();
/*
* Ajax
*/
var mypostrequest=new ajaxRequest();
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("info").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request")
}
}
}
var page_name=encodeURIComponent(document.getElementById("page_name").value);
var page_content=encodeURIComponent(document.getElementById("page_content").value);
var parameters="page_name="+page_name+"&page_content="+page_content;
mypostrequest.open("POST", "ajax/inserir_utilizador.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
v.resetForm();
v2.resetForm();
v3.resetForm();
return false;
}
});
var v = $("#create-user-form").validate();
jQuery("#reset").click(function() { v.resetForm(); $.jGrowl("User was not created!", { theme: 'error' }); });
var v2 = $("#write-message-form").validate();
jQuery("#reset2").click(function() { v2.resetForm(); $.jGrowl("Message was not sent.", { theme: 'error' }); });
var v3 = $("#create-folder-form").validate();
jQuery("#reset3").click(function() { v3.resetForm(); $.jGrowl("Folder was not created!", { theme: 'error' }); });
var formulario = $("#formulario").validate();
jQuery("#reset-validate-form").click(function() { formulario.resetForm(); $.jGrowl("O formulário foi limpo!", { theme: 'information' }); });
});
I have a div #info without anything in it that I'm trying to put there the result of the ajax.
My ajax file is just trying to echo the POST values:
<?php
$page_name=$_POST["page_name"];
$page_content=$_POST["page_content"];
echo $page_name."<br />";
echo $page_content;
?>
But it really doesn't work. It really doesn't do anything, or if it does, it refreshes the page.
What am I missing?
Regards and thanks!
I recommend you to use $.ajax() or $.post().
It's much easier and your headache will surely go away.
$.ajax({
type: 'POST',
url: 'url to post',
data: data,
success: function(data, status) {
//callback for success
},
error: error, //callback for failure
dataType: "json" //or "html" etc
});
many examples here:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.ajax/

Categories