jquery ajax event.preventDefault() cancel the submit action of form - php

I create a form in html:
<form id="flog" action="https://localhost/book.php" method="post">
<div id="inputUser">
<label for="userName">User</label>
<input type="text" name="userName" id="userName">
</div>
<div id="inputPass">
<label for="password">Password</label>
<input type="password" name="password" id="password">
</div>
<div id="savePassword">
<input type="checkbox" id="savePassword" value="CheckSavePAssword">Save password
<br>
</div>
<input type="submit" value="Acceptar">
</form>
And I create a submit function with JQuery:
$("#flog").submit(function(event) {
var savePassword = false;
if($("#CheckSavePAssword").is(':checked')) {
savePassword = true;
}
var login = new Object();
login.username = $("#userName").val();
login.pass = $("#password").val();
login.savePassword = savePassword;
var jlogin = JSON.stringify(login);
event.preventDefault();
$.ajax({
url: "./checkLogin.php",
type: "POST",
dataType: "JSON",
data: {"dataLogin" : jlogin},
success: function(data, textStatus, xhr) {
console.log("okk "+data);
},
error: function(xhr, textStatus, errorThrown) {
console.log("error");
console.log(xhr);
console.log(textStatus);
console.log(errorThrown);
}
});
});
But if i don't put "event.preventDefault()" the ajax function does not run, but this line (event.preventDefault()) canceling the submit form action.What is the problem?

When you use preventDefault(), you prevent the form from undergoing a traditional POST where your page would be submitted and reloaded. You need to use a JavaScript event handler if you want to give the user some feedback after your AJAX call.

Related

Jquery animations with Ajax post to php script

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'.

how to use a single ajax process looped form

