Site reloads when firing an AJAX-form-submit - javascript

I want to update my mySQL database with ajax. The browser should NOT reload or go to a different URL when I hit the submit-button.
My form looks like this:
<form class="directmsg_form" method="post" id="directmsg_form" name="directmsg_form">
<div class="form-group" id="directmsg_subject"></div>
<input class="form-control" style="display: none" id="directmsg_receiverid" name="directmsg_receiverid">
<div class="form-group">
<textarea class="form-control" id="directmsg_text" name="directmsg_text" placeholder="Nachricht"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default" name="directmsgsend_button" id="directmsgsend_button" style="font-size: 20px">
<span class="glyphicon glyphicon-send" style="font-size: 20px"></span> Nachricht senden
</button>
</div>
</form>
And here is the javascript-code which fires the AJAX:
document.getElementById("directmsgsend_button").addEventListener('click',function (){
var data = $("#directmsg_form").serialize();
$.ajax({
type : 'POST',
url : 'directmsg_send.php',
data : data,
beforeSend: function(){
$("#directmsg_button").html('<span class="glyphicon glyphicon-transfer"></span> übertrage Daten ...');
},
success : function(response){
alert(response);
}
});
return false;
});
After hiting the submit-button I get the javascript-alert like I should - and then the site reloads and I don´t know why.

Add event.preventDefault() to your function:
document.getElementById("directmsgsend_button").addEventListener('click',function (event)
{
event.preventDefault();
var data = $("#directmsg_form").serialize();
$.ajax({
type : 'POST',
url : 'directmsg_send.php',
data : data,
beforeSend: function(){
$("#directmsg_button").html('<span class="glyphicon glyphicon-transfer"></span> übertrage Daten ...');
},
success : function(response){
alert(response);
}
});
return false;
});

As pointed out in the comments, you should add add preventDefault() to your callback function in click event. Your code would look something like this.
document.getElementById("directmsgsend_button").addEventListener('click',function (event)
{
//will prevent default behavior, reloading page in this case
event.preventDefault();
var data = $("#directmsg_form").serialize();
$.ajax({
type : 'POST',
url : 'directmsg_send.php',
data : data,
beforeSend: function(){
$("#directmsg_button").html('<span class="glyphicon glyphicon-transfer"></span> übertrage Daten ...');
},
success : function(response){
alert(response);
}
});
return false;
});

Related

Enable next button ( to go to another tab) only if json response is true?

This is html form
<div class="tab-pane" id="step1">
<form method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);">
**DATA COMES HERE**
<div class="wizard-footer">
<div class="pull-right">
<button type="submit" class='btn btn-next btn-primary' name='next' value='Next'>Next</button>
</form>
</div>
DATA COMES HERE
My vue js script is
I have only added ajax request
$.ajax({
url: 'http://127.0.0.1:8000/post/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status)
{
alert("Success")
vm.pid=e.pid;
console.log(vm.pid);
}
else {
vm.response = e;
alert("Failed")
}
}
});
I need to move to next tab only if success. But now if anything happens, it is moving to next tab. How can I make button to move to next tab only if status is true. Only if alert message is success. I need to move to next tab. Please help me to solve the problem?
as mention from MRustamzade who have the right answer
1.add disabled on the button by default
<div class="tab-pane" id="step1">
<form data-parsley-validate="true" >
**DATA COMES HERE**
<div class="wizard-footer">
<div class="pull-right">
<button type="submit" class='btn btn-next btn-primary' disabled name='next' value='Next'>Next</button>
</form>
</div>
2.remove disabled only if e.success = true
$('form').submit(function(e){
var data = $(this).serializeArray();
var btn= $(this).find('.btn-next');
var btnText = btn.text();
$.ajax({
url: 'http://127.0.0.1:8000/post/',
data: data,
type: "POST",
dataType: 'json',
beforeSend: function(){
btn.prop('disabled', true).removeClass('.btn-primary').addClass('.btn-warning').text('wait');
},
success: function(e) {
if (e.status)
{
btn.removeClass('.btn-warning').addClass('.btn-success').text('success');
vm.pid=e.pid;
setTimeout(function(){
btn.prop('disabled',false).removeClass('.btn-success').addClass('.btn-primary').text(btnText);
},2000);
}
else {
btn.removeClass('.btn-warning').addClass('.btn-danger').text('failed');
vm.response = e;
setTimeout(function(){
btn.removeClass('.btn-danger').addClass('.btn-primary').text(btnText);
},2000);
}
},
error: function(e){
console.log(e); //for debug the error msg
btn.removeClass('.btn-warning').addClass('.btn-danger').text('error');
setTimeout(function(){
btn.removeClass('.btn-danger').addClass('.btn-primary').text(btnText);
},2000);
}
});
});

