Ajax function reloads the page with some parameter on response - javascript

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.

Related

POST Ajax for multiple buttons in one form

I am creating one form that has Auth and Login buttons that is planned to handle sending out OTP and checking if OTP is valid respectively below.
I am following this Process a Form Submit with Multiple Submit Buttons in Javascript using below code, but when I get any button, javascript seems to be not working and I can't not get any console.log values. No error on the browser.
otplogin.html
<div id="otplogin">
<form class="form-horizontal" id="getotp" >
{% csrf_token %}
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" value='auth' class="btn">Auth</button>
</div>
</div>
<div class="control-group">
<label class="control-label" for="otp">OTP</label>
<div class="controls">
<input type="otp" name="otp" id="otp" placeholder="OTP">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" value='login' class="btn">Login</button>
</div>
</div>
</form>
</div>
<script type="text/javascript">
(function () { //the browser said the '$' as in the linked answer can not be recognized
$("#getotp btn").click(function (ev) {
ev.preventDefault()
if ($(this).attr("value") == "auth") {
console.log("CHECK 1");
$.ajax({
type:'POST',
url:'/getotp2',
data:{
username:$('#username').val()
,csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function server_response(response) {
console.log('POST1 success')
}
});
}
else if ($(this).attr("value") == "login") {
console.log("CHECK 2");
$.ajax({
type:'POST',
url:'/otplogin',
data:{
username:$('#username').val(),
otp:$('#otp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function server_response(response) {
console.log('POST2 success')
}
});
}
});
});
</script>
views.py
def otplogin(request):
if request.POST:
otpentered=request.POST.get('otp','')
if otpentered==otp:
return redirect('/main')
return render(request,'esearch/otplogin.html')
def getotp2(request):
logout(request)
username = otp = ''
if request.POST:
username = request.POST.get('username','')
otp = pyotp.TOTP('base32secret3232').now()
OTPEmail('You Auth',username,[],'Your auth is '+otp)
print ('POST'+username)
print ('POST'+otp)
return JsonResponse(json.dumps({'username':username,'otp':otp}),safe=False)
Appreciate any help on this
Your selection is wrong:
(function(){
$("#getotp btn").click(function (ev){...});}
Change to:
$(document).ready(function(){
$(".btn").click(function(ev){...});});
Or
$("#getotp .control-group .controls .btn").click(...

Multiple file upload using jquery serialization works only at the second call

I experience a strange problem:
Form ajax call with multiple files and form values works perfect, but only on the second call. First call ends up the the success: function(result) "else" condition. Second call works perfect and sends all data to the php. So I hit the submit button once and it shows up an empty error box and I hit the submit button again and everything works perfect.
How is that possible and how to solve that?
UPDATE #1: Found workaround, but not the solution. It works when I put if (result==="") { $(".form-application").submit(); } below the success function. But thats very dirty! ... and it upload all files twice! :-(
PROBLEM SOLVED David Knipe provided the solution!! Thank you so much!!
JQUERY:
$(".form-application").submit(function(e) {
e.preventDefault();
$("#btnSubmit2").text("Please wait...");
$("#btnSubmit2").attr("disabled", true);
var files = $('#files')[0].files;
var form = $(this);
var error='';
var formData = new FormData(this);
grecaptcha.ready(function() {
grecaptcha.execute('6Le4Qb0UAAAAAHUPcsmVYIk7zc4XCsiBnf6oE-fP', {action: 'create_comment'}).then(function(token) {
$('<input>').attr({
type: 'hidden',
value: token,
name: 'token'
}).appendTo('form');
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
error += "Invalid " + count + " Image File"
}
else
{
formData.append("files[]", document.getElementById('files').files[count]);
}
}
if(error == '')
{
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: formData,
processData: false,
contentType: false,
success: function(result) {
if (result == "0") {
$("#btnSubmit2").text("Thank you!");
$("#btnSubmit2").attr("disabled", true);
$(".output_message").text("");
$(':input','.form-application')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
$(".output_message").append("<div class='alert alert-success alert-dismissible fade show' role='alert'>We have received your application!</div>");
} else {
$(".output_message").text("");
$(".output_message").append("<div class='alert alert-danger alert-dismissible fade show' role='alert'>"+result+"</div>");
$("#btnSubmit2").attr("disabled", false);
$("#btnSubmit2").text("try again");
}
}
});
}
else
{
alert(error);
}
});
});
return false;
});
HTML:
<form class="form-application" id="applicationform" method="post" action="https://<?PHP echo $_SERVER['HTTP_HOST']; ?>/include/process-application.php" enctype="multipart/form-data">
<input type="hidden" name="crsf" value="<?=$_SESSION['crsf']?>"/>
<input type="hidden" name="crsf-expire" value="<?=$_SESSION['crsf-expire']?>"/>
<div class="space40"></div>
<h6>Name</h6>
<input name="name" type="text" class="form-control" placeholder="Your Name">
<div class="space30"></div>
<h6>Email</h6>
<input name="email" type="text" class="form-control" placeholder="Your Email Address">
<div class="space30"></div>
<h6>Instagram Name</h6>
<input name="instagram" type="text" class="form-control" placeholder="Your Instagram Name">
<div class="space30"></div>
<h6>City & Country</h6>
<input name="from" type="text" class="form-control" placeholder="Where do you live?">
<div class="space30"></div>
<h6>Tell us more about you</h6>
<textarea name="message" class="form-control" rows="3" placeholder="Write some details about you, so we know you better."></textarea>
<div class="space30"></div>
<h6>Upload some photos of yourself</h6>
<div class="file-field">
<div class="btn btn-aqua">
<input name="files" id="files" type="file" accepts="image/*" multiple>
</div>
<div class="file-path-wrapper">
</div>
<div class="space20"></div>
</div>
</div>
<div class="col-12 text-center">
<button id="btnSubmit2" type="submit" class="btn btn-full-rounded btn-aqua">Submit Application</button>
<div class="space10"></div>
<span class="output_message"></span>
</div>
</form>
PHP Script /include/process-application.php
<?PHP
echo "0";
?>
OK, I think I've figured this out. $('<input>').attr(...); sets the token attribute on a new <input> element. But this is after var formData = new FormData(this);, so the token doesn't get included in formData. Then I guess you get an authentication error, and I guess it does the authentication before it even gets to the PHP part. It would just be a HTTP401 response with no body, hence "". But then, on the second attempt, the <input> has already been created with the correct token, and this ends up being used to authenticate.
Either keep onsubmit or action. Remove action from form tag, it will work