I have a HTML form that might be in a loop thus:
<form name="ajaxform" id="ajaxform<?php echo $sn;?>" action="" method="POST">
<p>Comment:<br /> <input type="text" value="" style="width:400px" name="comment<?php echo $sn;?>" />
<input type="button" id="simple<?php echo $sn;?>" class="submit" value="Save" />
<div id="simple-msg<?php echo $sn;?>"></div>
</form>
<?php
// the loop is ending here
?>
Now, the ajax code for posting these form onto a specific url is here:
<script>
$(document).ready(function()
{
$("#simple<?php echo $sn;?>").click(function()
{
$("#ajaxform<?php echo $sn;?>").submit(function(e)
{
//$('#simple').val().submit(function()
//$("#ajaxform1").submit(function(e)
//{
//$('#simple-msg').show();
$("#simple-msg<?php echo $sn;?>").html("<img src='ajax/profile/ajax-loader.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : "ajax/results/comment.php?id=<?php echo $sn;?>",
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#simple-msg<?php echo $sn;?>").html(''+data+'');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#simple-msg<?php echo $sn;?>").html('<font color="red">Failed to save<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</font><span class="icon icon-color icon- close"></span>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#ajaxform<?php echo $sn;?>").submit(); //SUBMIT FORM
});
});
</script>
The problem is how do I use this ajax script to process all the form without having to loop the script too. as you can see in the script above, I want to remove all the(). if I do that and submit the form, only the first form process, but if I put the script in the loop, all will process. I figure that this is a bad practise as if I have a thousand form in a page, the script also repeat a thousand time. large data to the browser huh?
Use classes:
<form name="ajaxform" action="" method="POST" data-sn="<?php echo $sn;?>">
<p>Comment:<br /> <input type="text" value="" style="width:400px" name="comment<?php echo $sn;?>" />
<input type="button" class="simple submit" value="Save" />
<div class="simple-msg"></div>
</form>
And JS:
$(document).ready(function() {
$(".simple").click(function() {
var $ajaxForm = $(this).parents('form');
var $simpleMsg = $ajaxForm.find('simple-msg');
$ajaxForm.submit(function(e) {
$simpleMsg.html("<img src='ajax/profile/ajax-loader.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: "ajax/results/comment.php?id=" + $ajaxForm.data('sn'),
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$simpleMsg.html('' + data + '');
},
error: function(jqXHR, textStatus, errorThrown) {
$simpleMsg.html('<font color="red">Failed to save<br/>textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</font><span class="icon icon-color icon-close"></span>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$ajaxForm.submit(); //SUBMIT FORM
});
});

Ajax POSTs data inspite of false Twitter bootstrap form validation

I am trying to submit a form and send the data to my php function with Ajax. The problem is that, When I send data without ajax call and just using form action, My form validation works, but when I want to use Ajax, Form will be submitted without being validated. Here is my code:
html:
<form novalidate="" class="form-horizontal">
<div class="control-group">
<label for="email" class="control-label">Email address</label>
<div class="controls">
<input type="email" required="" id="email" name="email">
<p class="help-block">Email address we can contact you on</p>
</div>
</div>
<div class="control-group">
<label for="emailAgain" class="control-label">Email again</label>
<div class="controls">
<input type="email" name="emailAgain" id="emailAgain" data-validation-matches-message="Must match email address entered above" data-validation-matches-match="email">
<p class="help-block">And again, to check for speeling miskates</p>
</div>
</div>
<button id="button" class="button" type="submit" name="submit">Check your
</form>
Ajax:
$(document).ready(function () {
$(function () {
$("#button").click(function () {
$('.error').hide();
// Process form
var email = $("input#email").val();
var emailagain= $("input#emailagain").val();
var dataString = 'email=' + email + '&emailagain=' + emailagain;
$.ajax({
type: "POST",
url: "send_email.php",
data: dataString,
success: function (data) {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("Thank you ")
});
}
});
return false;
});
});
});
I also tried submitHandler: function(form){} with Ajax call, but in that case, my success function in Ajax call won't work and it seems that the data will be sent through GET method instead of POST! weird!!! Thanks in advanced!
Ok you have a submit button and on clicking this you are doing some ajax, so you need to use event.preventDefault()
Here how the code should be and it should work, also check for any syntax error in your code. Below is the code I just tested and worked on my linux box.
<script>
$(document).ready(function () {
$(function () {
$("#button").click(function (x) {
x.preventDefault(); // lets stop the default behaviour which is submit
$('.error').hide();
// Process form
var email = $("input#email").val();
var emailagain= $("input#emailagain").val();
var dataString = 'email=' + email + '&emailagain=' + emailagain;
$.ajax({
type: "POST",
url: "send_email.php",
data: dataString,
success: function (data) {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("Thank you ");
}
});
});
return false;
});
});
</script>

How to submit and validate a form via ajax

Please I am trying to simultaneously submit and validate my form to my database through the use of Ajax, but it is not working for me.
Here is my jquery
$(document).ready(function(){
$(".button").click(function(){
$("#myform").validate();
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: { firstname: $("#firstname").val()},
success: function(){
$('#message').html(data);
}
});
return false;
});
});
The problem is when I submit the form,the Ajax form submit to itself.
Please What is the right way to use the jquery validate and $.ajax together?
Pass data as a parameter in your success function:
success: function(data){
Your success function won't do anything because you haven't defined data
Try this (working for me as expected):
HTML Form:
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/css/screen.css" />
<script src="http://jquery.bassistance.de/validate/lib/jquery.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script>
// JQuery Script to submit Form
$(document).ready(function () {
$("#commentForm").validate({
submitHandler : function () {
// your function if, validate is success
$.ajax({
type : "POST",
url : "process.php",
data : $('#commentForm').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
});
</script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required />
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required />
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url" />
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</fieldset>
</form>
<div id="message"></div>
PHP Code:
<?php
echo $_POST['email'];
?>
You forget to pass the response
$(document).ready(function() {
$(".button").click(function() {
//check the validation like this
if ($("#myform").valid()) {
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: {
firstname: $("#firstname").val()
},
//you forget to passs the response
success: function(response) {
$('#message').html(response);
}
});
return false;
}
});
});
First of all, why would you submit form if validation is not passed?
Try this, if validate really validates:
$(function(){
$(".button").click(function(){
var myform = $("#myform");
if (myform.validate()) {
$.post("process.php", myform.serialize(), function(data){
$('#message').html(data);
});
}
return false;
});
});

jQuery making a post request and retrieving result

So I have a test input and a submit button. I want to send the data via jQuery and retrieve the result from the post request and then display the value that the post request returns, without refreshing the page.
Here is my html:
<div id="middle">
<form id="searchForm" action="/">
<input placeholder="E.g. http://www.google.co.nz" id="url" type="text" name="forward_to"/>
<input id="button" type="submit" name="shorten" value="Go"/>
</form>
<div id="result"></div>
</div>
Here is my php
if($query) {
print("<div id='content'>http://www.website.co.nz/u/$short</div>");
} else {
print("<div id='content'>Error</div>");
}
Is there anyway to do this?
$(document).ready(function(){
$('#button').click(function(e){
e.preventDefault();
$.ajax({
type: 'post',
url: '/',
data: { query: $('#url').val() },
success: function(data) {
$("#result").html(data);
},
error: function() {
$("#result").html("Some error occurred.");
}
});
});
});

Categories