Ajax submit an ajax loaded form - javascript

I load replies to comments asynchronously in php like in youtube comments.
The ajax handler for forms (ie reply forms) loaded like this is not working. e.preventDefault() is not working. The forms are submitted to the action page itself and page is redirected to action url. If i edit a reply. It works but page is redirected to the action url. This happens only for the ajax loaded replies. The same handler is used for regular comments and it works fine.
A comment :
A comment with loaded replies :
When a reply is edited it just goes to /path/to/submit.php and shows the value of json output like this
result on submitting a reply form
Ajax to show or hide replies:
//load or hide replies
function loadmore(id) {
var val = $('#' + id).data("value");
var count = $('#' + id).data("count");
$.ajax({
type: 'post',
url: '/path/to/submit.php',
data: {
replyof: val
},
success: function(response) {
var content = document.getElementById("show" + val);
content.innerHTML = response;
var clicknum = $('#' + id).data("clicknum");
$('#' + id).data("clicknum", 2);
if (!$("#show" + val).is(":hidden") && clicknum != 1) {
document.getElementById(id).innerHTML =
' View all ' + count + ' replies <i class="fas fa-angle-down"></i>';
$("#show" + val).hide();
} else {
document.getElementById(id).innerHTML =
'Hide all replies <i class="fas fa-angle-up"></i>';
$('#show' + val).show();
}
}
});
}
I use the same class for comments as well as replies and ajax submit the form to the same page /path/to/submit.php using
eg
<form class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
The form handler
$(".replyform").submit(function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});

The .replyform render by ajax so use on instead of traditional way
$(document).on("submit", ".replyform",function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});

I think your calling your form wrong. You need an id attribute. I don't think you can call it by it's class name like that.
<form id="myForm" class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
$("#myForm").submit(function(e) {
...rest of script.

Related

jQuery prevent submit of form inside of if statement

Sorry if there are some mistakes, but I am a total noob and I am also posting for the first time on StackOverflow.
I am trying to configure a submit form, that controls if the inserted PIN is right, and if so goes on with the submission. I did some online research and found out that with jQuery we can use to function event.preventDefault(), I tried to insert it inside my AJAX request but it looks like it doesn't stop the form from being saved.
The code looks like these:
function verifyOTP() {
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp" : otp,
"PIN" : PIN,
"action" : "verify_otp"
};
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
error : function(event) { event.preventDefault(); };
}
//if I insert "return false;" here the submit is always blocked
}
I checked on atom if the parenthesis are right and it looks like it is.
Any ideas how I should use the preventDefault()?
I also checked if the output of m_ajaxpinr.php is correct, and it is. I also tried like these but it still didn't work...
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
$("form").submit(function(event) {
if (response.type == 'success')
{
alert(response.type);
}
else if (response.type == 'error')
{
alert(response.type);
event.preventDefault();
}
});
as said in comment above ajax call is asynchronous, you need to complete cancel default action for the form or put event.preventDefault(); on the top function, then submit it in success function if it valid otp.
.val() will not return null, it return empty if no input.
$('#myForm').on('submit', verifyOTP);
function verifyOTP(e) {
e.preventDefault(); // note this
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp": otp,
"PIN": PIN,
"action": "verify_otp"
};
if (otp) { // mean not null, undefined, empty, false, 0
$.ajax({
//url: 'm_ajaxpinr.php',
url: 'https://httpbin.org/anything/test',
type: 'GET',
dataType: "json",
data: input,
success: function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
if(response.args.otp == 1234){
console.log('valid otp, continue submission')
$('#myForm').off('submit'); // remove submit event
$('#myForm').submit(); // then submit the form
}
else{
console.log('invalid pin,\nvalid pin: 1234');
}
},
error: function() {
console.log("server error, submission cancelled");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
console.log("otp maybe empty, submission cancelled");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<input id="contomovimentato">
<button>submit</button>
</form>

How to use two forms in the Ajax request?

var getLoginpasssystem = function(getPassForgotSystem,getLoginCheckSystem){
$(document).ready(function() {
$('#login' || '#lostpasswordform').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function(response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert('Ungültige Email oder Password!');
}
}
});
});
})
}
The question is how to use two forms in one request with ajax. In this code I used ||, but it doesn't work. I mean the #login form works well but the #lostpasswordform doesn't work. When I click on the button it reloads the page instead of giving an alert.
The reason for this is the way you do your jQuery selection. Selecting multiple elements is done like this: $( "div, span, p.myClass" )
In other words it should work if you replace $('#login' || '#lostpasswordform') with $('#login, #lostpasswordform')
You can read more in detail about this in the jQuery docs
elector be used to select multiple elements. $("#login,#lostpasswordform").submit()
Use below code :
var getLoginpasssystem = function(getPassForgotSystem,getLoginCheckSystem){
$(document).ready(function() {
$("#login,#lostpasswordform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function(response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert('Ungültige Email oder Password!');
}
}
});
});
})
}

select child at beginning of function jquery