if/else in php script not working on ajax request

I'm working on a website with heavy Ajax, and I'm using codeigniter for building it.
I've got a form with post method, and this form is being posted using ajax request which call a function with if/else statement, like this:
if(isset($_POST['save']))
{
$data['phase'] = 'translating';
}
elseif(isset($_POST['submit']))
{
$data['phase'] = 'waiting_approve';
}
The if/else statement check which button is being clicked, and it works 100% after posting the data of the form in the usual way, but never works when posting it using ajax request.
My ajax request:
$('#workspace-content').delegate('form#article', 'submit', function(){
var that = $('form#article'),
url = that.attr('action'),
type = that.attr('method'),
data = {};
data = that.serialize();
$.ajax({
type: type,
url : url,
data : data,
dataType: 'json',
success: function(data){
$('#header-search-field').append(data.msg).delay(3000).fadeOut(500, function(){
var that = $(this);
that.html('').fadeIn();
});
}
});
return false;
});
Any suggestion or solution?!!
The HTML form:
<button id="save-article" type="submit" name="save" class="btn btn-info btn-xs pull-left">
<span class="glyphicon glyphicon-floppy-save"></span>
</button>
<input name="title" type="text" value="<?php echo $work->title;?>" class="form-control" id="title" placeholder="" />
<textarea row="10" name="article" class="form-control" id="article" placeholder=""><?php echo $work->article;?></textarea>
<button id="submit-article" type="submit" name="submit" class="btn btn-info btn-block">Send</button>
<input name="slug" type="hidden" value="<?php echo $work->slug;?>" />
When you submit a form normally, the button that you used to submit it will be included in the POST data. But when you submit with AJAX, and use that.serialize(), the POST data just includes the input fields -- the submit button isn't included. You need to attach your submit code to the buttons, so you can add the appropriate values to the data.
$('#workspace-content').on('click', 'form#article .btn', function(){
var that = $(this).closest("form"),
url = that.attr('action'),
type = that.attr('method'),
data = that.serialize();
data += '&' + this.name + '=1';
$.ajax({
type: type,
url : url,
data : data,
dataType: 'json',
success: function(data){
$('#header-search-field').append(data.msg).delay(3000).fadeOut(500, function(){
var that = $(this);
that.html('').fadeIn();
});
}
});
return false;
});

Form is not submitting in jQuery ajax success

