jquery auto submits itself - javascript

Anyone understand why this auto submits the form? Can`t seem to find the right answer to why it does that.
Using query parsley to validate the form in modal.
User open modal, user starts typing into the text area, you must at least type 20 characters and limit of 100. When you are over the 20, the form submits it self.
No matter what i do, i can`t prevent that for happening.
Any clue ?
Thanks =)
<div id="form-content" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">X</span>
</button>
<h4 class="modal-title" id="myModalLabel2">Modal title</h4>
</div>
<div class="modal-body">
<!-- start form for validation -->
<form id="ReportForm">
<label for="fullname">Brukernavn :</label>
<input type="hidden" id="Username_Field" class="form-control" name="username" value="Kimmeliten" />
<label for="message">Message (20 chars min, 500 max) :</label>
<textarea id="message" required="required" class="form-control" name="message" data-parsley-trigger="keyup" data-parsley-minlength="20" data-parsley-maxlength="100" data-parsley-minlength-message="Come on! You need to enter at least a 20 caracters long comment.." data-parsley-validation-threshold="10"></textarea>
</form>
<!-- end form for validations -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="submit10">Save changes</button>
</div>
</div>
</div>
</div>
<!-- /modals -->
<script>
$(document).ready(function() {
$.listen('parsley:field:validate', function() {
validateFront();
});
$('#submit10').click(function(){
$('#ReportForm').parsley().validate();
validateFront();
});
var validateFront = function() {
if (true === $('#ReportForm').parsley().isValid()) {
$('.bs-callout-info').removeClass('hidden');
$('.bs-callout-warning').addClass('hidden');
$.ajax({
type: "POST",
url: "forum/ajax/report.ajax.php",
data: $('#ReportForm').serialize(),
success: function(msg){
$("#thanks").html(msg);
$("#form-content").modal('hide');
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
} else {
$('.bs-callout-info').addClass('hidden');
$('.bs-callout-warning').removeClass('hidden');
}
};
});
try {
hljs.initHighlightingOnLoad();
} catch (err) {}
</script>

Not really sure, but looking into the documentation, shows:
form:validate | Triggered when a form validation is triggered, before its validation.
Is seems, that your listener is fired as soon as you begin to validate, what triggers validateFront.
$.listen('parsley:field:validate', function() {
validateFront();
});
Have you tried to listen to form:success instead?

Related

Why my ajax post is not working codeigniter? The page is refreshing

// save new employee record
$('#saveEmpForm').submit('click',function(){
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
});
<form id="saveEmpForm" method="post">
<div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add New Employee</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-md-2 col-form-label">Jenis</label>
<div class="col-md-10">
<input type="text" name="jenis" id="jenis" class="form-control" required>
<input type="hidden" id="input_id" name="input_id" class="form-control " value="{$input_id}">
</div>
</div>
<div class="form-group row">
<label class="col-md-2 col-form-label">Jarak</label>
<div class="col-md-10">
<input type="text" name="jarak" id="jarak" class="form-control" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>
Save function in controller file
public function save(){
$data=$this->inputs_model->saveEmp();
echo json_encode($data);
}
Save function in Model
public function saveEmp(){
$data = array(
'input_id' => $this->input->post('input_id'),
'jenis' => $this->input->post('jenis'),
'jarak' => $this->input->post('jarak'),
'created_at' => date("Y-m-d h:i:sa"),
'updated_at' => date("Y-m-d h:i:sa")
);
$result=$this->db->insert('input_jenis_industri',$data);
return $result;
}
The code are as stated above, my ajax function to save the data is not working. It is not saving the data in the db. What can cause the problem?
My ajax function calls the InputPembangunan/save to save the data, then the controller try to the save data using the save() function. It is saved using the model saveEmp()
The following is incorrect, there is no click involved in a submit event
$('#saveEmpForm').submit('click',function(){
Change to
$('#saveEmpForm').submit(function(event){
event.preventDefault()// prevent normal form submit
without refreshing the page you have to call event.preventDefault() method after submit event.
replace this
$('#saveEmpForm').submit('click',function(){
with
$('#saveEmpForm').on('submit',function(){
event.preventDefault()
Change this
<button type="submit" class="btn btn-primary">Save</button>
to
<button type="button" class="btn btn-primary">Save</button>
You can onlick() method. Actually I used like this;
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" onclick="save()" class="btn btn-primary">Save</button>
</div>
than add jquery
function save() {
// ajax adding data to database
var formData = new FormData($('#form')[0]);
$.ajax({
URL: "<?php echo site_url('InputPembangunan/save')?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
success: function(data) {
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else {
//do something
}
},
error: function(jqXHR, textStatus, errorThrown) {
//do error form
}
});}
Use the following way,
$( "#saveEmpForm" ).submit(function( event ) {
event.preventDefault();
/** Your Existing Code ***/
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
/** Your Existing Code ***/
});
Also, you can check the jQuery reference from this link:
https://api.jquery.com/submit/#submit
Replace
$('#saveEmpForm').submit('click',function(){
with
$(document).off('submit','#saveEmpForm').on('submit','#saveEmpForm',function(event) {
event.preventDefault(); //to prevent default submit action
...rest of the code
})
also check for any errors on the browser dev tool

Modal hide trobleshooting

I am working on a module where a dropdown modal has to appear after a duration of 3 mins on the page. It has an input field where digits has to be entered by the user and when he clicks on 'save', the modal should hide. Although I am getting the modal at correct time and when the digits are entered the values are being saved too but only the modal does not hides. I am just unable to figure out the reason behind it as the modal implementation is correct up to my knowledge. I am new to jquery and javascript so need suggestions and expertise of community. I am putting my code here, please have a look and any help or suggestion will be highly appreciated.
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<form name="frmActive" id="frmActive" action="" method="post">
<div class="modal-content" style="height:250px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ideal Time activation</h4>
</div>
<div class="modal-body">
<p>Please enter activation PIN:</p>
<p id="msg" style="color:#F00;"></p>
<input type="password" name="pin" id="pin" value="" maxlength="4" onKeyUp="checkNumber(this)" class="form-control" placeholder="Enter Pin">
<input type="hidden" id="inactiveTime">
</div>
<div class="modal-footer">
<button type="button" id="btnSubmit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Save</button>
<input type="hidden" id="module_id" value="<?php echo $moduleId ; ?>">
<input type="hidden" id="chapter_id" value="<?php echo $chapterId ; ?>">
</div>
</div>
</form>
</div>
</div>
jQuery("#btnSubmit").on("click", function(){
var pin = jQuery("#pin").val();
var chapter_id = jQuery("#chapter_id").val();
var module_id = jQuery("#module_id").val();
var nowDate = jQuery.now();
var inactiveTime = jQuery("#inactiveTime").val();
var seconds = (nowDate - inactiveTime) / 1000;
var formData = new FormData();
formData.append("pin", pin);
formData.append("seconds", seconds);
formData.append("module_id", module_id);
formData.append("chapter_id", chapter_id);
// $("#spinner").show();
$.ajax({
url: "processActivation.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
//dataType:'json',
success: function(result){
if(result == 'active')
{
$("#bt").html(result) ;
jQuery('#myModal').modal('hide');
}
else if(result == 'active')
{
jQuery('#myModal').modal('hide');
}
else
{
$("#msg").html(result) ;
}
}
});
});
And the ajax request being made for success,
$dataactivation = array("user_id"=>$uid, "module_id"=>$moduleId, "chapter_id"=>$chapterId,"time_taken"=>$time_taken, "created"=>$created);
$db->query_insert("tbl_activation", $dataactivation);
echo trim('active');
Please try console.log your result, you need to know the respond.
console.log(result);
here is the problem: if(result == 'active')
Remove echo trim('active');
change to : header('Content-Type: application/json', true, 200);
echo json_encode('active')); exit();
i hope you get it.

how to refresh and rebind the data from db in angularjs

hi all iam using angularjs ngrepeat to bind the datas into table.i have one add new button when i click bootstrap model popup open i fill the input details click submit means data will stored correctly but table couldn't not get the new data but once i reload the page data will show
my controller code
var refresh = function () {
$http.get('/ViewFacility').success(function (response) {
$scope.ViewFacilitys = response;
};
refresh();
My add new code:
$scope.AddRole = function () {
$http.post('/AddNewRole', $scope.Role).success(function (response) {
refresh();
});
};
Html Code
<form name="profileform">
<div class="modal fade" id="myModal" role="dialog" ng-controller="IndexController">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="margin-top:135px">
<div class="modal-header">
<h4 class="modal-title ">Role Name</h4>
</div>
<div class="modal-body">
<h4>Name</h4>
<input type="text" name="RoleName" class="form-control" ng-model="Role.RoleName">
<span class="error" ng-show="profileform.FirstName.$invalid && profileform.FirstName.$dirty">Please enter a First Name</span>
<h4>Description</h4>
<input type="text" name="Description" class="form-control" ng-model="Role.Description">
<span class="error" ng-show="profileform.LastName.$invalid && profileform.LastName.$dirty">Please enter a Last Name</span>
<h4>IsActive</h4>
<input type="checkbox" name="IsActive" class="form-control checkbox" ng-model="Role.IsActive" style="margin-left:-47%" >
<span class="error" ng-show="profileform.Email.$invalid && profileform.Email.$dirty">Please enter a Email</span>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="AddRole()" ng-disabled="profileform.$invalid">Submit</button>
<button class="btn btn-primary" data-dismiss="modal" ng-click="deselect()">Clear</button>
</div>
</div>
</div>
</div>
</form>
Just add the new item to the array.
$scope.AddRole = function () {
$http.post('/AddNewRole', $scope.Role).success(function (response) {
$scope.ViewFacilitys.push($scope.Role);
});
};
You don't need to fetch all data each time you create a new item. Refresh must be called just one time.
For pagination you can code a simple function that send the number of page to the server:
$scope.changePage = function (page) {
$scope.get('/ViewFacility?page='+page)
.then(function (response) {
$scope.ViewFacilitys = response.data;
});
}
Try modifying your refresh function like so
var refresh = function () {
$http.get('/ViewFacility').success(function (response) { //assuming this only fetches the newly added one
$scope.ViewFacilitys.push(response);
};

Select2 - not working in bootstrap 3 with tabindex removed?

Select2 has this bug where it refuses to work properly in a Bootstrap 3 modal unless one removes the tabindex element from the modal. I have done so with several modals on my page and they all work, however, there is one where I cannot get Select2 to activate at all.
I have a list of department names and positions which is displayed in a table, each row has its own "EDIT" button that calls up the modal to display the record details. The modal-body is empty but upon load is populated via AJAX.
I am using another select2 field on the same page (not inside that modal, but the main table) which is working well, just the select2 in this modal doesnt seem to work...
My thought is that due to the AJAX interaction, I might have to refresh select2 or load it before / after the modal is populated, but neither has yielded any results so far.
Any suggestions please?
PHP
<!-- Modal EditDepartmentModal -->
<div class="modal fade" id="EditDepartmentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit Department Record</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" id="SaveDepartmentButton" name="SaveDepartmentButton" class="btn btn-primary">Save Changes</button>
<button type="button" id="DeleteDepartmentButton" name="DeleteDepartmentButton" class="btn btn-danger">Delete Record</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /.Modal EditDepartmentModal -->
AJAX:
<!-- JavaScript for Modal -->
<script type="text/javascript">
//Initialize Select2 Elements
$(function () {
$(".select2").select2();
});
// VIEW DEPARTMENT RECORD
$('#EditDepartmentModal').on('show.bs.modal', function(e) {
var modal = $(this);
var dataDeptName = $(e.relatedTarget).data('dname');
$.ajax({
type: "POST",
url: "../../plugins/MySQL/ajax_action.php",
data: { action:"view_department",Department_Name:dataDeptName}, // form data to post goes here as a json object
//dataType: "html",
//async: true,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
},
error: function(err) {
console.log(err);
},
});
});
</script>
AJAX return:
echo "
<!-- ID No. -->
<label>ID No.:</label>
<div class=\"input-group\">
<span class=\"input-group-addon\"><i class=\"fa fa-database\"></i></span>
<input type=\"number\" class=\"form-control\" id=\"dataDeptID\" name=\"dataDeptID\" size=\"5\" value=\"$dept_id\" disabled />
</div>
<!-- /.id number -->
<p> </p>
<!-- Department -->
<label>Department Name:</label>
<div class=\"input-group\">
<span class=\"input-group-addon\"><i class=\"fa fa-bars\"></i></span>
<input type=\"text\" class=\"form-control\" id=\"dataDeptName\" name=\"dataDeptName\" value=\"$dept_name\" />
</div>
<!-- /.department -->
<p> </p>
<!-- Positions -->
<label>Department Positions:</label>
<div class=\"input-group\">
<span class=\"input-group-addon\"><i class=\"fa fa-briefcase\"></i></span>
<select class=\"form-control select2\" style=\"width:100%;\" id=\"test\" name=\"test\">
<option value=\"1\">Option 1</option>
<option value=\"2\">Option 2</option>
<option value=\"3\">Option 3</option>
<option value=\"4\">Option 4</option>
</select>
</div>";
The code is working alright, its just select2 that doesnt want to show up -.-
Again, if I read this right, the html is contained in the ajax return so you cannot call the select2 on it until after that so try this...
<script type="text/javascript">
//Initialize Select2 Elements
$(function () {
// VIEW DEPARTMENT RECORD
$('#EditDepartmentModal').on('show.bs.modal', function(e) {
var modal = $(this);
var dataDeptName = $(e.relatedTarget).data('dname');
$.ajax({
type: "POST",
url: "../../plugins/MySQL/ajax_action.php",
data: { action:"view_department",Department_Name:dataDeptName}, // form data to post goes here as a json object
//dataType: "html",
//async: true,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
$(".select2").select2();
},
error: function(err) {
console.log(err);
},
});
});
});
</script>

get data From Bootstrap 3 modal form with jquery ajax

i wrote this to get form data and post it to a php page and do some proccess and get back a result to me,i start with getting post data from my bootstrap modal form and i found that the script can't take values from modal form,because the php part i can't upload it to fiddle or somewhere else.
i upload it on my server for rapid review
click on compose;
complete the fields
and when Send button clicked it expect to modal form sent some value to jquery ajax(on submit) but nothing sent from modal inputs to ajax and the whole $_POST array remain null,and whats going on?
hours and hours i searched for doc's and example's,but i couldn't found any answer,some examples works with bootstrap 2,and nothing for the bootstrap 3.
bootstrap 3.3.1,jquery 2.1.1
here is the modal code:
<div class="modal fade" id="largeModal" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Compose</h4>
</div>
<div class="modal-body">
<form id="sendmail" data-async method="post" role="form" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2" for="inputTo">To</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputTo" placeholder="comma separated list of recipients">
</div>
</div>
<div class="form-group">
<label class="col-sm-2" for="inputSubject">Subject</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputSubject" placeholder="subject">
</div>
</div>
<div class="form-group">
<label class="col-sm-12" for="inputBody">Message</label>
<div class="col-sm-12">
<textarea class="form-control" id="inputBody" rows="18"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" value="Submit">Send</button>
<div id='response'></div>
</div>
</form>
</div>
</div>
</div>
jQuery:
$(document).ready(function () {
$('#sendmail').submit(function () {
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'proccess.php',
data: $(this).serialize()
})
.done(function (data) {
$('#response').html(data);
})
.fail(function () {
alert("Posting failed.");
});
return false;
});
});
Simple PHP Code:
print_r($_POST);
In your code, this which is provided inside the $.ajax method's object refers ajax object. And it seems that you need to refer to the form from which you have to get the data and serialise it and send it into AJAX request.
Try following code,
$(document).ready(function () {
$('#sendmail').submit(function () {
var that = this;
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'proccess.php',
data: $(that).serialize()
})
.done(function (data) {
$('#response').html(data);
})
.fail(function () {
alert("Posting failed.");
});
return false;
});
});
here I have referred the form object this by assigning it to that

Categories

Resources