AJAX does not respond to form submission - javascript

I wrote a toy program to learn AJAX, which is to submit the user registration form to web server, however, the program on the server side cannot receive the data. I guess the error is on the following JS code using jQuery:
$(document).ready(function() {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
},
registerResults: function() {
console.log("register success!");
} // end of registerResults
}); // end of ready
The corresponding html form is as following:
<form class="form-horizontal" role="form" id='registerForm' method='POST' action="/admin/user/signup">
<div class="form-group">
<label class="col-sm-3 control-label" for="fullname">Fullname: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="fullname" name='fullname' placeholder="Full Name" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="username">Username: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="username" name='username' placeholder="Username" />
</div>
</div>
<div class="form-group">
<input type='submit' value="Submit" class="register-form-button" form='user-create-form' />
</div>
</form>
can someone help me with my JS code using jQuery? Thanks a lot!

Like Felix said, your JavaScript syntax is invalid. Open up the JS console and refresh the page, and you'll see syntax errors.
Here's a shot at fixing it:
$(document).ready(function () {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData)
.done(registerResults)
.fail(registerError);
});
function registerResults() {
console.log("register success!");
}
function registerError() {
console.log("There was an error");
}
});

The registerResults function was a namespace function based on the formatting, but you only need a standard function like the below.
$(document).ready(function () {
$('#registerForm').submit(function () {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
});
function registerResults() {
console.log("register success!");
} // end of registerResults
}); // end of ready

Related

Native checkout WooCommerce - AJAX issue

I am developing a custom plugin for WooCommerce using viva payments. The documentation is here. It will be a native plugin
https://github.com/VivaPayments/API
The issue
Currently I have to dequeue the wc-checkout script to get it to work
wp_dequeue_script( 'wc-checkout' );
The reason for dequeue is that viva uses a card handler, and using onblur events makes XHR requests to viva. Looking in the network tab the XHR request called is
https://demo.vivapayments.com/api/cards/installments?key=mykey
and the response is {"MaxInstallments":0}
If i don't deqeue the script this request isn't made. If the request isn't made when I try and get the token I get served an error saying "Expiration date could not be parsed"
Here is the jscode
function getToken(){
VivaPayments.cards.requestToken( function(){
});
}
function tokenMyFunction() {
VivaPayments.cards.requestToken( function(){
//do something?
});
}
$(document).ready(function (){
if (viva_params.testMode === '1'){
var url = "https://demo.vivapayments.com"
} else {
url = "https://www.vivapayments.com"
}
VivaPayments.cards.setup({
publicKey: viva_params.publishableKey,
baseURL: url,
cardTokenHandler: function (response) {
//console.log(response)
if (!response.Error) {
//console.log(response.Token)
$('#hidToken').val(response.Token);
return false;
}
else{
console.log(response);
alert(response.Error);
return false;
}
},
installmentsHandler: function (response) {
if (!response.Error) {
if (response.MaxInstallments == 0)
return;
$('#drpInstallments').show();
for(i=1; i<=response.MaxInstallments; i++){
$('#drpInstallments').append($("<option>").val(i).text(i));
}
}
else
alert(response.Error);
}
});
});
Here is the viva js from their server that is used
https://demo.vivapayments.com/web/checkout/js
Here is the form
<form action="index.php" method="POST" id="payment-form">
<div class="form-row">
<label>
<span>Cardholder Name</span>
<input class="form-field" type="text" size="20" name=”txtCardHolder” autocomplete="off" data-vp="cardholder"/>
</label>
</div>
<div class="form-row">
<label>
<span>Card Number</span>
<input class="form-field" type="text" size="20" maxlength="16" name=”txtCardNumber” autocomplete="off" data-vp="cardnumber"/>
</label>
</div>
<div class="form-row">
<label>
<span>CVV</span>
<input class="form-field" type="text" name=”txtCVV” size="4" autocomplete="off" data-vp="cvv"/>
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YYYY)</span>
<input type="text" size="2" class="form-field" name=”txtMonth” autocomplete="off" data-vp="month"/>
</label>
<span> / </span>
<input type="text" class="form-field" class="lukeexpiry" size="4" name=”txtYear” autocomplete="off" data-vp="year"/>
</div>
<div class="form-row">
<label>
<select id="drpInstallments" value="0" name="drpInstallments" style="display:none"></select>
</label>
</div>
<div class="form-row">
<button type="button" onclick="getToken()">Get Token</button>
</div>
<input type="hidden" name="OrderId" value="146228" /> <!--Custom Field-->
<input type="hidden" name="hidToken" id="hidToken" /> <!--Hidden Field to hold the Generated Token-->
</form>
Like I said:
When I dequeue the wc-checkout, viva makes the request fine to api/cards/instalments and thus subsequently when I call tokenMyFunction() gets the token fine
If I don't dequeue I get an error about expiration on token request
How can I let viva still make requests alongside the wc-checkout script, or what in the hell is that call to instalments doing?
Why does that impact the token request. I can't see anywhere where the response {"MaxInstallments":0} is used again?
Any provided help is welcome.

