Why doesn't the preventDefault function work always? - javascript

I'm trying to create a quiz with PHP and Javascript.
After a user clicked for an answer, an ajax request starts and the result is been given in the response. If it was true, the clicked button gets a 'success' class and if false, a 'wrong' class.
After this the buttons are disabled and the user can click to the next question.
But the problem is, that after one or two questions, the javascript function doesn't work and the default action of the form is being called.
$(document).ready(function(){
// Get the form.
var form = $('#bilderquiz');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
e.preventDefault();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
, async: false
})
.done(function(response) {
var submittedAnswer = $("input[type=submit][clicked=true]");
var allAnswers = document.querySelectorAll( ".answerButton" );
alert(response);
if(response == 'trueAnswer'){
submittedAnswer.removeClass('wrongAnswer');
submittedAnswer.addClass('trueAnswer');
$(".answerButton").attr('disabled', true);
} else{
submittedAnswer.removeClass('trueAnswer');
submittedAnswer.addClass('wrongAnswer');
$(".answerButton").attr('disabled', true);
}
})
.fail(function(data) {
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
function setClicked(input){
$(input).parents("form").removeAttr("clicked");
$(input).attr("clicked", "true");
}
<div class="answerChar">A</div>
<form id="bilderquiz" action="includes/functions.php" method="post">
<button class="answerButton" type="submit" id="selection" name="selection" value="0" onclick="setClicked(this)">
<?php echo $questionData['answerButtons'][0] ;?>
</button>
</form>
</div>
<div class="col-sm-6">
<div class="answerChar">B</div>
<form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<button class="answerButton" type="submit" id="selection" name="selection" value="1" onclick="setClicked(this)">
<?php echo $questionData['answerButtons'][1];?>
</button>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="answerChar">C</div>
<form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<button class="answerButton" type="submit" id="selection" name="selection" value="2" onclick="setClicked(this)">
<?php echo $questionData['answerButtons'][2];?>
</button>
</form>
</div>
<div class="col-sm-6">
<div class="answerChar">D</div>
<form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<button class="answerButton" type="submit" id="selection" name="selection" value="3" onclick="setClicked(this)">
<?php echo $questionData['answerButtons'][3];?>
</button>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<button class="submitButton" type="submit" id="selection" name="selection" value="4" onclick="setClicked(this)">Nächste Frage</button>
</form>
</div>
</div>
My second problem is, that this lines also doesn't work:
submittedAnswer.removeClass('wrongAnswer');
submittedAnswer.addClass('trueAnswer');

Your forms need unique IDs, right now they are all id="bilderquiz"
Or you could use classes.
The php:
<form class="capture-me">...</form>
<form class="capture-me">...</form>
The JS:
$('form.capture-me').on('submit',function(e){ .....

Related

How to return second register form on submition?

I have a page with two registration forms individual and business type and individual type form is set as default the other form is hidden, it works fine. but when I switch it to second form and click on submit button it submits second form but returns to first form after submition even on errors it return to first form.
I want it to stay on second form on errors and after submition.
Here is my php :
if (isset($_POST["btnRegister"])) {
echo "Done";
}elseif (isset($_POST["btnbusiness"])) {
echo "Done";
}
HTML and js codes in my page:
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for(i = 0 ; i < radioName.length; i++){
document.getElementById(radioName[i].id.concat("Settings")).style.display="none";
}
document.getElementById(x.id.concat("Settings")).style.display="initial";
}
<div class="col-10 clmiddle">
<label for="production"><b>Individual</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development"><b> Business</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
</div>
First Form :
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second Form :
<div id="developmentSettings" style="display:none" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
EDIT: I changed JS to php, Here is the solution.
PHP codes (which get url):
$path = $_SERVER['REQUEST_URI'];
$Aurl = explode(",",$path);
for ($i=0; $i<count($Aurl);$i++){
$Burl = str_replace("?", "/", trim($Aurl[$i]));
}
$url = htmlspecialchars(basename($Burl));
$FormPostUrl = basename($path);
Html part :
Checkbox :
<div class="col-10 clmiddle" style="margin-top: 20px;">
<label for="production"><b>Individual</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php"); ?>" name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("register.php")){ echo 'checked="checked"';}?>>
<label for="development"><b>Business</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php?business");?>"
name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("business")){ echo 'checked="checked"';}?>>
</div>
First Form :
<?php if($url === htmlspecialchars("register.php")){?>
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second form:
<?php } elseif($url === htmlspecialchars("business")){ ?>
<div id="developmentSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
<?php } ?>
You can use PHP to control whether display:none is added to your divs or not. Use an if statement (or a ternary operator might be neater syntax in the context) to make the decision about what to echo. Since the default is to display the production settings form, we only need to check whether the other form has been submitted or not, in order to know whether to change that.
e.g. something like this (untested):
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" <?php echo (isset($_POST["btnRegister"]) ? "" : 'checked="checked"'); ?> />
and
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" <?php echo (isset($_POST["btnRegister"]) ? 'checked="checked"' : ""); ?> />
and
<div id="productionSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "style='display:none'" : ""); ?>>
and
<div id="developmentSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "" : "style='display:none'"); ?>>
P.S. Unless you've massively simplified these forms for the purpose of your example, they appear to be basically identical. It's questionable whether you actually need two separate forms at all. The only difference appears to be the choice between "individual" and "business" - that could be handled by a single form with a radio button to choose the type, which would then simplify how you handle the postback as well, and reduce the amount of duplicated code and HTML. Of course if you're actually capturing more distinct fields for these forms than you've shown, then these remarks don't really apply.

Hide form and show div

So I have this
<?php
if(isset($_POST['submit'])) {
$error = "test";
}
?>
<div id="first" class="1">
<form action="" method="post" id="myform">
<p>
<label for="textfield">Text Field:</label>
<input type="text" name="name" id="name">
<br>
<input type="submit" name="submit" formmethod="POST">
</p>
</form>
</div>
<div id="second" class="2" style="display:none">
<?php echo $error; ?>
</div>
<script>
$(document).ready(function() {
$("#myform").submit(function(e) {
e.preventDefault();
$("#first").hide();
$("#second").show();
});
});
</script>
So, everything is OK with javascript, the form is hiding, div is displaying, but the php isnt working. The form is submitting only to js and not to php.
You need an action, it's not doing anything because it's TOLD to not do anything
<form action="name_of_this_file.php" method="post" id="myform">
or
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" id="myform">
You have no php action handler listed.

How to hide an form after form is submitted

I am not that much good at programming. i am working on one feature, that is form hiding after the submit of form data. Here number of forms created dynamically. i need to hide the form once we submit the form data, to prevent multiple submission of form. here i used form inside div i also tried for div hiding. it is not working please let me know the solution.
<script>
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
});
function frmsubmit()
{
var frm = document.getElemetsByName('formdata')[0];
frm.submit();
frm.reset();
return false;
}
$('#submit_0').click(function() {
$.ajax({
url:"section.php?status=result",
data:$('#f_0').serialize(),
success:function(data)
{
alert(data);
$('#f_0')[0].reset();
}
});
});
// Haven written same code for submit_0 to submit_10
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Enter the values:</h3><br>
<ul class="nav nav-tabs">
<?php
foreach($clasarr as $temp)
{
?>
<li><a href="#<?php echo $temp; ?>"> <?php echo $temp; ?> </a </li>
<?php
}
?>
</ul>
<div class="tab-content">
<?php
$y=0;
foreach($clasarr as $temp)
{
?>
<div id="<?php echo $temp; ?>" class="tab-pane fade">
<form name="formdata" action="" method="post" class="form-horizontal" id="f_<?php echo $y; ?>">
<div class="col-md-offset-2 col-md-10">
<h3> CLASS: <?php echo $temp; ?></h3>
</div>
<input type="text" name="idr" id="idr" value="<?php echo $id; ?>" hidden>
<input type="text" name="clss" id="clss" value="<?php echo $temp; ?>" hidden>
<div class="form-group">
<label class="control-label col-sm-2" for="totalb">Budgeted #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="totalb" id="totalb" value="<?php echo $totalarr[$y]; ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="received">Received #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="received" id="received_<?php echo $y; ?>" onblur="getcsv(<?php echo $y; ?>),getupload(<?php echo $y; ?>),getexpected(<?php echo $y; ?>)"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="deleted"> Deleted data #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="deleted" id="deleted_<?php echo $y; ?>" onblur="getcsv(<?php echo $y; ?>),getupload(<?php echo $y; ?>),getexpected(<?php echo $y; ?>)"/ >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="csvno"> CSV Number #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="csvno" id="csvno_<?php echo $y; ?>" onload="getupload(<?php echo $y; ?>)">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="duplicate"> Duplicate #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="duplicate" id="duplicate_<?php echo $y; ?>" onblur="getupload(<?php echo $y; ?>),getexpected(<?php echo $y; ?>)" onclick="getupload(<?php echo $y; ?>)"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="upload"> Upload #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="upload" id="upload_<?php echo $y; ?>">
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-2">
<input class="btn btn-info" type="submit" name="submit" id="submit_<?php echo $y; ?>" value="submit" onclick="frmsubmit()">
<input class="btn btn-info" type="reset" name="Reset" value="Reset">
</div>
</div>
</form>
</div>
<?php
$y++;
}
You may not need both input type = "submit" and onclick event handler, the submit input will be enough.
Also there is a need to prevent default behaviour of the submit button since ajax is used to submit the form data.
Replace the input type "submit" with this
<input class="btn btn-info" type="submit" name="submit" id="someId" value="submit">
Also while dynamically creating the form use a class instead of id(presuming id is also dynamic so every new form creating will change the id)
<form name="formdata" action="" method="post" class="form-horizontal someFormClass"
id="someDynamicId">
// rest of the code
</form>
To prevent the default behaviour add event.preventDefault();.Inside the ajax success delegate the event of hiding the form from body
$('#submitButtonId').click(function(e) {
e.preventDefault();
var form = $(this).parents('form.someFormClass');
$.ajax({
//Rest of the code
success:function(){
$('body').find(form).hide()
}
})
});
Hopefully this pseudo code will be useful
A ridiculously simplified version of what you're trying to do. A form, in a div, with a jQuery on click hook that will hide the div on submit click.
$('#submit').click(function() {
$('#f_0').hide();
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="f_0">
<form name="formdata" action="" method="post" class="form-horizontal" id="f_1">
<input class="btn btn-info" type="submit" name="submit" id="submit" value="submit">
<input class="btn btn-info" type="reset" name="Reset" value="Reset">
</form>
</div>
#AvinashT But is the ajax call being made or not?
#gurvinder372 ajax is called and form data is entring into table
successfully
Based on above discussion, you just need to add this line in the success handler to hide the form
$('#submit_0').closest( "form" ).hide()
Here number of forms created dynamically. i need to hide the form once
we submit the form data, to prevent multiple submission of form.
Form is being submitted multiple times, because you have two handlers (one is via onclick and other via submit click event handler).
You need to remove the onclick="frmsubmit()" from the form tag since submit click event handler is already taking care of form-submission.

multi form ajax php social comment system

I have a lot of these forms that I post with PHP. They are under every article in my page, but when I submit the form with these ajax functions it only sends to the first form of the page. Why? I want send these form separately what am I doing wrong?
<script type="text/javascript" >
$(function() {
$(".submit").click(function()
{
var name = $("#name").val();
var comment = $("#comment").val();
var post_id = $("#post").val();
var dataString = 'name='+ name + '&comment=' + comment+ '&post_id=' + post_id;
if(name=='' || comment=='')
{
alert('Please Give Valid Details');
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loading.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "commenti.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
}return false;
});
});
<script>
<ol id="update" class="timeline">
</ol>
<div id="flash"></div>
<div >
<form action="#" method="post">
<input type="hidden" id="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" id="name" value="<?php echo $username; ?>"/>
<textarea id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
<ol id="update" class="timeline">
</ol>
<div id="flash"></div>
<div >
<form action="#" method="post">
<input type="hidden" id="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" id="name" value="<?php echo $username; ?>"/>
<textarea id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
<ol id="update" class="timeline">
</ol>
<div id="flash"></div>
<div >
<form action="#" method="post">
<input type="hidden" id="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" id="name" value="<?php echo $username; ?>"/>
<textarea id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
First of all, as has been said in the comments, don't use repetead IDs. If you don't intend to use Ids as a unique identifier, use classes.
<ol class="timeline update">
<div id="flash"></div>
<div >
<form action="#" id="form" method="post">
<input type="hidden" class="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" class="name" value="<?php echo $username; ?>"/>
<textarea class="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
</ol>
In your javascript code, you are trying to get the id name with var name = $('#name'), right? What name?
Also, try to send your requeste with an array rather than a string.
Something like this:
$(".submit").click(function()
{
var name = $(this).parents('form:input.name').val();
var comment = $(this).parents('form:input.comment').val();
var post_id = $(this).parents('form:input.post').val();
var data = {'name': name,
'comment': comment,
'post_id':post_id},
$.ajax({
type: "POST",
url: "commenti.php",
data: data,
success: function(html){
//do stuff
}
}
Access your variable in PHP with $_POST['varName'];
Hope it helps.

(javascript) onClick="form.submit(); doesn't work on IE & Opera

I have a code (see it below). It works perfectly in Firefox: it saves submitted information after clicking __JL_SAVE button and keeps user on same page.
But in Internet Explorer & Opera it only redirects to index page (index.php) and doesn't save submitted information.
What can I do for solving this problem? Thanks.
Here is my code:
<form action="index.php" id="mosForm" method="post" enctype="multipart/form-data">
<fieldset>
<legend><?=__JL_ABOUT_MYSELF?></legend>
<span class="a" onclick="showHideLegend('about_myself_1')"><?=__JL_EDIT_BLOCK;?></span>
<div id="about_myself_descr" style="display: block"><?=__JL_SELF_DESCR;?></div>
<div id="about_myself_1" style="display: none"><?php include "html/about_myself_fill.php"?></div>
<div id="about_myself_2""><?php include "html/about_myself_show.php"?></div>
</fieldset>
<fieldset>
<legend><?=__JL_ABOUT_MYSELF?></legend>
<span class="a" onclick="showHideLegend('type_1')"><?=__JL_EDIT_BLOCK;?></span>
<?php if ($typ_block) {?>
<?php /* <input type="checkbox" id="jl_type_block" name="jl_type_block" <?php if ($roon_type_block) echo 'checked ';?> /> */ ?>
<input type="checkbox" id="jl_type_block" name="jl_type_block" disabled <?php echo 'checked ';?> />
<label for="jl_type_block"><?=__JL_ON_BLOCK?></label>
<?php } else {
echo __JL_OFF_BLOCK;
}?>
<div id="about_myself_descr" style="display: block"><?=__JL_SELF_DESCR;?></div>
<div id="type_1" style="display : none">
<?php include "html/type.php"?>
</div>
<?php if ($typ_block) { ?>
<div id="type_2">
<?php include "html/type_show.php"?>
</div>
<?php } ?>
</fieldset>
<fieldset>
<legend><?=__JL_INTEREST?></legend>
<span class="a" onclick="showHideLegend('interest_1')"><?=__JL_EDIT_BLOCK;?></span>
<?php if ($interest_block) {?>
<input type="checkbox" id="jl_interest_block" name="jl_interest_block" disabled <?php echo 'checked ';?> />
<label for="jl_interest_block"><?=__JL_ON_BLOCK?></label>
<?php } else
echo __JL_OFF_BLOCK;
?>
<div id="interest_descr" style="display:block"><?=__JL_INTEREST_DESCR;?></div>
<div id="interest_1" style="display:none">
<?php include "html/interest.php"?>
</div>
<?php if ($interest_block) { ?>
<div id="interest_2">
<?php include "html/interest_show.php"?>
</div>
<?php } ?>
</fieldset>
<input type="submit" name="save" value="__JL_SAVE" onClick="mosForm.submit();" />
<input type="hidden" name="option" value="com_joomlove" />
<input type="hidden" id="task" name="task" value="save_info" />
</form>
Full source available here: http://narkoz.pastebin.com/f4f036f5
You should really perform any submission related logic in FORM's "submit" event handler, not in "click" of one of FORM's elements. e.g.:
<form ... onsubmit="return validateForm(this);"> ... </form>
This should ensure that keyboard-based submission goes through your handler; it also gives you an ability to prevent form submission by returning falsy value from an event handler. Any truthy value, on the other hand, will automatically submit a form.
If you're not changing the behavior of the form, why use JavaScript to submit the form?, you're already in a submit button.
You should try giving the form name="mosForm", not just id="mosForm", so that the DOM reference from that event handler can be found.
When you have:
<form method="post" action="somefile.php" name="form" id="form">
<button type="button" name="submit" onclick="$('#form').submit()">go</button>
</form>
Does work in IE8, Opera, Chrome, but not in Firefox(14):
Firefox has a problem with: name="submit". When you change the name attribute in: name="submit_ff" (or something else), it works also in Firefox.

Categories