I am grabbing the values of several input fields with the help of an Ajax/JS function. The issue is that the values of the textbox are not being echoed. I checked with the firebug tool and it shows that the post is performed but there is a blank value. Why is the PHP not echoing the value when the JS function submits it?
EXAMPLE
JS
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>
HTML
<form action="" method="post" enctype="multipart/form-data" id="contact_form" name="form4">
<div class="row">
<div class="label">Contact Name *</div> <!-- end .label -->
<div class="input">
<input type="text" id="contact_name" class="detail" name="contact_name" value="<?php echo isset($_POST['contact_name'])? $_POST['contact_name'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['contact_name']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
<div class="row">
<div class="label">Email Address *</div> <!-- end .label -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['email']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
</form>
You need to use .serialize() on the form probably
Friend first understand the Javascript behaviour.
When you post a form, it becomes one request to the server. At the same time when you send an ajax to server it becomes another separate request to the server
So you should either do form post or ajax.
As you are using ajax here you, in the ajax request you have to pass data separately in data parameter
<script type="text/javascript">
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
data: $('#contact_form').serialize(), // check this line
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>
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};
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>
I am currently using Ajax/JS to submit a form without a page refresh or button click. I have set a timer with keyup to trigger the function. I have tested it with one input field and works well but now that other input fields have been added I am getting no results echoed out by the PHP. I have checked with firefox bug tool and the results are being stored. I am not sure if this a JS or PHP issue.
How can I properly echo the value of input field after the user has stop typing? EXAMPLE
JS/AJAX
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
data: dataString,
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
var name = $("#contact_name, #email, #phone, #address, #website").val();
dataString = 'name='+ name;
});
});
</script>
HTML/PHP Snippet
<form action="" method="post" enctype="multipart/form-data" id="contact_form" name="form4">
<div class="row">
<div class="label">Contact Name *</div> <!-- end .label -->
<div class="input">
<input type="text" id="contact_name" class="detail" name="contact_name" value="<?php echo isset($_POST['contact_name'])? $_POST['contact_name'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['contact_name']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
<div class="row">
<div class="label">Email Address *</div> <!-- end .label -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['email']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
Rather than trying to do a mass assignment, you'll need to build up your data. E.g., you currently have:
var name = $("#contact_name, #email, #phone, #address, #website").val();
That jquery should match on the first identifier it matches, most likely the element with id contact_name, and that will be the only value name has, where as you're hoping to get several form fields of data.
In fact, you shouldn't need to build up dataString at all, as your data will be submitted by post via the form.
Rewriting the JS:
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
In your index.php, you can then access the form values in the $_POST array, e.g. $_POST['contact_name'].