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/
Related
I am trying to submit a form via ajax post to php but the value of the input tag appears to empty.
I have cross-checked defined class and id and it seems ok. I don't where my mistake is coming from. Here is the code
index.html
<div class="modal">
<div class="first">
<p>Get notified when we go <br><span class="live">LIVE!</span></p>
<input type="text" class="input" id="phone" placeholder="Enter your email adress" />
<div class="arrow">
<div class="error" style="color:red"></div>
<div class="validator"></div>
</div>
<div class="send">
<span>Subscribe</span>
</div>
</div>
<div class="second">
<span>Thank you for<br />subscribing!</span>
</div>
</div>
<script src='jquery-3.3.1.min.js'></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
function validatePhone(phone) {
var re = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
return re.test(phone);
}
$('.input').on('keyup',function(){
var formInput = $('.input').val();
if(validatePhone(formInput)){
$('.validator').removeClass('hide');
$('.validator').addClass('valid');
$('.send').addClass('valid');
}
else{
$('.validator').removeClass('valid');
$('.validator').addClass('hide');
$('.send').removeClass('valid');
}
});
var phone = $('#phone').val();
var data =
'phone='+phone;
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
});
subscribe.php
```php
$phone = htmlentities($_POST['phone']);
if (!empty($phone)) {
echo 1;
}else{
echo "Phone number cannot be empty";
}
```
An empty results with the error code is all I get. Can any one help me out here with the mistakes I am making. Thanks
Change next
JS:
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
to
$('.send').click(function(){
var data = $('#phone').val();
$.ajax({
type:"POST",
url:"subscribe.php",
data: {phone: data},
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
});
});
If you send a POST request via ajax you need to format data as a JSON object, see my code below.
Replace this:
var data =
'phone='+phone;
with this:
var data = {phone: phone};
I am trying to get my jQuery to work with CSS animations/class changes and working with an ajax post for this logon forum. I am having trouble reworking the JQuery animation script and incorporating the Ajax port for username and password. It does not seem to be posting the login information.
<form class="login" action="" method="post" autocomplete="false">
<div class="group">
<input id="user" type="username" name="user" class="input" placeholder="Username" required autofocus>
</div>
<div class="group">
<input id="password" type="password" name="password" class="input" data-type="password" placeholder="Password" required>
</div>
<div class="group">
<button>
<i class="spinner"></i>
<span class="state">Log in</span>
</button>
</div>
<div class="hr"></div>
</form>
Here is the jQuery
var working = false;
$('.login').on('submit', function(e) {
e.preventDefault();
if (working) return;
working = true;
var $this = $(this),
$state = $this.find('button > .state');
$this.addClass('loading');
$state.html('Authenticating');
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
url: "login.php",
success: function(data) {
if (data.status == 'success') {
this.addClass('ok');
$state.html('Welcome back!');
setTimeout(function() {
window.location = "/index.php"
}, 4000);
} else if (data.status == 'error') {
setTimeout(function() {
$state.html('Log in');
$this.removeClass('ok loading');
}, 3000);
}
},
});
});
After using Diego's suggestion and piping the out to the console log I was able to determine that the php function was not returning anything. Adding an echo in with corresponding results resolved my issue along with using 'data' in the if statement instead of 'data.status'.
sbms.php
<?php
header('Access-Control-Allow-Origin: *');
if(isset($_POST['signup']))
{
$id = $_POST['val'];
echo $id;
}
?>
index.html
<form>
<label class="item-input">
<span class="input-label">ID</span>
<input type="text" id="cid">
</label>
<label class="item-input">
<button class="button button-block button-positive" id="signup">Submit</button>
</label>
</form>
<div class="card">
<div class="item item-text-wrap">
<p id="res"></p>
</div>
</form>
ajax script:-
$(document).ready(function(){
$('#signup').click(function(){
var data = $('#cid').val();
$.ajax({
type : "POST",
data : val,
url : 'http://127.0.0.1/ionic/sbms.php',
crossDomain : true,
success : function (data) {
alert(data);
}
});
});
});
I am just trying to a dummy response from the server but the response I get is totally blank. I am not able to figure out the problem
You're not sending a signup value, you're just sending in an unnamed value so your PHP script is not entering the if condition. Try changing your ajax call to this:
$.ajax({
type : "POST",
data : { val: val, signup: true }
url : 'http://127.0.0.1/ionic/sbms.php',
crossDomain : true,
success : function (data) {
alert(data);
}
});
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 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/