Jquery Not Sending the Form to HTTP

I'm having some problems with Jquery/Ajax.
This is my code for the form :
<form class="form-auth-small" method="POST" id="form" enctype="multipart/form-data">
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Email</label>
<input type="email" class="form-control" name="email" value="samuel.gold#domain.com" placeholder="Email">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Name</label>
<input type="text" class="form-control" name="name" value="John">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Phone</label>
<input type="text" class="form-control" name="phone" placeholder="938434928">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only"></label>
<input type="password" class="form-control" name="password" placeholder="****">
</div>
<div class="form-group">
<input name="image" type="file" />
</div>
<button type="submit" id="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</form>
And this is my code to AJAX/Jquery:
<script>
$(".submit").on("click", function(e) {
var form = $("#form");
// you can't pass Jquery form it has to be javascript form object var formData = new FormData(form[0]);
console.log(formData);
$.ajax({
type: "POST",
url: '/user/signup/',
data: formData,
contentType: false, //this is requireded please see answers above processData: false, //this is requireded please see answers above //cache: false, //not sure but works for me without this error: function (err) { console.log(err);
success: function(res) {
console.log(res);
},
});
});
</script>
When i do console.log to check that from form i don't receive any value, and when i check in network i dont see any HTTP callback.
Your code doesn't work because you were using the class selector token . (dot) instead of the id selector token # hashtag. Further details can be found on the documentation
Change this instruction
$(".submit").on("click", function(e) // …
to
$("#submit").on("click", function(e) // …
You dont have submit class. You have id="submit"
$("#submit").on("click", function(e) {
Use this and it should work.
Also change type="submit" to type="button" or in your js code you need to add
e.preventDefault();

Why does my form submit and ignore validation?

I am trying to figure out why jquery validation does not stop my form from being submitted? When the submit button is pressed the form posts correctly but seems to ignore the validation error (This field is required) even if the input field is left blank.
The form
$(document).ready(function() {
$("#message").hide();
//Define your validation rules.
$(function() {
$("#myform").validate({
});
$("#submitButtonId").on("click", function(e) {
var formdata = $("#myform").serialize();
//Post form data
$.post('php_includes/simple_insert.php', formdata, function(data) {
//Process post response
$("#message").html(data);
$("#message").fadeIn(500);
$("#message").fadeOut(500);
});
//Reset Form
$('#myform')[0].reset();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<form class="form-inline" action="" id="myform" method="post">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="bill_cost"></label>
<div class="col-md-8">
<input id="bill_cost" name="bill_cost" type="text" placeholder="Bill Cost" class="form-control input-lg" required>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit1"></label>
<div class="col-md-4">
<button type="submit" id="submitButtonId" name="submit1" class="btn btn-primary btn-xl">Submit</button>
</div>
</div>
</form>
Try this, use submitHandler to do other things for a valid form:
$("#myform").validate({
submitHandler : function() {
var formdata = $("#myform").serialize();
//Post form data
$.post('php_includes/simple_insert.php', formdata, function(data){
//Process post response
$("#message").html(data);
$("#message").fadeIn(500);
$("#message").fadeOut(500);
});
//Reset Form
$('#myform')[0].reset();
}
});
Remove a Required tag in bill cost text box.then you check the validation is ignored

Ajax function reloads the page with some parameter on response

I am working on an application where user submit his/her information in tabs...
After .onclick() function, data is submitted to action and saved correctly and returned "success" successfully redirect user to login page...
I have returned two responses so far, "success" and "fail"
But the problem really is, when returning "false"...console.log shows the response correctly, although the work i'd like to perform on "fail" isn't really working..and page reloads with some parameters(i will show it in snapshot)....
Html
<form class="form-horizontal" id="default" name="myform">
<fieldset title="Step1" class="step" id="default-step-0">
<div class="form-group">
<label class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="email" class="form-control" id="Email1" required>
<label id="err1" class="col-lg-6 control-label" "></label>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" name="password1" class="form-control" id="password1" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Confirm Password</label>
<div class="col-lg-10">
<input type="password" name="confirmpassword1" class="form-control" id="confirmpassword1" required>
<label id="passMatch" class="col-lg-6 control-label""></label>
</div>
</div>
</fieldset>
<fieldset title="Step 2" class="step" id="default-step-1">
//some other input fields on 2nd tab
</fieldset>
<input type="button" class="finish btn btn-danger" value="Save" id="btnSubmitAll" />
</form>
Ajax
<script>
$("#btnSubmitAll").click(function (event) {
event.preventDefault();
var Email = $('#Email1').val();
var password = $('#password1').val();
var confirmpassword = $('#confirmpassword1').val();
$.ajax({
type: "POST",
url: '#Url.Action("Submit", "Home")',
dataType: "JSon",
async: false,
data: {"Email": Email, "password": password, "confirmpassword": confirmpassword},
success: function (data) {
if (data == "success")
{
window.location.href = '#Url.Action("login","Home")';
console.log(data);
}
else {
$('#err1').html("Email Exist");
console.log(data);
}
},
error: function (data, jqXHR, exception) {
//some errors in if/else if/else
}
}
});
});
</script>
Please remember, when data == "success", all things go right(returns success after successfull record insertion), but when "fail" returned, console shows it correctly but label not updated with the message and also the whole page reloads with some parameters from the form inputs as can be seen below...
InAction
if (objIdHelper.IsUserExist(Email))
{
return this.Json ("fail");
}
else
{
//some process
return this.Json ("success");
}
I am surely missing some logic or doing something stupid, please help....
Any kind of help will be appreciated...thanks for your time
Check for the argumet passed in the success callback..Also note that you have wrong understanding for error callback. It wont execute if there are any errors in success callback conditions. It is to handle network errors.
Your if statement if (data == "success") uses data instead of data1 like the function specifies.

Meteor.call method not found

I am working my way through the Microscope project in Discover Meteor and I have hit a problem. I am getting a 'Method not found' error for the following code:
HTML Template - microscope/client/templates/posts/post_submit.html
<template name="postSubmit">
<form class="main form">
<div class="form-group">
<label class="control-label" for="url">URL</label>
<div class="controls">
<input name="url" id="url" type="text" value="" placeholder="Your URL" class="form-control"/>
</div>
</div>
<div class="form-group">
<label class="control-label" for="title">Title</label>
<div class="controls">
<input name="title" id="title" type="text" value="" placeholder="Name your post" class="form-control"/>
</div>
</div>
<input type="submit" value="Submit" class="btn btn-primary"/>
</form>
JS - microscope/client/templates/posts/post_submit.js
Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
var post = {
url: $(e.target).find('[name=url]').val(),
title: $(e.target).find('[name=title]').val()
};
Meteor.call('postInsert', post, function(error, result) {
// display the error to the user and abort
if (error)
return alert(error.reason);
Router.go('postPage', {_id: result._id});
});
}
});
I am not sure how to debug this as I am getting no errors in the console. Please can anyone suggest where I am going wrong?
Very likely that you need to add the method postInsert to the server side. If you're following along in Discover Meteor, they do that in the next section - https://book.discovermeteor.com/chapter/creating-posts
For example, you put the method in a file called lib/collections/posts.js like this
Meteor.methods({
postInsert: function(postAttributes) {
check(Meteor.userId(), String);
check(postAttributes, {
title: String,
url: String
});

Categories

Resources