I am making a simple form of single text input.I want to cross check from db that is it exist or not.So my html is
<form action="zoneAdd" method="post" id="zoneAdd" name="zoneAdd">
<div class="box-body">
<div class="form-group">
<label>Zone Name<span id="required">*</span></label>
<input type="text" class="form-control" name="zone_name" id="zone_name" placeholder="Enter Zone Name" />
<span id="zone_name_error"></span>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<input type="submit" class="btn btn-primary btn-flat btn-sm" name="submit" value="Submit"/>
</div>
</form>
and my javasript is
$('document').ready(function(){
$("[name=submit]").click(function(e){
e.preventDefault();
if ($('#zone_name').val().length <= 0) {
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Please enter Zone name!');
//isStepValid = false;
}
else if(!$('#zone_name').val().match(/^[a-zA-Z\s-, ]+$/)){
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Please use only alphabats!');
//isStepValid = false;
}else{
var data = {'zone':$('#zone_name').val()}
$.ajax({
type:"post",
data:data,
url:"<?php echo site_url('zone/checkZoneName');?>",
success:function(err){
if(err == 0)
{
console.log('hello');
$('#zone_name_error').html('');
$('#zone_name_error').removeClass("errMsg");
$('#zone_name_error').removeClass("errMsgDngr");
//document.forms["zoneAdd"].submit();
$('form#zoneAdd').submit();
//console.log($('form#zoneAdd').submit());
}
else
{
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Zone Name already existed!');
}
}
});
}
});
});
every thing is going right. My problem is my form is not submit in ajax success
I think problem in form action.
Specify exact path in the form action such that
<form action="<?php echo site_url('filenameWhereyouSubmit')?>" method="post" id="zoneAdd" name="zoneAdd">
You don't have a handler function on form submit and your ajax call
happens after $("[name=submit]").click().
You're submitting the form after ajax success:
success:function(err){
if(err == 0)
{
...
$('form#zoneAdd').submit();
...
}
}
but the submit is not ajax call, so try to handle the form
onsubmit.
something like this:
$('document').ready(function(){
$('form#zoneAdd').submit(function(e){
e.preventDefault();
// You checks code ...
var data = {
'zone': $('#zone_name').val()
};
$.ajax({
type:"post",
data:data,
url:"<?php echo site_url('zone/checkZoneName');?>",
success: function (err){
if(err == 0)
{
console.log('hello');
$('#zone_name_error').html('');
$('#zone_name_error').removeClass("errMsg");
$('#zone_name_error').removeClass("errMsgDngr");
}
else
{
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Zone Name already existed!');
}
}
});
});
});
Start form like this :
<form id="FORM-ID" method="post" action="">
For ajax submit
$(document).ready(function(){
$('#FORM-ID').submit(function(e) {
var myarray= array of all form values
var data = JSON.stringify(myarray);
e.preventDefault();
$.ajax({
type: "POST",
data: {value:data},
url: "URL TO SUBMIT",
success: function() {
//Sucess function
}
});
});

Disabling button on ajax submit

I have this button that I want to disable when my ajax is running, and then being enabled again once it's done.
My HTML:
<form name="send" class="stacked form-send-disable" id="form">
<label for="senderID">Your phone number here (senderID)</label>
<input type="tel" name="senderID" id="senderID" autofocus="on" class="input-1-2" placeholder="Your number" maxlength="9">
<label class="error" id="senderID_error" for="senderID">Please enter your own number here.</label>
<label for="recipient" id="recipient_label">Your recipient(s)</label>
<input type="text" name="recipient" id="recipient" class="input-1" maxlength="50" placeholder="e.g 748930493 - add multiple numbers by using a comma ' , '.">
<label class="error" id="recipient_error" for="recipient">You need to enter at least one number here.</label>
<label for="message">Write your message</label>
<textarea type="text" name="message" class="input-1" placeholder="(Write something clever..)" id="message"></textarea>
<label class="error" for="message" id="message_error">You can't send empty messages.</label>
<input type="submit" name="submit" class="button btn btn-green block disabled-btn" id="submit_btn" value="Send the message(s)">
</form>
ajax:
<---- Some form validation going on up here ------>
var dataString = 'recipient=' + recipient + '&message=' + message + '&senderID=' + senderID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$('#send-message').append("<div id='feedback'></div>");
$('#feedback').html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.append("")
.hide()
.fadeIn()
.delay(4000)
.fadeOut();
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
});
}
});
return false;
});
I tried to do the following in my document:
Jquery:
$('#form').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});
But nothing happens. I guess I have to somehow call this within the ajax, so that it applies to the button that way?
Thanks in advance.
UPDATE
$(':submit', this).prop('disabled', true);
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$('#send-message').append("<div id='feedback'></div>");
$('#feedback').html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.append("")
.hide()
.fadeIn()
.delay(4000)
.fadeOut();
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
}).always(function(){$(':submit', this).prop('disabled', false);});;
}
I updated with the above code (big thanks to A.Wolff), and my ajax request still works, however there is no change on the button, which i assume is because of lack of css for this particular state of the button, how do I go about this?
Thanks to the other replies, i will try them out.
I made a working demo that disables the form whilst the ajax request is happening. I hope its of some use. See: http://jsfiddle.net/EWkpR/
$("#form").on("submit", function(event) {
//stop the default submission:
event.preventDefault();
//create an alias to this form
$form = $(this);
//create the feedback element
$feedback = $("<div id='feedback'>Please wait...</div>");
$form.before($feedback);
//validate the form:
var valid = true;
/*[some form validation here]*/
//use jQuery's serialize to build the form submission params:
var dataString = $(this).serialize();
console.log(dataString);
//check if invalid
if(!valid){
//not valid. tell the user
$feedback.html("<p>Some message about invalid fields!</p>");
} else {
//valid.
$form.disable();//disable the form;
//do the ajax
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$feedback
.html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.fadeIn()
.delay(4000)
.fadeOut("normal",
function(){$form.enable();}//callback to fade the form back in
);
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
});
}
});
}
return false;
});
//plugin function to disable form fields
$.fn.disable = function(){
this.fadeTo(1,.5);
this.find("input").attr("disabled", true);
};
//plugin function to enable form fields
$.fn.enable = function(){
this.fadeTo(1,1);
this.find("input").removeAttr("disabled");
};
You can set the button as disabled before the AJAX runs and re-enable it once the ajax has completed.
$.ajax({
beforeSend: function() {
$("input[type=submit]", $("#form")).attr("disabled", "disabled");
},
...
complete: function () {
$("input[type=submit]", $("#form")).removeAttr("disabled");
}
});
Edit: I notice there is a class on the button disabled-btn if this needs to be added and removed as the button is disabled/re-enabled then you can do this by chaining the following to the above:
.addClass("disabled-btn");
...
.removeClass("disabled-btn");
I would assume if this is the case then the class should be removed from the actual element to start with.
You could use:
//using allias for nested ajax:
var _self = this;
$(':submit', _self ).prop('disabled', true);
//your nested ajax request
$.ajax(...).always(function(){$(':submit', _self ).prop('disabled', false);});