Getting XMLHttpRequest erros on ajax Post

I have a modal in which there's a form that I want users to be able to submit an email with. I set up the ajax post like I usually would, however, the post keeps failing. When it does, I get the following two errors in the console.
Setting XMLHttpRequest.withCredentials for synchronous requests is deprecated
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
Interestingly, the email sometimes sends regardless of the errors, but sometimes it doesn't either.
Here is my Html:
<form class="cmxform" id="contactForm" >
<div class="row">
<div class="col-xs-6">
<label class="col-md-12 control-label" style="text-align: left;" >Name</label>
<div class="col-md-12">
<input required class="form-control" id="FromName" name="FromName" style="margin-bottom: 10px;" type="text" value=""/>
</div>
</div>
<div class="col-xs-6">
<label class="col-md-12 control-label" style="text-align: left;" >Email</label>
<div class="col-md-12">
<input required class="form-control" style="margin-bottom: 10px;" id="FromEmail" name="FromEmail" type="text" value=""/>
</div>
</div>
</div>
<label class="col-md-12 control-label" >Message</label>
<div class="col-md-12">
<textarea required class="form-control contact-message" cols="20" id="Message" name="Message" rows="2"></textarea>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-info" value="Submit" />
</div>
</form>
And my JS:
function sendMessage(messageData) {
$.ajax({
async: true,
url: '/api/SendMessageApi',
type: 'POST',
data: messageData,
success: function () {
},
error: function (ex) {
alert('there was an error');
}
});
}
$("#contactForm").submit(function () {
var name = $('#FromName').val();
var email = $('#FromEmail').val();
var message = $('#Message').val();
var messageData = { Name: name, Email: email, Message: message };
sendMessage(messageData);
});
Any help would be much appreciated!
To submit the form after ajax success, you can use:
function sendMessage(messageData) {
$.ajax({
context: this, // set context to the form
async: true,
url: '/api/SendMessageApi',
type: 'POST',
data: messageData,
success: function () {
this.submit(); // submit form on success
},
error: function (ex) {
alert('there was an error');
}
});
}
$("#contactForm").submit(function (e) {
e.preventDefault();
var name = $('#FromName').val();
var email = $('#FromEmail').val();
var message = $('#Message').val();
var messageData = { Name: name, Email: email, Message: message };
sendMessage.call(this, messageData); // set context to the form
});

