I have an issue where I wanted to submit by form with javascript but obviously I have hit an issue when trying to do this and wondered if anyone could help me with the issue, more information can be found below on the issue and the code samples.
Hello. My form .submit function isn't calling when I submit my form that's added, can anyone help?
So first, the form is inside the modal:
<div class="modal fade" id="editPositionModal" role="dialog">
<div class="modal-dialog" style="width:460px;">
<!-- Modal content-->
<div class="modal-content" id="edit-position-content">
</div>
</div>
</div>
As you can see, the form has yet to be added, so I add it using a function:
function modifyPosition(businessId, positionId) {
$.ajax({
url: ajaxCallUrl + 'api/ajax/positions/' + positionId + '/get-edit-content',
type: "GET",
error: function(req, message) {
showErrorNotification('It seems something went wrong, sorry...');
},
statusCode: {
400: function (response) {
showErrorNotification(response.responseText);
},
500: function (response) {
showErrorNotification(response.responseText);
}
},
success: function(data) {
lastModifiedPositionId = positionId;
$('#edit-position-content').html(data);
$('#editPositionModal').modal('show');
},
});
}
I call the above function on the button I click to open the modal with the form on.
Heres the modal content gotten by the ajax request:
<div class="modal-header">
<button class="close" data-dismiss="modal" type="button">×</button>
<h4 class="modal-title">Creating a new position</h4>
</div>
<div class="modal-body">
<form id="save_edit_position" method="POST">
<label>Position Title</label>
<input type="text" class="form-control" style="margin-bottom:20px;" value="{{ $position->position_title }}">
<label>Position Pay</label>
<input type="text" class="form-control" style="margin-bottom:20px;" value="{{ $position->position_shift_wage }}">
<label>Position Type</label>
<select class="form-control" name="business_position_type" id="position_type_modify">
<option value="employee">Employee</option>
<option value="supervisor">Supervisor</option>
<option value="manager">Manager</option>
<option value="ownership">Ownership</option>
</select>
</div>
<div class="modal-footer">
<button class="btn btn-success" type="submit"><i class="fa fa-sign-in"></i> Save</button>
</form>
</div>
<script>
var element = document.getElementById('position_type_modify');
element.value = '{{ $position->position_type }}';
</script>
And here is the javascript handler for the form submit, on the end of the page where the modal content is included on:
$("#save_edit_position").submit(function(e) {
alert('Submit Called...');
e.preventDefault();
$.ajax({
type: "POST",
url: ajaxCallUrl + 'api/ajax/positions/' + lastModifiedPositionId + '/save-position',
data: $("#save_edit_position").serialize(),
error: function(req, message) {
showErrorNotification('It seems something went wrong, sorry...' + message);
},
statusCode: {
400: function (response) {
showErrorNotification(response.responseText);
},
500: function (response) {
showErrorNotification(response.responseText);
}
},
success: function(data)
{
var mymodal = $('#editPositionModal');
mymodal.modal('hide');
showNotification(data, updatePositionsTable(pageBusinessId)); // show response from the php script.
}
});
});
Delegate you submit event, your form is dynamically added to the page so you need event delegation to bind your event
$('body').on('submit',"#save_edit_position",function(e) {
....
or use a delegated click event
$('body').on('click',"#save_edit_position input[type='submit']",function(e) {
....
Note if you have multiple forms on the page with the same id then only the first form with the id will work ids must be unique
You should use a onSubmit="" function handler
onsubmit="functionhere();"
Your form is incorrectly structured
<div class="modal-footer">
<button class="btn btn-success" type="submit"><i class="fa fa-sign-in"></i> Save</button>
</form>
You cannot, legitimately, straddle the form tag like this and from previous experience this will likely cause problems.
You can also change your submit type to button like that and add an onclick event to a javascript function. If though your form generate dynamically, but I think this should work.
<div class="modal-footer">
<input class="btn btn-success" type="button" value="Save" onclick="_submitForm();"/>
</div>
And your js should be
function _submitForm(){
alert('Submit Called...');
$.ajax({
type: "POST",
url: ajaxCallUrl + 'api/ajax/positions/' + lastModifiedPositionId + '/save-position',
data: $("#save_edit_position").serialize(),
error: function(req, message) {
showErrorNotification('It seems something went wrong, sorry...' + message);
},
statusCode: {
400: function (response) {
showErrorNotification(response.responseText);
},
500: function (response) {
showErrorNotification(response.responseText);
}
},
success: function(data)
{
var mymodal = $('#editPositionModal');
mymodal.modal('hide');
showNotification(data, updatePositionsTable(pageBusinessId)); // show response from the php script.
}
});
}
Try
$("form.save_edit_position").submit(function(e) {...}
I have one more doubt, Can you please share exact location of javascript handler for the form submit in code!!
Related
Here is a simple PHP form with a button..
<form method="POST">
<div class="mb-3">
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
<p></p>
</div>
</form>
Here is the Jquery functions which executes a PHP file.
$(document).ready(function(){
$("#btnnew1").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
else{
$.ajax({
url: 'test.php',
success: function(data) {
$("p").text(data);
}
});
}
});
});
And the test.php is as follows,
<?php
echo 'Button1 clicked'
?>
My question is how to modify my test.php if I have multiple buttons.
As an example,
<form method="POST">
<div class="mb-3">
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
<p></p>
</div>
<div class="mb-3">
<button type='button' id ="btnnew2" class="btn btn-info" >submit</button>
<p></p>
</div>
<div class="mb-3">
<button type='button' id ="btnnew3" class="btn btn-info" >submit</button>
<p></p>
</div>
</form>
Result should be,
If btnnew1 clicks--->echo("Button1 clicked);
If btnnew2 clicks--->echo("Button2 clicked);
If btnnew3 clicks--->echo("Button3 clicked);
Update:
What If I need to run three different php functions(no any pattern)?
Ex:
If btnnew1 clicks--->
sleep(5)
echo("Button1 clicked);
If btnnew2 clicks--->
sleep(15)
echo("Button2 clicked by user);
If btnnew3 clicks--->
sleep(35)
echo("Button3 clicked by user);
In here I am changing little bit your default settings. This will help you as I can understand. You can try as below,
1)Change your button into input type..I have added some inline CSS as well. If you don't like you may neglect it...
<input type="button" style="background-color: #3CBC8D;padding:3px;" class="button" name="fcn1" value="Update My Status"/>
<input type="button" class="button" style="background-color: #3CBC8D;padding:3px;" name="fcn2" value="Update My Status" />
Then go to jquery and use as below, success function change as you wish. Here I have used an alert box...
$(document).ready(function(){
$('.button').click(function(){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
else{
var clickBtnValue = $(this).attr('name');
var fetchdata= 'testme.php',
data = {'action': clickBtnValue};
$.post(fetchdata, data, function (response) {
// Response div goes here.
alert("Updated successfully -"+response);
});
}
});
});
Finally change your testme.php as follows,
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'fcn1':
fcn1();
break;
case 'fcn2':
fcn2();
break;
}
}
function fcn1() {
echo 'Button1 clicked';
exit;
}
function fcn2() {
sleep(5);
echo 'Button2 clicked';
exit;
}
Set the name to each button:
Button 1
Send data using ajax:
Get button text using e.target.text and send using POST method.
$.ajax({
type: 'POST',
url: 'test.php',
data: { buttonTitle: e.target.name},
success: function(data) {
$("p").text(data);
}
});
php:
Inside php use $_GET to get the data which we send from the frontend.
if(isset($_POST['buttonTitle'])) {
$buttonTitle = $_POST['buttonTitle'];
echo $buttonTitle . " clicked";
}
I have 2 HTML forms that contain dynamic ID attributes. What I want is to store data with AJAX call from each HTML form separately. Currently AJAX call works only for one HTML form when I use static ID name "surveyImage".
I don't know how I can with jQuery to call method submit() individually for each form. Is there any way to resolve this issue?
Form with id="surveyImage13"
<form method="POST" action="http://localhost/1/467/survey" accept-charset="UTF-8" id="surveyImage13" role="form" class="form-material m-t-40" novalidate="novalidate">
<div class="row">
<div class="col-lg-12">
<input name="questionnaire_pivot_id" id="questionnaire_pivot_id13" class="questionnaire_pivot_id" type="hidden" value="13">
<input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="1">
<input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">
...
<div class="row" style="margin-bottom: 5%;">
<div class="col-xl-2 col-lg-3 col-md-3">
<button id="add" class="btn btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
</div>
</div>
</form>
Form with ID="surveyImage18"
<form method="POST" action="http://localhost/2/467/survey" accept-charset="UTF-8" id="surveyImage18" role="form" class="form-material m-t-40" novalidate="novalidate">
<div class="row">
<div class="col-lg-12">
<input name="questionnaire_pivot_id" id="questionnaire_pivot_id18" class="questionnaire_pivot_id" type="hidden" value="18">
<input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="2">
<input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">
...
</div>
</div>
<div class="row" style="margin-bottom: 5%;">
<div class="col-xl-2 col-lg-3 col-md-3">
<button id="add" class="btn btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
</div>
</div>
</form>
AJAX call
<script type="text/javascript">
$("#surveyImage13").validate({
rules: {
'responses[]': {
required:true
}
},
// change name of error class that is assigned to input fields
errorClass: 'error_validate',
errorPlacement: function (label, element) {
// default
if (element.is(':radio')) {
label.insertAfter(element.parent('.form-check-inline'));
}
else {
label.insertAfter(element);
}
}
});
</script>
<script type="text/javascript">
$("#surveyImage13").submit(function(e) {
e.preventDefault();
var route=$('#surveyImage13').attr('action');
var pivot_id = $("#questionnaire_pivot_id").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline input').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $("#surveyImage13").valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'pivot_id': pivot_id},
success: function(response){
$("#surveyImageForm").css("display", "none");
$("#surveyImageAjax").css("display", "block");
$('#SurveyTableAjaxColumn1').append(response[1]);
$('#SurveyTableAjaxColumn2').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
</script>
Why not give your forms a common class
$('.myClass').validate({ ...
})
$('.myClass').submit(...
Based on your provided configuration, it should not be possible for jQuery to perform the submit action. The jQuery selector is #surveyImage, which does not match any id attributes in the provided HTML.
<form id="surveyImage13">...</form>
<form id="surveyImage18">...</form>
$("#surveyImage").submit...
I think you may be able to resolve the issue by using a different query selector string.
$('#surveyImage13 #surveyImage18').submit...
or...
$('form[id^="surveyImage"]').submit...
1.Instead of submit event use button click event
2.Get form id and store it
3.use this variable where you need id
$(".btn").click(function(e) {
e.preventDefault();
var formId = '#'+ $(this).parents('form').attr('id');
var route=$(formId).attr('action');
var pivot_id = $("#questionnaire_pivot_id").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline input').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $(formId).valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'pivot_id': pivot_id},
success: function(response){
$("#surveyImageForm").css("display", "none");
$("#surveyImageAjax").css("display", "block");
$('#SurveyTableAjaxColumn1').append(response[1]);
$('#SurveyTableAjaxColumn2').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
Thanks for all answers but I found solution. Im working in LARAVEL therefore I used foreach loop based on which i was able to assign dynamic ID on HTML forms.
#foreach($questionnaire_by_images as $t)
<form id="surveyImage{{$t->id}}">...</form>
<form id="surveyImage{{$t->id}}">...</form>
#endforeach
script
#foreach($questionnaire_by_images as $t)
<script type="text/javascript">
$( document ).ready(function() {
$("#surveyImage{{$t->id}}").validate({
rules: {
'responses[]': {
required:true
}
},
// change name of error class that is assigned to input fields
errorClass: 'error_validate',
errorPlacement: function (label, element) {
// default
if (element.is(':radio')) {
label.insertAfter(element.parent('.form-check-inline'));
}
else {
label.insertAfter(element);
}
}
});
$("#surveyImage{{$t->id}}").submit(function(e) {
e.preventDefault();
var route=$('#surveyImage{{$t->id}}').attr('action');
var survey_image_pivot = $("#survey_image_pivot{{$t->id}}").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline .radio{{$t->id}}').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $("#surveyImage{{$t->id}}").valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'survey_image_pivot': survey_image_pivot},
success: function(response){
$("#surveyImageForm{{$t->id}}").css("display", "none");
$("#surveyImageAjax{{$t->id}}").css("display", "block");
$('#SurveyTableAjaxColumn1{{$t->id}}').append(response[1]);
$('#SurveyTableAjaxColumn2{{$t->id}}').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
});
</script>
</script>
#endforeach
I have a login form that is working in a kinda same way I don't know why this won't work. When I press 'Criar' it does nothing, it doesn't even change the text of that Button to 'Loading ...' as I have stated on beforeSend function. I started using Jquery so sorry if it is a stupid mistake!
Form
<form id="criarSubCategoria-form" class="form-horizontal" role="form" action="criarCategoria.php" method="post">
<div class="col col-lg-4">
<label for="nome">Nome:</label>
<input type="text" class="form-control" id="nome" name="nome">
</div>
<br>
<div class="form-group margin-top-pq">
<div class="col-sm-12 controls">
<button type="button" class="btn btn-primary" name="btn-criarSubCategoria" id="btn-criarSubCategoria">
Criar
</button>
</div>
</div>
</form>
click Function
$('document').ready(function(){
$("#btn-login").click(function(){}); // this one is working so I didn't put all the code here
$("#btn-criarSubCategoria").click(function(){
var data = $("#criarSubCategoria-form").serialize();
$.ajax({
type : 'POST',
url : '../functions/criarCategoria.php',
data : data,
dataType: 'json',
beforeSend: function()
{
$("#btn-criarSubCategoria").html('Loading ...');
},
success : function(response){
if(response.codigo == "1"){
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'none')
}else{
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'block')
$("#mensagem").html('<strong>Erro! </strong>' + response.mensagem);
}
}
});
});
});
jQuery is not define. Or use jQuery instead of $ will works.
Change 1st line
jQuery(document).on("click", "#btn-criarSubCategoria", (function(e, $){
Try using this as your click function
$(document).on("click", "#btn-criarSubCategoria", (function(e){
var data = $("#criarSubCategoria-form").serialize();
e.preventDefault();
$.ajax({
type : 'POST',
url : '../functions/criarCategoria.php',
data : data,
dataType: 'json',
beforeSend: function()
{
$("#btn-criarSubCategoria").html('Loading ...');
},
success : function(response){
if(response.codigo == "1"){
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'none')
}else{
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'block')
$("#mensagem").html('<strong>Erro! </strong>' + response.mensagem);
}
}
});
});
Hope this gets your work done.
I'm new in web. This is my html:
<div class="modal fade" id="EditDocumentModal">
<div class="modal-dialog">
<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">Edit Vacation Types</h4>
</div>
<div class="modal-body">
<form action=#Url.Action(MVC.Admin.Admin.EditFile()) method="post" enctype="multipart/form-data" class="edit-file-form" id="Edit-File-Form">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default close-edit-document-button" data-dismiss="modal">Close</button>
<button type="button" form="Edit-File-Form" id="edit-Document-submit" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
And this is my JS:
$(document).on("click", "a.Edit-File-link", function (e) {
var id = $(this).data('id');
$.ajax({
url: '/Admin/Admin/EditFile/' + id,
cache: false
}).done(function (data) {
var div = '<div class = "checkbox-for-edit"></div>';
$('#Edit-File-Form').prepend(div);
$(".checkbox-for-edit").attr("data-id", data.documentId);
for (var i = 0; i < data.checkboxList.length; i++)
{
var checkBox = "<input type='checkbox' data-id = '" + data.checkboxList[i].Id + "' id='Edit-document-checkbox" + data.checkboxList[i].Id + "'/>" + data.checkboxList[i].Type + "<br/>";
$(checkBox).appendTo('.checkbox-for-edit');
if (data.checkboxList[i].IsSelected == true) {
$("#Edit-document-checkbox" + data.checkboxList[i].Id).prop('checked', true);
}
else {
$("#Edit-document-checkbox" + data.checkboxList[i].Id).prop('checked', false);
}
}
$('#EditDocumentModal').modal('show');
});
});
$(document).on("click", "button.close-edit-document-button", function (e) {
$(".checkbox-for-edit").remove();
});
$("#edit-Document-submit").click(function (e) {
$.ajax({
url: '/Admin/Admin/EditFile/',
type: 'POST',
data: {
documentId: $('.checkbox-for-edit').attr('data-id')
//put checkbox post logic here
},
cache: false,
dataType: "json",
success: function (data) {
}
});
});
As you can see, on click Edit-File-link I get checkboxes from the action and draw them on bootstrap modal window. This part work fine. Now I need to POST this checkboxes to my action. This is my action:
[HttpPost]
public virtual ActionResult EditFile(Guid documentId, List<VacationTypeViewModel> checkboxList)
{
throw new NotImplementedException();
}
So, Id I've posted well. But I don't know what should I do with my checkboxes on the bootstrap modal window.
First, you're not naming your checkboxes at all, so their values will never be posted. Update your checkbox creation code to add a name="checkboxList[]" attribute. Likewise, you also need to include a value="" attribute for each checkbox with something like the id you want posted back.
Second, the only thing that will ever be posted back from the checkboxes is the value you assigned, not the full VacationTypeViewModel you started off with. As a result, your action parameter should be something like List<int> checkboxList. If you need to work with the actual instances represented by the ids posted back, you'll need to requery them from the database based on the posted list of ints in your post action.
Here is my form's markup
<form name="contactForm" id="contactForm" role="form">
<div style="width: 190px">
<div class="form-group">
<input type="text" placeholder="fullname" name="fullname" id="formFullname" class="form-control">
</div>
<div class="form-group">
<input type="email" placeholder="email" name="email" id="fromEmail" class="form-control">
</div>
<div class="form-group">
<input type="text" placeholder="company" name="company" id="fromCompany" class="form-control">
</div>
</div>
<div class="clear"></div>
<div class="form-group">
<textarea placeholder="message" name="message" id="formMessage" rows="3" class="form-control"></textarea>
</div>
<button class="btn btn-success" type="submit" name="submit" id="formSubmit">send</button>
</form>
Using jquery 1.10.2
And here is JS
var form = $('#contactForm');
form.submit(function () {
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $(this).serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
I know that function fires, tested with alert. But console.log doesnt return anything, and during ajax call I don't see anything in POST (Watching with firebug's XHR).
BTW: role="form" is because i'm using Twitter Bootstrap framework
What am I doing wrong?
UPDATE
data: $(form).serialize() didn't help also
If you try this :
form.submit(function () {
console.log("form ", $(this).serialize());
return false;
});
it works just fine. So I think the problem
form.on('submit',function () {
event.preventDefault();
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $("form").serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
Because $(this) in your code doesn't refer to the form but instead refers to jQuery on which the ajax method is called
Try the following code, but first modify your form HTML so that is has an "action" attribute. The nice thing about this code is that it can be used on any form which has a submit button and an action attribute. (i.e. it is not coupled to any specific IDs)
$(function() {
$('input[type="submit"]').click(function(event) {
event.preventDefault();
var form = $(this).closest('form');
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function() {
alert('Yay! your form was submitted');
})
.fail(function() {
alert('Uh oh, something went wrong. Please try again');
});
});
Cheers.