HTML/JQuery: Button submits once when it shouldn't at all

I'm using jQuery to allow the form to submit, so I don't want the form to submit on it's own.
Here's my form:
<form class="navbar-form navbar-right" id="signform">
<div class="form-group">
<input type="text" placeholder="Username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control">
</div>
<button id="signbtn" class="btn btn-success">Sign in</button>
</form>
Here's my JQuery code:
var signingIn = false;
$(document).ready(function() {
$('#signbtn').click(function() {
if (signingIn) return;
signingIn = true;
var img = $('<img id="loader" style="padding-left: 10px;" src="loader.gif"/>');
$(this).after(img);
var data = $('signform').serialize();
$.ajax({
url: '/logs',
type: 'post',
data: data,
done: function() {
$('#loader').remove();
alert('success');
}
});
});
});
Now when I go to the url: website.com/index.html and click Sign in, it refreshes the page (what I don't want at all) and goes to website.com/index.html? - Now when I click it again, nothing happens (exactly what I want all the time so my added elements through jQuery isn't lost).
You want to use jQuery ajax call like so:
$(document).on('click','button#signbtn', function(){
var $form = $('form#signform');
var url = $form.attr('action');
$.ajax({
type: "POST",
enctype: 'mutipart/form-data',
url: url,
data: $form.serialize(), // serializes the form's elements.
success: function(data){// whatever you want your code to do on success}
})
return false; // avoid to execute the actual submit of the form.
});
$(function() {
$( '#signform' ).submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function(result) {
// Do something on success
}
});
});
});

Categories

Resources