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/
Related
I have a PHP application, In this application I am trying to using AJAX.
Below code is for View page. From this page I am trying to go to the controller URL but I am not getting it back after echo the value. Could you please help anyone!
<?php require APPROOT.'/views/inc/header.php'; ?>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<div id="container" class="col-xs-6 col-xs-offset-3">
<div class="row">
<h2>Search Our Database</h2>
<input class='form-control' type="text" name='search' id='search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="bg-success" id="result"> rumman
</h2>
</div>
<script>
$(document).ready(function(){
$('#search').keyup(function(){
var search = $('#search').val();
// alert(search);
$.ajax({
url:'Subjects/add',
data:{search:search},
type: 'POST',
success:function(data){
if(!data.error) {
$('#result').html(data);
}
}
});
});
});
</script>
<?php require APPROOT.'/views/inc/footer.php'; ?>
Below is my Controller method inside Subjects controller
public function add(){
if(isset($_POST['search'])) {
$search = $_POST['search'];
echo $search;
}
$this->view('Subjects/add');
}
I hope this will solve your problem.
<script>
$(document).ready(function(){
$('#search').keyup(function(){
var search = $('#search').val();
$.ajax({
url:'subjects/add',
data:{search:search},
type: 'POST',
success:function(data){
if(!data.error) {
$('#result').html(data);
}
}
});
});
});
</script>
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;
}
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/
I believe my problem has something to do with the fact that my first form RETURNS a new form via ajax success .html(result) AFTER DOM has executed. My jquery within DOM isn't being recognized because elements aren't visible until after the submit of first form. HOW to get my $("#fullFormMA").on(submit,(function(e){ to execute is eluding me. Here is my html
<?php
session_start();
require_once('functions.php');
include('header.htm');?>
<title>Membership Application</title>
<meta name="description" content="">
</head>
<body>
<div id="container">
<div id="loginBanner">
<?php include ("loginMenu.php"); ?>
<?php include ("bannerIcons.php"); ?>
</div> <!--end loginBanner-->
<div id="header" class="clear">
</div> <!--end header-->
<div id="content"><div class="content">
<div id="colLt">
<?php include('tabContent.php');?>
<?php include('leftSidebar.php');?>
</div>
<div id="colRt"><div class="content">
<h1>New Member Application</h1>
<ul><li>submitting an application</li><li>submitting payment</li></ul><h6>Step #1—the application</h6>Please enter an email which will ultimately be used as your website username. This email will remain as your private email.</p><br><br>
<form method="post" name="checkUserMA" id="checkUserMA">
<label class="clear" style="width:120px">Username/Email<br><span class="small"></span></label>
<input type="text" name="usernameMA" id="usernameMA" class="green" style="width:300px;"/><br><br>
<input type="submit" id="checkUserMA" class="submit" value="Submit" />
</form>
<div class="clear"></div>
<div id="errorMA" style="background:yellow;width:200px;height:100px"></div>
<div id="resultMA"></div>
</div></div>
<div class="clear"></div>
</div></div><!--end content-->
<div id="footer">
<?php include("footer.htm") ?>
<!--<?php include("disclaimer.htm") ?>-->
</div><!--end footer-->
<div class="clear"></div>
</div><!--end container-->
<div class="clear"></div>
</body>
</html>
Here is my jquery:
$(document).ready(function() {
$('#resultMA').hide();
$('#errorMA').hide();
$("#checkUserMA").submit(function(event){
event.preventDefault();
$("#resultMA").html('');
var values = $(this).serialize();
$.ajax({
url: "checkMA.php",
type: "post",
data: values,
success: function(result){
$("#resultMA").html(result).fadeIn();
$('.error').hide();
},
error:function(){
// alert("failure");
$("#resultMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
$("#fullFormMA").on(submit,(function(e){
e.preventDefault();
$("#errorMA").html('');
var values = $(this).serialize();
$.ajax({
url: "validMA.php",
type: "post",
data: values,
success: function(result){
},
error:function(){
// alert("failure");
$("#errorMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
});//end dom
Here is checkMA.php...
<?php
session_start();
include('functions.php');
connect();
$username = urldecode(protect($_POST['usernameMA']));
$_SESSION['guestUser'] = $username;
$sql2 = mysql_query("SELECT username FROM members WHERE username = '$username'");
$checkNumRows = mysql_num_rows($sql2);
if (!$username){
echo "<p class='red'>Enter an email to be used as your username...</p>";
} else if ($checkNumRows == 1){
echo "<span style='font-weight:bold'>The username: ".$username." is already in use.</span>";
} else if ($checkNumRows == 0){
echo "<hr><p class='green'>This username is available.</p><p>Please continue with the registration process...</p><br>";?>
<form method="post" name="fullFormMA" action="memberAppProcess.php">
<h6>Public Information - this information will be displayed to website visitors</h6>
<label class="clear" style="width:75px">Name</label>
<label class="error" id="name_error">This field is required.</label>
<input type="text" name="firstName" id="firstName" class="left inputCheck" style="width:150px" placeholder="first name"/>
<input type="text" name="lastName" id="lastName" class="inputCheck" style="margin-left:10px" placeholder="last name"/><br><br>
<input type="submit" name="fullFormMA" id="fullFormMA" class='submit right' onClick='submitFullForm();' value="Submit application">
</form>
<?php
}?>
My #checkUserMA works but my #fullFormMA doesn't work. I would love to understand why (DOM already loaded?) and how I might fix my code to allow for a form added "after the fact" via ajax .html(result). Thank you.
The DOM is ready before your ajax success so you can write this JQuery full code
$(document).ready(function() {
$('#resultMA').hide();
$('#errorMA').hide();
$("#checkUserMA").submit(function(event){
event.preventDefault();
$("#resultMA").html('');
var values = $(this).serialize();
$.ajax({
url: "checkMA.php",
type: "post",
data: values,
success: function(result){
$("#resultMA").html(result).fadeIn();
$('.error').hide();
RunAfterAjax();
},
error:function(){
// alert("failure");
$("#resultMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
function RunAfterAjax(){
$("#fullFormMA").on(submit,(function(e){
e.preventDefault();
$("#errorMA").html('');
var values = $(this).serialize();
$.ajax({
url: "validMA.php",
type: "post",
data: values,
success: function(result){
},
error:function(){
// alert("failure");
$("#errorMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
}
});//end dom
It's executing, you just aren't waiting long enough for it to exist. Move the event binding for the new form to the line right after you add the new form to the document.
$("#resultMA").html(result).fadeIn();
$("#fullFormMA").on(submit,(function(e){...
$("#fullFormMA").on(submit,(function(e){ /* ... */ });
fullFormMA is an <input>, you should bind click instead of submit, and use quotes around the event name.
When you use $('#something').on('event', ...), it only works if the #something element already exists.
You could fix your code by delegating the listener to an upper existing element :
$('#content').on('click', '#fullFormMA', function() { /* ... */ });
This code will detect the click event on #fullFormMA event if it is added after an ajax response.
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>