I am trying to submit a form using ajax post.Before that i am checking that all the form data are correct, if so the form will be submitted.Can any body tell me why the form is not submitting ?
HTML:
<form id="formElem" name="formElem" action="" method="post">
<fieldset class="step">
<legend>Account</legend>
<p>
<label for="password">Password</label>
<input type="password" name="uPassword" id="uPassword" value="<?=$uPassword;?>" AUTOCOMPLETE=OFF />
</p>
<p>
<label for="password">Verify Password</label>
<input type="password" name="uVPassword" id="uVPassword" value="<?=$uVPassword;?>" />
</p>
<p class="submit">
<button id="registerButton" type="submit">Register</button>
</p>
</fieldset>
</form>
jQuery code :
$('#registerButton').bind('click', function () {
if ($('#formElem').data('errors')) {
alert('Please correct the errors in the Form');
return false;
} else {
$(function () {
$("#formElem").on("submit", function (event) {
event.preventDefault();
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
});
}); ///end of func
return true;
}
});
Why do you have event.preventDefault(); in the beginning of your submit function? It seems that that's the problem.
You don't need the click handler, in the submit handler you can check for the validity
jQuery(function ($) {
$("#formElem").on("submit", function (event) {
event.preventDefault();
if ($(this).data('errors')) {
return;
}
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
});
})
You can call ajax on click of button. For any error it will go in to the if condition otherwise submit the form successfully..
$('#registerButton').bind('click', function () {
if ($('#formElem').data('errors')) {
alert('Please correct the errors in the Form');
return false;
}
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
return true;
}); ///end of func
$(function() { /*code here */ }); That execute the function when the DOM is ready to be used. This means that this function is assigned to the event onDocumentReady that occurs only once (when the page loads), and you assign a function after this event, so never execute.
It's the same with this function $("#formElem").on("submit", function (event) {}); Do not tell her immediately but do you create a handle to the event onSubbmit.
Related
How can I send input values through AJAX on button click? My code is below. Thanks in advance.
while
{
<form class="commentform">
<input type="hidden" class="proid" name="proid" value="<?=$rr['id']?>">
<input type="text" class="form-control" name="comval" placeholder="Write a comment.." autocomplete="off">
<button class="btn btn-post" type="button">Post</button>
</div>
</form>
}
$(document).ready(function() {
$(document).on('click', '.btn-post', function(){
var thePostID = $(this).val;
$.ajax({
url: 'fetch_comments.php',
data: { postID: thePostID },
type: 'POST',
success: function() {
alert(data);
}
});
Firstly, the correct method is $(this).val(), not just $(this).val.
Secondly, you can simplify your code by getting the data from the closest form element using serialize(). Try this:
$(document).on('click', '.btn-post', function() {
var $form = $(this).closest('form');
$.ajax({
url: 'fetch_comments.php',
data: $form.serialize(),
type: 'POST',
success: function() {
alert(data);
}
});
});
$("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.
Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});
I have a form with
<form id=myform onsubmit=return validate();>
<input type=text id=name name=name>
</form>
In my javascript file I have
function validate(){
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (data.exists){
return false;
}
}
});
return true;
}
This Ajax code check if the returned data has value especially the data.exists. I would like to prevent submit form based on the value of exists.
This
if (data.exists){
return false;
}
does not really work.
Your problem occurs because of async ajax function call, it returns true before ajax data returns.
I haven't checked it, But you can try something like this:
function validate(){
var self = this;
self.preventDefault();
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (!data.exists){
self.submit();
}
}
});
return false;
}
$('#myform').submit(function() {
return false;
});
This should do the trick, now the form won't reload the page on pressing enter or a button.
EDIT:
Your form is also missing double-quotes
<form id="myform" onsubmit="return validate();">
<input type="text" id="name" name="name">
</form>
Solution:
I have changed my HTML and I have added onclick event than onsubmit
<form id="myform">
<input type="text" id="name" name="name">
<button type="submit" id="button" onclick="validate();">
</form>
Also in Javascript
I prevent the submit here
$("#button").on("click",function(event){
event.preventDefault();
});
Here is my function to check if not exists data so then submit form
function validate(){
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (!data.exists){
$('#myform').submit();
}
}
});
Been asking a lot of jquery questions lately, I'm trying my best to learn a lot about it.
Anyway, I am sending an Ajax HTTP request to a PHP page in order to make a login form without requiring a page refresh. Now since it may take some time to connect the database and get the login information etc..
Now I do have loading as a .html but how can I hide the loading data once data has loaded?
Tried to use a few functions but didn't seem to work.
Thanks so far, this site has helped me a lot through the learning process.
Here's the JavaScript:
$(document).ready(function() {
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
user_login: $('#user_login').val(),
pass_login: $('#pass_login').val()
}
}
function loading(e) {
$('#content').html('Loading Data');
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#field').keyup(function(e) {
if (e.keyCode == 13) {
var username = $('#user_login').val();
loading(e);
check(e);
}
});
$('#submit').click(function(e) {
if (e.keyCode != 13) {
loading(e);
check(e);
}
});
});
Here is the HTML:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="js/login.js"></script>
<div id="content"> Loading...</div>
<div id="field">
<input type='text' name='user_login' id='user_login' placeholder='eg: Mark#gmail.com'> <br>
<input type='password' name='pass_login' id='pass_login'> <br>
<input type="submit" name="submit" id="submit" value="Login">
</div>
function check(){
$.ajax({
url: 'ajax/check.php',
type: 'post',
error: function(){
alert('An error has occured.');
},
beforeSend: function(){
$('#content').show('slow').html('Loading');
//loading(e);
},
data: {user_login: $('#user_login').val(),pass_login: $('#pass_login').val()}, // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});
}
$('#submit').click(function(){
check();
});
$('#field, #field input').keyup(function(e){
var username = $('#user_login').val();
if (e.keyCode == 13) {
check();
}
});
Markup
<div id="field">
<input type='text' name='user_login' id='user_login' placeholder='eg:Mark#gmail.com'> <br>
<input type='password' name='pass_login' id='pass_login'> <br>
<input type="button" name="submit" id="submit" value="Login">
</div>
Good luck!!!
First of all, i'm not sure if your code will return a success. This code will help you find out if the response is not successfully. If you get a browser alert. It means you have a server side error. Its either the url path is wrong or your server response statuscode is 500 (Internal error).
$.ajax({
url: 'ajax/check.php',
type: 'post',
error: function(){
alert('An error has occured.');
},
beforeSend: function(){
$('#content').show('slow').html('Loading');
//loading(e);
},
data: getData(), // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});
Refactoring your code entirely will look like this. Choose first or second:
$.ajax({
url: 'ajax/check.php',
type: 'post',
error: function(){
alert('An error has occured.');
},
beforeSend: function(){
$('#content').show('slow').html('Loading');
//loading(e);
},
data: {user_login: $('#user_login').val(),pass_login: $('#pass_login').val()}, // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});
I'm trying to send post variables to php himself document via jQuery ajax, but after send, the post vars are not set.
the code:
if(isset($_POST['email']) && isset($_POST['pass'])){
do something
}
<form id="form_login_pv">
Email: <input type="text" name="email" id="email"><br>
Password: <input type="password" name="pass" id="pass">
<div class="send_login_button_pv">Login</div>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e){
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
});
</script>
why dont you try to use form submit jquery function.
if(isset($_POST['email']) && isset($_POST['pass']))
{
//do something
}
<form id="form_login_pv" action="<?php echo $_SERVER['PHP_SELF'] ?>">
Email: <input type="text" name="email" id="email">
Password: <input type="password" name="pass" id="pass">
<button type="submit" class="send_login_button_pv">Login</button>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e)
{
e.preventDefault(); // just to make sure it wont perform other action
$("#form_login_pv").submit(function(){
//afte server response code goes here
});
});
</script>
Make sure form must have action set.
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
Try this in jQuery ready event:
//you can also use an <input type="submit" value="login" /> instead ofusing a button!
$("#button_id").on("click",function(e){
$("#form_login_pv").submit();
return e.preventDefault();
});
$("#form_login_pv").submit(function(e) {
var email = $('input[name=email]').val();
var pass = $('input[name=pass]').val();
// validate given values here
// if bad value detected, output error and return false;
if(!email.test(YOUR REGEX HERE)) {
$('#error-message').text('Wrong E-Mail Format!');
return false;
}
if(pass.length<6) {
$('#error-message').text('Password to short! At least 6 Characters!');
return false;
}
$.ajax({
type: "POST",
url: "index.php",
data: {
email: email,
pass: pass,
},
success: function(response){
alert("mensaje enviado");
}
});
return e.preventDefault();
});
And don't forget to pervent the form from submitting via HTTP Post!
You can do this by returning false at the end of your button click event.
Or by using a method of your event object e, e.preventDefault();
I suggest to return e.preventDefault(); at the end of your click function!
You also can check if given variables are empty or validate them with javascript, before submitting via ajax!