I can't appear to select the child form of a div I have for some reason.
For the matter, I am trying to find a way that I can have a function select the child form of a div since I have it changing for a toggling function at my site.
$(document).ready(function(){
$("#soundToggle, #soundOffForm").submit(function(event){
/*var r = new XMLHttpRequest();
r.open("POST", "sessionsetter.php", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
r.send("a=1&b=2&c=3");*/
alert("post");
event.preventDefault();
$.ajax({
type: "POST",
url: "sessionsetter.php",
data: {
sound : '0',
},
success: function(data) {
//alert("Sound toggled successfully: " + data);
$('#soundToggle').load(location.href + " #soundOnForm");
},
error: function(data) {
alert("Error in processing request: " + data);
}
});
});
$("#soundToggle, #soundOnForm").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "sessionsetter.php",
data: {
sound : '1',
},
success: function(data) {
//alert("Sound toggled successfully: " + data);
$('#soundToggle').load(location.href + " #soundOffForm");
},
error: function(data) {
alert("Error in processing request: " + data);
}
});
});
});
Anyone have any suggestions on how I can make this a possibility? Thanks. When I don't select the child of a form, the handler is destroyed as I replace the form in my DOM.
The jquery binding will be lost if the Dom is reconstructed after page loads, you may want to use this:
Assumption here is #soundToggle is the div that contains form
$("#soundToggle, #soundToggle form").submit(function(event){
if($("#soundToggle form").attr('id') == "soundOnForm"){
//do on functionality
} else if($("#soundToggle form").attr('id') == "soundOffForm"){
//do off functionality
}
}

submit individual form in twitter bootstrap wizard

I am using twitter bootstrap from wizard, and i want to submit 4 form in wizard,
http://vadimg.com/twitter-bootstrap-wizard-example/examples/basic-formvalidation.html#
Below is my code on each next button press,
onNext: function (tab, navigation, index) {
if(index == 1) {
if(form_header.valid() === true) {
$('#report_header_fm').submit(function(){
console.log('test123');
$.ajax({
type: "POST",
url: baseURL + "index.php/addNewReport",
data: $("#report_header_fm").serialize(),
success: function(data)
{
console.log('test');
}
}); //Ajax end
});
}
else
{
return false;
}
}
handleTitle(tab, navigation, index);
},
I have form with 5 inputs and id=report_header_fm,
Now when i click on next, i can see form validation occurs but form does not get submitted, Note- I am not clicking on submit button but there is next button--
<input type="submit" class="btn green-haze" value="Save">
So what i want is to submit a form when clicked on next, here validation occurs when click on next but submit is not happening,
I could not see 'test123' in console,
In short, how do i submit form without hitting submit button?
Thanks,
Here is a list of things you can change here to make it work, hopefully. Try it out.
onNext: function (tab, navigation, index) {
var wizard = this;
if(index == 1) {
if(form_header.valid() === true) {
//below line are not needed, so comment it out
//$('#report_header_fm').submit(function(){
console.log('test123');
$.ajax({
type: "POST",
url: baseURL + "index.php/addNewReport",
data: $("#report_header_fm").serialize(),
success: function(data)
{
console.log('test');
//At this point you will need to call the show method with index of tab you want to move to.
wizard.show(2);
}
}); //Ajax end
//});
// this would run before the ajax completes
return false;
} else {
return false;
}
}
onNext: function (tab, navigation, index) {
if(index == 1) {
if(form_header.valid() === true) {
$.ajax({
type: "POST",
url: baseURL + "index.php/addNewReport",
data: $("#report_header_fm").serialize(),
success: function(data)
{
console.log('test');
this.show(2);
}
});
} else {
return false;
}
}
onNext: function (tab, navigation, index) {
if(index == 1) {
if(form_header.valid() === true) {
console.log('test123');
$.ajax({
type: "POST",
url: baseURL + "index.php/addNewReport",
data: $("#report_header_fm").serialize(),
success: function(data)
{
console.log('test');
//index of tab
// this will move to next tab only after getting successful response
$('#rootwizard').bootstrapWizard('show',1);
}
}); //Ajax end
//required so that control does not move to next tab unless response is fetched
return false;
} else {
return false;
}
}

Only send post/get if form values has changed

I want to prevent multiple ajax calls (user holds enter key down or multi presses submit or other)
I'm thinking, the best way is to use a var with the previous form post values and compare them at each click/submit.. Is it the same? : Then do nothing
But I don't know how to go about it
Here is my javascript/jquery:
$('form').submit(function() {
$theform = $(this);
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
Not very creative with naming vars here:
var serial_token = '';
$('form').submit(function() {
$theform = $(this);
if ($(this).serialize() === serial_token) {
console.log('multiple ajax call detected');
return false;
}
else {
serial_token = $(this).serialize();
}
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
You could combine this with a timeout/interval function which aborts the submit, but the code above should just compare the data in the form
If you have some kind of submit button, just add a class 'disabled' to it when you start the ajax call, and check if it is present before trying to make the call. Remove the class when the server gives a response. Something like:
...
$theform = $(this);
$button = $theform.find('input[type=submit]');
if ($button.hasClass('disabled')) {
return false;
}
$button.addClass('disabled');
$.ajax({
....
},
complete: function () {
$button.removeClass('disabled');
}
});
...

Categories