I have the following form and input box. However, when there is nothing in the input box, the javascript doesn't execute. I need to detect if someone clicked "submit" without filling in the form. I have tried many things I've found on SO and none have worked. When there is an input value, everything works perfectly to execute the js. However, when there is nothing, the console.log(bidz) doesn't produce anything and it appears as if the script quits. From what I've read, I understand that the input box doesn't exist without a value in it. But then I tried to say if it doesn't exist, then something, but that also didn't work.
Perhaps this has to do with the fact that I give it a placeholder value of "enter something?"
<form action="" method="post">
<div id="<?php echo $this->item['id']; ?>">
<div class="ab">
<label for="ab_input"><?php echo $this->translate('To get the auction started, you must enter a starting bid.'); ?></label>
<span class="auction_bid_container">
<input id="ab_input" type="text" maxlength="12"
class="middle nmr event-clear-focus"
name="bidz" value="Enter something" />
<input id="updateBidButton" type="submit"
class="button grey-button num-items-button"
name="bidz"
value="<?php echo $this->translate('submit'); ?>"/>
</span>
</div>
</div>
</form>
<div class="clear mb20"></div>
and here is my js function. I have tried all kinds of things but it appears "this.value" results in an error if there is no value:
$('input[name="bid_amount"]').live('change', function () {
var bidz = this.value;
console.log(bidz);
$.ajax({
type: 'post',
url: "?module=is&controller=index&action=syy",
dataType: "text",
data: 'bid=' + bid_amount + '&id=' + id,
beforeSend: function () {
$('.ab').animate({
'backgroundColor': '#ffdead'
}, 400);
},
success: function (result) {
if (result == 'ok') {
console.log(bid_amount);
$('.ab').animate({
'backgroundColor': '#A3D1A3'
}, 300);
} else {
$('.ab').animate({
'backgroundColor': '#FFBFBF'
}, 300);
}
}
});
});
You are submitting the form either way, that's why! So, what you have to do is to stop the form from being submitted. How?
You can add onsubmit=" return false; " to your form
<form action="" method="post" onsubmit=" return false; ">
</form>
submit.addEventListener("submit", form, function(){
e.preventDefault(); /* This will prevent the form from being sent until you explicitly send it. */
});
If you are sending the form through ajax there is no need to submit the actual form (meaning form.submit() )
Related
Its very common question all over the internet but I don't know how to fix this problem. I have a comment system, where users can post comments. The problem is when someone posts comment on the 10th post of the page, by submitting the form they redirect to the top of the page, which i don't want. I want the comment to be sent successfully and the user must be on the same post. I hope i can understand you all experienced developers.
HTML FORM
<form id="form" action="" method="post">
<div class="input-group mb-3">
<img class="p-1 m-0" src="images/" width="35" height="35" alt="">
<input name="post_comment" id="add_comments" type="text" autofocus class="form-control pl-3 pr-3" placeholder="type somethign" aria-label="Recipient's username" aria-describedby="button-form">
<div class="input-group-append">
<button class="btn btn-secondary" type="submit" name="submit_comment" id="button-form">Add Comment</button>
</div>
</div>
</form>
JavaScript code:
<script>
$(document).ready(function(){
$('#button-form').click(function(){
var add_comments = $('#add_comments').val();
if(add_comments == '')
{
$('#error_msg').html("Comments blank!");
}
else
{
$('#error_msg').html('');
$.ajax({
url:"index.php",
method:'post',
data:{add_comments:add_comments},
success:function(data){
$("form").trigger("reset");
$('#succ_msg').fadeIn().html(data);
setTimeout(function(){
$('#success_message').fadeOut("Slow");
}, 2000);
}
});
}
});
});
</script>
PHP Query:
if(isset($_POST['submit_comment'.$ansRow['id']])){
$comments = $_POST['post_comment'.$ansRow['id']];
if(empty($comments)){
$cError = "Wrote nothing in comments!";
}else{
$comments = mysqli_real_escape_string($con,$_POST['post_comment'.$ansRow['id']]);
$cQuery = "INSERT INTO `qa-comments` (posted_at,updated_at,user_id,answer_id,question_id,comments_text)
VALUES
(now(),now(),'".$_SESSION['id']."','$ansId','$qId','$comments')";
if(mysqli_query($con,$cQuery)){
// header('refresh:0s');
}else{
$cError = "Something went wrong!";
// printf("Errormessage: %s\n", mysqli_error($con));
}
}
}
console erros.[![enter image description here][1]][1]
You do not currently prevent the form from executing it's default behavior. When you click the button of type="submit" the form get's sent to the page specified in <form action="some_url"></form> or to the same page, if that is empty
$(document).ready(function(){
$('#form').on('submit', function(){
event.preventDefault()
var add_comments = $('#add_comments').val();
if(add_comments == '')
{
$('#error_msg').html("Comments blank!");
}
else
{
$('#error_msg').html('');
$.ajax({
url:"index.php",
method:'post',
data:{add_comments:add_comments},
success:function(data){
$("form").trigger("reset");
$('#succ_msg').fadeIn().html(data);
setTimeout(function(){
$('#success_message').fadeOut("Slow");
}, 2000);
}
});
}
});
});
This will prevent the reloading of the page and execute your javascript instead
I am writing code for page reload after getting response from button click event in javascript. But its not working page is not getting reload after button click event.
My form
<div class="form-group">
<label>My Label Name</label>
<select class="form-control my_select2_id" id="my_select2_id" name="my_select2_id" tabindex="-1">
<option></option>
<?php if($table_rows != '') {
foreach($table_rows as $each_row) {?>
<option value="<?=$each_row['id']; ?>"><?=$each_row['my_column']; ?></option>
<?php } }?>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control second_field" id="second_field_id" name="second_field_id" placeholder="Enter second field ID">
</div>
<div class="form-group">
<input type="text" class="form-control my_third_field" id="my_third_field" name="my_third_field" placeholder="Enter Third Field">
</div>
<button type="button" id="my-button-id" class="btn btn-success float_left">Add Test Case</button>
My Select2 dropdown select box is:
$("#my_select2_id").select2({
placeholder: "Select One ID",
allowClear: true,
initSelection: function(element, callback) { }
});
My Ajax call is:
$('#my-button-id').click(function(){
---------
---------
---------
var data = $('#my_form').serialize();
$.ajax({
type:"POST",
url:"ajax/my_ajax_file.php",
data:data,
success:function(response)
{
if(response == 'error')
{
$('.failure-msg').text('Some problem occurred, please try again.');
$('.form_error').show();
}
else
{
$('.form_error').hide();
$('#my_form')[0].reset();
$("#my_select2_id").select2('data', null);
//$("#my_select2_id").val('').trigger('change');
$('.myData').html(response);
$('.success-msg').text('Data has been added.');
$('.my_form_success').show();
window.setTimeout(function(){location.reload()},1000)
}
}
});
})
My requirement here is I just want to reset the select2 box, for this I am following 2 ways that is I have to either reset select2 box which is not getting reset or reload the page so that select2 also will be reset. It is neither refreshed by window.setTimeout(function(){location.reload()},1000) nor the select2 box is getting reset by $("#my_select2_id").select2('data', null); Can anyone please help me in this. Thanks in advance.
As mentioned in the comments to your question there is no obvious syntactical error in your code but you lack to check for errors on your AJAX call by only checking the success() portion of the code. I would recommend to either add the complete() or error() functions to make sure you are also able to react to errors that may occur while submitting the data.
$.ajax({
type:"POST",
url:"ajax/my_ajax_file.php",
data:data,
success:function(response) {
},
error: function (jqXHR, status, message)
{
alert ("Submitting data failed with message: " + message);
}
});
On a page refresh all form elements will be reset to their original values, you therefor don't have to clear the SELECT field prior to reloading the data.
You can try with:
setTimeout(function(){ location.reload(); }, 1000);
Form :
<form method="post" id="loginForm">
<div class="form-group">
<label for="email-signin">Email address:</label>
<input type="email" class="form-control" id="email-signin" name="email-signin">
</div>
<div class="form-group">
<label for="pwd-signin">Password:</label>
<input type="password" class="form-control" id="pwd-signin" name="pwd-signin">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" id="signIn" name="signIn">Sign In</button>
<div id="error">
<!-- error will be shown here ! -->
</div>
</form>
jquery :
$("#signIn").on("click", function(e) {
e.preventDefault();
var values = $("#loginForm").serialize();
console.log( values );
$.ajax({
type: "POST",
url: "../php/BusinessLayer/User.php",
data: values,
beforeSend: function() { $("#error").fadeOut() },
success : function(response)
{
console.log("Success");
if(response=="ok"){
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
});
}
}
});
php:
<?php
session_start();
include ("../DataLayer/VO/UserVO.php");
include ("../DataLayer/DAO/UserDAO.php");
// Database Execution for User Related Request
$userDAO = new UserDAO();
print_r($_POST);
if(isset($_POST['signIn']))
{
echo 'test2';
$user = new UserVO();
$user->setEmail(trim($_POST['email-signin']));
$user->setPassword(trim($_POST['pwd-signin']));
// Request signin
$userDAO->signIn($user);
}
Using this code, my if(isset($_REQUEST['signIn'])) in my php file never returns true. I have tried multiple things, and nothing seems to work.
PS : I am using Jquery 1.12.4
Also, my print_r($_POST); returns an empty Array.
jQuery's serialize function does not encode the values of buttons. Taken from here
NOTE: This answer was originally posted by slashingweapon
jQuery's serialize() is pretty explicit about NOT encoding buttons or submit inputs, because they aren't considered to be "successful controls". This is because the serialize() method has no way of knowing what button (if any!) was clicked.
I managed to get around the problem by catching the button click, serializing the form, and then tacking on the encoded name and value of the clicked button to the result.
$("button.positive").click(function (evt) {
evt.preventDefault();
var button = $(evt.target);
var result = button.parents('form').serialize()
+ '&'
+ encodeURIComponent(button.attr('name'))
+ '='
+ encodeURIComponent(button.attr('value'))
;
console.log(result);
});
As far as the var dump being empty on the PHP side, try using jQuery's .click instead of the .on event.
$('#signIn').click(function(){});
Also, remove the method from your form. It looks like the form may be submitting as soon as you click the button. Also, remove
e.preventDefault();
and place
return false;
at the VERY END of the on click function. return false does 3 things
e.preventDefault()
e.stopPropigation();
return immdediatly
I have the following problem:
2 forms that need to be submitted with one button. I will explain how it should work.
And of course my code so far.
#frmOne contains a url field where I need to copy the data from to my #frmTwo, this works.
(it forces the visitor to use www. and not http:// etc)
When I press 1 submit button
Verify fields #frmOne (only url works now, help needed on the others)
Call #frmTwo and show result in iframe. result shows progress bar (works)
But Div, modal or any other solution besides iframe are welcome.
Close #frmOne (does not work)
Finally process (submit) #frmOne if #frmTwo is done (does not work)
Process completed code of #frmTwo in iframe =
<div style='width' id='information'>Process completed</div>
<ol class="forms">
<iframe width="100%" height="50" name="formprogress" frameborder="0" scrolling="no" allowtransparency="true"></iframe>
<div id="txtMessage"></div>
</ol>
<div id="hide-on-submit">
<form id="frmOne" method="post">
<input type="text" name="company" id="company" >
<input type="text" name="url" id="url" >
<input type="text" name="phone" id="phone" >
<input type="text" name="occupation" id="occupation" >
<textarea rows="20" cols="30" name="summary" id="summary" >
<button type="submit" class="btn btn-danger">Submit</button>
</form>
</div>
<form id="frmTwo" method="post" target="formprogress"></form>
<script>
jQuery(document).ready(function(){
//Cache variables
var $frmOne = $('#frmOne'),
$frmTwo = $('#frmTwo'),
$txtMessage = $('#txtMessage'),
frmTwoAction = 'http://www.mydomainname.com/form.php?url=';
//Form 1 sumbit event
$frmOne.on('submit', function(event){
event.preventDefault();
var strUrl = $frmOne.find('#url').val();
//validation
if(strUrl === ''){
$txtMessage.html('<b>Missing Information: </b> Please enter a URL.');
}
else if(strUrl.substring(0,7) === 'http://'){
//Clear field
$frmOne.find('#url').val('');
$txtMessage.html('<b>http://</b> is not supported!');
}
else if(strUrl.substring(0,4) !== 'www.'){
//Clear field
$frmOne.find('#url').val('');
$txtMessage.html('<b>Invalid URL</b> Please enter a valid URL!');
}
else{
//set form action and submit form
$frmTwo.attr('action', frmTwoAction + strUrl).submit();
$('#hide-on-submit').hide(0).fadeIn(1000);
$('form#frmOne').submit(function(e) {
$(this).hide(1000);
return true; // let form one submit now!
}
return false;
});
});
</script>
read here https://api.jquery.com/jQuery.ajax/. basically you need to submit the first one with $.ajax and then, when you get the server response (in the success() function ) you need to send the second form, again width ajax().
Something like:
$form1.on('submit', function(e) {
e.preventDefault(); //don't send the form yet
$.ajax(
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize()
).success(function(data) {
alert('form one sent');
$.ajax(
url: $('#form2').attr('action'),
type: $('#form2').attr('method'),
data: $('#form2').serialize()
).success(function(data) {
alert('form two sent');
})
});
});
This code isn't ready to be copy/pasted, it's just to give you a guideline of how I would solve it. It's a big question, try going with this solution and come back with smaller question if you find yourself blocked.
I have a form, and it has a field for entering a PIN code. Here I am using ajax for finding place when enter PIN code. It works when that field is not enclose in a form. If it is enclosed in a form, AJAX is not working.
HTML CODE:
<form id="form" class="blocks" action="#" method="post" enctype="multipart/form-data">
<div class="col_4 right">
<label for="fullname">FirstName:</label>
<input name="fname" type="text" class="text" />
</div>
<div class="col_4 right">
<label for="pincode">Pin-Code:</label>
<input name="pincode" type="text" class="text" id="pincode" />
<div id="section1"></div>
</div>
</form>
JS CODE:
<script>
$(document).ready(function() {
$('#pincode').keyup(function (e) {
if (e.keyCode == 13) {
//ajax request
$.ajax({
url: "pincode_check.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) { <!--console.log(data.success);-->
if(data.success){
//console.log(data.results[0].formatted_address.split(','))
var long_address=data.results[0].formatted_address.split(',');
console.log(long_address[0]);
$('#section1').append(long_address[0]);
}
}
});
}
});
});
</script>
PHP CODE(pincode_check.php):
<?php
$pincode=$_REQUEST['pincode'];
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$pincode.'&sensor=false');
$response= json_decode($geocode); //Store values in variable
$lat = $response->results[0]->geometry->location->lat; //Returns Latitude
$long = $response->results[0]->geometry->location->lng; // Returns Longitude
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$long.'&sensor=false');
$data= json_decode($geocode);
if($data==true)
{ // Check if address is available or not
$data->results[0]->formatted_address ;
$data->success=true;
echo json_encode($data);
}
else {
$data->success= false;
echo json_encode($data);
}
?>
The default content type in $.ajax is application/x-www-form-urlencoded. But you've set your form content to multipart/form-data.
multipart/form-data is normally used for sending files with POST. I don't think you need that, so you don't need to specify enctype at all, just remove it and use the default form encoding, which is application/x-www-form-urlencoded.
(Additionally, the default request type in $.ajax is GET, so if you do want to send a file, you'll need to change that too..as well as add the attribute type="file" to your form I believe...)