Cannot POST / error when clicking Submit button - javascript

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
});

Related

post data on WebAPI after save in php Using ajax

I have created the code for save data in my custom table using Ajax which is working fine.
After that I want to post these data on the asp.Net API using js/jQuery. How I can post same data on the aps.net.
Here is my HTML form and JS code:
<div id="inline1" class="audit-form" style="display: none;">
<form class="infusion-form" id="infusion-form">
<h3 style="color: #002046;">Sign Up For a Free Capability Audit </h3>
<div class="dis_block clearfix">
<div class="form-group">
<label>First Name *</label>
<input required class="form-control" id="inf_field_FirstName" name="inf_field_FirstName" type="text" />
</div>
<div class="form-group">
<label>Last Name *</label>
<input required id="inf_field_LastName" name="inf_field_LastName" type="text" class="form-control" />
</div>
<div class="form-group">
<label>Email *</label>
<input required id="inf_field_Email" name="inf_field_Email" type="email" class="form-control" />
</div>
<div class="form-group">
<label>Confirm Email *</label>
<input required id="inf_field_Phone1" name="inf_field_Phone1" type="email" class="form-control" />
</div>
<div class="form-group" style="text-align: center;">
<input type="hidden" name="action" value ="save_procurement_data" />
<input type="submit" id="frm_basic_info" class="btn custom-btn" value="NEXT" />
</div>
</div>
</form>
</div>
JS Code is here
<script type = "text/javascript">
jQuery(document).ready(function() {
jQuery(document).on('click', '#frm_basic_info', function(e){
jQuery("#infusion-form").validate({
rules: {
inf_field_FirstName: "required",
inf_field_LastName: "required",
inf_field_Email: "required",
inf_field_Phone1: {
equalTo: inf_field_Email
}
},
messages: {
inf_field_FirstName: "Please enter your firstname",
inf_field_LastName: "Please enter your lastname",
inf_field_Email: "Please enter your email",
inf_field_Phone1: "Please enter your confirm email correct",
},
submitHandler: function (form) {
e.preventDefault();
var frmd = new FormData();
var save_data = jQuery('form').serializeArray();
jQuery.each(save_data,function(key,input){
frmd.append(input.name,input.value);
});
jQuery.ajax({
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: frmd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
return false;
//window.location.href = "<?php echo site_url(); ?>/about-your-organization";
}
});
}
});
});
});
</script>
In the alert I getting alert data saved success fully.
Simply add one more ajax method after saving in your php Url.
See, in your above ajax success method, check the status then post to Asp.Net Web Api, just like my bellow code,
success: function(data){
//Here you can check the data and call your Web Api. For example
if(data == "data saved success fully")
{
//Write an ajax method to post data to Web Api
$.ajax({
url: 'YourWebApiUrlHere',
data: frmd,
type:'Post',
success: function (data) {
//Show an alert message here that data saved in Web Api blah blah
if(data == "Your response from Web Api goes here")//Edit this message
alert("Data saved using Web Api");
else
alert("Failed to save data using Web Api");
}
error: function(xhr, status, error) {
alert(xhr.responseText); //This is the exception if any issue with server
}
})
}
else
alert("Your data haven't saved in Php Url. Check with server");
return false;
}
Hope it helps!

jQuery - Change action and form ID and use this

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>

Javascript code never loaded

I have a javascript code that I have hardcoded into my html file, but it never seems to load. My form sends data to a php file via post immediately without every going through javascript verification. Any ideas? Thanks!
<!DOCTYPE html>
<html>
<head>
<!-- Stylesheets - boostrap and get-shit-done, a free UI -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="styelsheet" type="text/css" href="css/get-shit-done.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">
<h1>Registration</h1>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$('#registration').on('submit', function(e){
var usernameValue = $("#username").val();
var passwordValue = $("#password").val();
var confirmationValue = $("#confirmation").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ usernameValue + '&password1='+ passwordValue + '&confirmation1='+ confirmationValue;
if(usernameValue==''||passwordValue==''||confirmationValue=='') {
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
</script>
</head>
<body>
<form id ="registration" action="register.php" method="post">
<fieldset>
<legend>Registration Details</legend>
<form class="form-inline">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" id="username" placeholder="Username" type="text"/>
</div>
<div class="form-group">
<input class="form-control" id="password" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<input class="form-control" id="confirmation" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<button class="btn btn-default btn-round" type="submit" id="submit">
<span aria-hidden="true" class="glyphicon glyphicon-log-in"></span>
Log In
</button>
</div>
</form>
</fieldset>
</form>
<div>
<p class="text-center">or login</p>
</div>
</body>
</html>
You need to wrap your $('#registration').on('submit', function(e){ }); with in a $(function(){ }); (or $(document).ready()) as it is currently binding before the document is ready -
<script>
$(function(){
$('#registration').on('submit', function(e){
...
[rest of your code]
...
});
});
</script>
Please try adding your script inside jquery document ready . Example
$( document ).ready(function() {
$('#registration').on('submit', function(e){
var usernameValue = $("#username").val();
var passwordValue = $("#password").val();
var confirmationValue = $("#confirmation").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ usernameValue + '&password1='+ passwordValue + '&confirmation1='+ confirmationValue;
if(usernameValue==''||passwordValue==''||confirmationValue=='') {
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});

MailChimp Ajax Integration

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 #"})

Form serialize issue

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.

Categories