I have a login form that is working in a kinda same way I don't know why this won't work. When I press 'Criar' it does nothing, it doesn't even change the text of that Button to 'Loading ...' as I have stated on beforeSend function. I started using Jquery so sorry if it is a stupid mistake!
Form
<form id="criarSubCategoria-form" class="form-horizontal" role="form" action="criarCategoria.php" method="post">
<div class="col col-lg-4">
<label for="nome">Nome:</label>
<input type="text" class="form-control" id="nome" name="nome">
</div>
<br>
<div class="form-group margin-top-pq">
<div class="col-sm-12 controls">
<button type="button" class="btn btn-primary" name="btn-criarSubCategoria" id="btn-criarSubCategoria">
Criar
</button>
</div>
</div>
</form>
click Function
$('document').ready(function(){
$("#btn-login").click(function(){}); // this one is working so I didn't put all the code here
$("#btn-criarSubCategoria").click(function(){
var data = $("#criarSubCategoria-form").serialize();
$.ajax({
type : 'POST',
url : '../functions/criarCategoria.php',
data : data,
dataType: 'json',
beforeSend: function()
{
$("#btn-criarSubCategoria").html('Loading ...');
},
success : function(response){
if(response.codigo == "1"){
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'none')
}else{
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'block')
$("#mensagem").html('<strong>Erro! </strong>' + response.mensagem);
}
}
});
});
});
jQuery is not define. Or use jQuery instead of $ will works.
Change 1st line
jQuery(document).on("click", "#btn-criarSubCategoria", (function(e, $){
Try using this as your click function
$(document).on("click", "#btn-criarSubCategoria", (function(e){
var data = $("#criarSubCategoria-form").serialize();
e.preventDefault();
$.ajax({
type : 'POST',
url : '../functions/criarCategoria.php',
data : data,
dataType: 'json',
beforeSend: function()
{
$("#btn-criarSubCategoria").html('Loading ...');
},
success : function(response){
if(response.codigo == "1"){
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'none')
}else{
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'block')
$("#mensagem").html('<strong>Erro! </strong>' + response.mensagem);
}
}
});
});
Hope this gets your work done.
Related
Apparently in the DOM have changed the values, even changed the ID of the form with the idea that the script no longer has effect but when you click Publish, nothing happens. Searching I tried to use "prop" instead of "attr" but it still does not work. I think it's because of the "e.preventDefault ()". But I do not know how to disable it. This is my code.
As you can see once the request is sent, the input and the "send" button are deactivated and when the values are received, they change the id of the form, the id and name of the button and it is renamed "Publish".
<script>
jQuery(function($){
var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
$('[id^="form-search"]').on('submit', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://localhost/ladoserver/getapi.php',
data : $(this).serialize(),
cache: false,
beforeSend: function(){
$('input#keyword').prop('disabled', true);
$('button#search').prop('disabled', true);
$('#resuls').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
}
}).done(function(data) {
$('#results').html(data);
$('input#keyword').prop('value', 'PUBLISH DATA');
$('button#search').prop({disabled: false, id:'publish', name:'publish'}).html('Publish');
$('span#help').hide();
$('[id^="form-search"]').prop('action','publish.php');
$('[id^="form-search"]').prop('id', 'form-publish');
var countResults = $('input#total_data').val();
for (var i = 1; i <= countResults; i++) {
$('#lista>select').clone().prop({ id: "cat_"+i, name: "cat_"+i}).appendTo('.category_'+i);
}
$('#lista').remove();
});
});
});
</script>
Here my html
<form action="" method="post" class="form-search" id="form-search">
<fieldset>
<!-- Form Name -->
<legend>Name</legend>
<div class="form-group">
<input id="keyword" name="keyword" required="" type="text">
<button id="search" name="search" class="btn btn-success boton">Search</button>
<span class="help-block" id="help">Help</span>
<div id="lista" style="display:none">Test</div>
</div>
</fieldset>
<div id="result"></div>
</form>
Here a fiddle showing that happened (check DOM).
JSFiddle.net
//var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
// when the action is plugin url.
$(document).on('submit','[id^="form-search"]', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://localhost/ladoserver/getapi.php',
data : $(this).serialize(),
cache: false,
beforeSend: function(){
$('input#keyword').prop('disabled', true);
$('button#search').prop('disabled', true);
$('#resuls').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
}
}).done(function(data) {
$('#results').html(data);
$('input#keyword').prop('value', 'PUBLISH DATA');
$('button#search').prop({disabled: false, id:'publish', name:'publish'}).html('Publish');
$('span#help').hide();
$('[id^="form-search"]').prop('action','publish.php');
$('[id^="form-search"]').prop('id', 'form-publish');
var countResults = $('input#total_data').val();
for (var i = 1; i <= countResults; i++) {
$('#lista>select').clone().prop({ id: "cat_"+i, name: "cat_"+i}).appendTo('.category_'+i);
}
$('#lista').remove();
});
});
// when the action point to publish.php === This is what you need
$(document).on('submit','[id^="form-publish"]', function(e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type : 'POST',
url : url,
data : $(this).serialize(),
cache: false,
beforeSend: function(){
// do your pre-processing
}
}).done(function(data) {
// do your post processing.
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form action="" method="post" class="form-search" id="form-search">
<fieldset>
<!-- Form Name -->
<legend>Name</legend>
<div class="form-group">
<input id="keyword" name="keyword" required="" type="text">
<input type ="submit" id="search" name="search" class="btn btn-success boton">Search</button>
<!-- change the button type to submit type -->
<span class="help-block" id="help">Help</span>
<div id="lista" style="display:none">Test</div>
</div>
</fieldset>
<div id="result"></div>
</form>
I am developing a login page for our mobile app using Phone gap. But whenever I clicked the Submit button, an error 'Cannot POST /' appears. Why is that so? Please see my code below.
index.html
<body>
<div class="main-info2">
<h3>Sign In</h3>
<div class="in-form">
<form id="login_form" method="post"">
<input type="text" placeholder="Username" required=" " id="email" />
<input type="password" placeholder="Password" required=" " id="password" />
<div class="check-sub">
<input type="submit" value="Login" id="login">
</div>
</form>
</div>
</div>
<div class="copy-right">
<p>Design by W3layouts</p>
</div>
</div>
<!-- //main -->
</body>
login.js
$(document).ready(function(){
do_login();
});
function do_login() {
$("#login").click(function () {
var email = $('#email').val();
var password = $('#password').val();
var dataString="email="+email+"&password="+password+"&login=";
if($.trim(email).length>0 & $.trim(password).length>0){
$.ajax({
type: 'POST',
url: "http://localhost:1234/cleverpro/login.php",
dataType: 'json',
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").html('Connecting...');},
success: function(data){
if(data == "success"){
console.log("hay nako!");
alert("hala");
}else if(data == "failed"){
$("#login").html('Login');
console.log("hastang sayupa");
alert("halajud");
}
}
});
}else{
return false;
console.log("walay sulod uy");
}
});
}
login.php
<?php
include "db.php";
if(isset($_POST['login'])){
$email=mysql_real_escape_string(htmlspecialchars(trim($_POST['email'])));
$password=mysql_real_escape_string(htmlspecialchars(trim($_POST['password'])));
$login=mysql_num_rows(mysql_query("select * from `user` where `email`='$email' and `password`='$password'"));
if($login!=0){
echo "success";
}else{
echo "failed";
}
}
?>
I didn't know where did I gone wrong with this. Please help me.
First of all it would be better to use on('submit', handler) instead on click. (see Whats the difference between onclick and onsubmit?)
When you clicks "Login", default form send action happens after your javascript code finishes. It means that form POST happens to 'action' of your form that is not set in your form and is '/' by default.
You need to preventDefault action, somethink like this
$('#login_form').on('submit', function(e) {
e.preventDefault();
//Your code
});
I am trying to custom mailchimp signup form.
I want to the form not got to the mailchimp landing page, after the form submit. I want it reload the form and display the message, if the submission success or failed.
I have tried what have been discussed on https://stackoverflow.com/a/15120409, but it is failed.
This my html & javascript for the form :
//newsletter -start
var $form = $('#mc-embedded-subscribe-form');
if ( $form.length > 0 ) {
$('form button[type="submit"]').bind('click', function ( event ) {
if ( event ) event.preventDefault();
register_newsletter($form);
return false;
});
}
function register_newsletter($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: {EMAIL:.find('#mce-EMAIL').val()},
//data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result == "success") {
$( "#mc-embedded-subscribe-form .form-group, #mc-embedded-subscribe-form button" ).remove();
$( "#mc-embedded-subscribe-form" ).append('<p>Pendaftaran Anda berhasil.</p>');
} else {
$( "#mc-embedded-subscribe-form .form-group, #mc-embedded-subscribe-form button" ).remove();
$( "#mc-embedded-subscribe-form" ).append('<p>Pendaftaran anda <strong>gagal</strong>.</p>');
}
}
});
}
//newsletter -end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-sub">
<div class="row">
<div class="col-md-24 col-sm-24 col-xs-24">
<div id="mc_embed_signup">
<p><strong>Daftar & Dapatkan VOUCHER 75,000<br/>serta penawaran spesial dari MatahariMall</strong></p>
<form action="http://mataharimall.us10.list-manage.com/subscribe/post-json?u=ce402de87bc4303ab82a36695&id=912ec37292&c=?" class="form-search-opps" id="mc-embedded-subscribe-form" method="post" name="mc-embedded-subscribe-form" novalidate="" role="search" target="_blank">
<div class="form-group">
<input class="form-control" id="mce-EMAIL" name="EMAIL" placeholder="Masukkan email Anda di sini" type="text" value="" />
</div>
<button class="btn btn-red pria" id="mce-GENDER-0" name="GENDER" type="submit" value="Pria">Pria</button>
<button class="btn btn-red wanita" id="mce-GENDER-1" name="GENDER" type="submit" value="Wanita">wanita</button>
</form>
</div>
</div>
</div>
</div>
If success, mailchimp will produce this :
?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."})
If failed, mailchimp will produce this :
?({"result":"error","msg":"0 - An email address must contain a single #"})
It seems like i cant get to serialize my form. I do get the first alert with lol, but not the second alert with pdata. Does anyone see whats wrong? Im trying to use ajax to send the data in the form. Down below is the script and the html code.
<html>
<head>
<script>
function dologin(event) {
event.preventDefault();
alert("lol");
var pdata = $('#form').serialize();
alert(pdata);
$.ajax({
type: 'POST',
data: pdata,
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
};
</script>
</head>
<body>
<h1>Logg inn</h1>
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="login" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-default">Logg inn</button>
</form>
<div class="login-help">
<p>Glemt passordet? Trykk her for å endre det.</p>
</div>
</body>
</html>
The problem with your code is, you are accessing event argument wheres there is no parameter passed to the function, so its triggering an error and submitting the form as normal form submission.
If you like to keep your implementation u can modify your code like bellow:
function dologin() {
alert("lol");
var pdata = $('#form').serialize();
alert(pdata);
$.ajax({
type: 'POST',
data: pdata,
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
return false;
};
and modify this line
<form id="form" onsubmit="dologin()">
to
<form id="form" onsubmit="return dologin()">
or can use the following way
$(document).ready(function() {
$('#form').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
data: $(this).serialize(),
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
});
});
And form tag should be then:
<form id="form">
Here is my form's markup
<form name="contactForm" id="contactForm" role="form">
<div style="width: 190px">
<div class="form-group">
<input type="text" placeholder="fullname" name="fullname" id="formFullname" class="form-control">
</div>
<div class="form-group">
<input type="email" placeholder="email" name="email" id="fromEmail" class="form-control">
</div>
<div class="form-group">
<input type="text" placeholder="company" name="company" id="fromCompany" class="form-control">
</div>
</div>
<div class="clear"></div>
<div class="form-group">
<textarea placeholder="message" name="message" id="formMessage" rows="3" class="form-control"></textarea>
</div>
<button class="btn btn-success" type="submit" name="submit" id="formSubmit">send</button>
</form>
Using jquery 1.10.2
And here is JS
var form = $('#contactForm');
form.submit(function () {
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $(this).serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
I know that function fires, tested with alert. But console.log doesnt return anything, and during ajax call I don't see anything in POST (Watching with firebug's XHR).
BTW: role="form" is because i'm using Twitter Bootstrap framework
What am I doing wrong?
UPDATE
data: $(form).serialize() didn't help also
If you try this :
form.submit(function () {
console.log("form ", $(this).serialize());
return false;
});
it works just fine. So I think the problem
form.on('submit',function () {
event.preventDefault();
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $("form").serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
Because $(this) in your code doesn't refer to the form but instead refers to jQuery on which the ajax method is called
Try the following code, but first modify your form HTML so that is has an "action" attribute. The nice thing about this code is that it can be used on any form which has a submit button and an action attribute. (i.e. it is not coupled to any specific IDs)
$(function() {
$('input[type="submit"]').click(function(event) {
event.preventDefault();
var form = $(this).closest('form');
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function() {
alert('Yay! your form was submitted');
})
.fail(function() {
alert('Uh oh, something went wrong. Please try again');
});
});
Cheers.