AJAX does not respond to form submission

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

jQuery .submit() .ajax() have to click send button two times to get the correct response

I have a form with 5 fields that i am sending with AJAX to a PHP Script that does some simple validation and returns a string.
I have made a little jQuery script for the actual submission, and when i try to send the form i have to click the send button two times.
Update: Url to live site: http://www.dan-levi.no/new/#!/Kontakt
Here are some code:
HTML
<form id="contact_form" class="form-horizontal" action"includes/contact.php" method"post">
<div class="control-group">
<label class="control-label" for="contact_name">Ditt navn og evt. bedrift</label>
<div class="controls">
<input type="text" class="input-large" id="contact_name" name="contact_name" placeholder="Ditt navn og evt. bedrift" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_email">E-post</label>
<div class="controls">
<input type="email" class="input-large" id="contact_email" name="contact_email" placeholder="E-post" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_tel">Telefon</label>
<div class="controls">
<input type="tel" class="input-large" id="tel" name="contact_tel" placeholder="Telefon" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_subject">Emne</label>
<div class="controls">
<input type="text" class="input-large" id="subject" name="contact_subject" placeholder="Emne for melding" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_desc">Din beskjed</label>
<div class="controls">
<textarea rows="10" class="input-large" id="contact_desc" name="contact_desc" placeholder="Din beskjed"></textarea>
</div>
</div>
<div class="text-error pull-right" id="error_message"></div><br>
<input class="btn btn-large pull-right" type="submit" name="" value="Send" /><br>
</form>
javaScript
$(document).ready(function() {
$('#contact_form').submit(function(e) {
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
})
.done(function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
})
e.preventDefault();
});
});
PHP
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_tel = $_POST['contact_tel'];
$contact_subject = $_POST['contact_subject'];
$contact_desc = $_POST['contact_desc'];
if ($contact_name == '' || $contact_email == '' || $contact_tel == '' || $contact_subject == '' || $contact_desc == '') {
echo "empty";
die();
}
echo $contact_name.'<br><br>';
echo $contact_email.'<br><br>';
echo $contact_tel.'<br><br>';
echo $contact_subject.'<br><br>';
echo $contact_desc.'<br><br>';
I cant find out why i have to click the button two times, i have tried some trial and error, read the forum for answers. I tried to serialize the form outsite the submit function, i just cant get this to behave the way i want. All help is greatly appreciated.
Oh, worth to mention. The actual response is that the fields are empty (php validation) the first time i click, but the second time it works as it should.
Make the ajax call using a regular input button instead of a submit button.
$("#button").click(function () { ... ajax ... }
I'm not sure if it makes a difference but have you tried putting what you want to happen afterwards in a success callback?
$(document).ready(function() {
$('#contact_form').submit(function(e) {
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
success: function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
}
});
e.preventDefault();
});
});
I'm guessing it's because the default action (submit the form) is processing before your $.ajax request. Try making e.preventDefault() first in your submit callback.
$(document).ready(function() {
$('#contact_form').submit(function(e) {
e.preventDefault();
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
success: function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
}
});
});
});

Categories

Resources