Select2 - not working in bootstrap 3 with tabindex removed? - javascript

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>

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

Refreshing Modal content with Jquery Ajax

I'm having issues with getting a form loaded into a modal in BS4 to repost (post to self in affect), check the form input, and re-load the modal div with the error, or re-direct to checkout page.
The initial Ajax loading of the form from select.php loads well, but upon pressing the submit button on the form within select.php in the modal, I just get no response at all from the button, as if the button it dead, nothing shown in console etc.
Any ideas at all? I'm new to using JQ and Ajax etc, but it seems quite close to what other people are doing in their code.
<script>
$(document).ready(function() {
$('.view_data').click(function() {
var eventID = $(this).attr("id");
$.ajax({
url: "select.php",
method: "post",
data: {
eventID: eventID,
selectToken: 'true'
},
success: function(data) {
$('#modal-body').html(data);
$('#ticketsModal').modal("show");
}
});
});
// process the form in select.php shown in the modal
$('#ticketForm').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'maleplaces': $('input[name=maleplaces]').val(),
'femaleplaces': $('input[name=femaleplaces]').val(),
'friendplaces': $('input[name=friendplaces]').val(),
'eventID': $('input[name=eventID]').val(),
'ticketSubmit': $('input[name=ticketSubmit]').val()
};
$.ajax({
type: 'POST',
url: 'select.php',
data: formData,
dataType: 'json',
encode: true
})
// using the done promise callback
.done(function(data) {
$('#modal-body').html(data);
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
The Modal code on the main.php page is here as requested:
<!-- Modal -->
<div class="modal fade" id="ticketsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Select </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal End-->
Here is the form in select.php:
<form id="ticketForm" name="ticketForm" method="post" action="select.php">
<div class="form-group">
<select name="maleplaces" id="maleplaces" class="custom-select">
<option value="0" selected>Male Tickets (0)</option>
<option value="1">Male Tickets (x1)</option>
<option value="2">Male Tickets (x2)</option>
<option value="3">Male Tickets (x3)</option>
<option value="4">Male Tickets (x4)</option>
<option value="5">Male Tickets (x5)</option>
</select>
</div>
<div class="form-group">
<select name="femaleplaces" id="femaleplaces" class="custom-select">
<option value="0" selected>Female Tickets (0)</option>
<option value="1">Female Tickets (x1)</option>
<option value="2">Female Tickets (x2)</option>
<option value="3">Female Tickets (x3)</option>
<option value="4">Female Tickets (x4)</option>
<option value="5">Female Tickets (x5)</option>
</select>
</div>
<div class="form-group">
<select name="friendplaces" id="friendplaces" class="custom-select">
<option value="0" selected>Double Tickets (0)</option>
<option value="1">Saver Tickets (x1)</option>
<option value="2">Saver Tickets (x2)</option>
<option value="3">Saver Tickets (x3)</option>
<option value="4">Saver Tickets (x4)</option>
<option value="5">Saver Tickets (x5)</option>
</select>
<input name="eventID" type="hidden" id="eventID" value="<?php echo $event['event_id']; ?>" />
<input name="ticketSubmit" type="hidden" id="ticketSubmit" value="<?php echo $event['event_id']; ?>" />
</div>
</div>
<div class="col-auto my-1">
<button type="submit" id="ticket_btn" class="btn btn-primary" onclick="return doubleticketFunction()">Continue to payment</button>
</div>
</form>
Because you dynamically change your #ticketForm element you lose the bind with the submit event listener when you replace your form. You'll have to either rebind the event or use event delegation to listen for the events. In this example I've chosen the former to elaborate.
First take your function that you use in the $('#ticketForm').sumbit and name it. You'll be using this function to bind the first form and all the forms that replace it.
function ticketFormSubmit(event) {
// Use jQuery serialize to get the form values.
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'select.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
$('#modal-body').html(data);
console.log(data);
});
event.preventDefault();
}
In the succes callback of your $.ajax call select the newly added form and add the event listener to it like in the example below.
$('.view_data').click(function()
var eventID = $(this).attr("id");
$.ajax({
url: "select.php",
method: "post",
data: {
eventID: eventID,
selectToken: 'true'
},
success: function(data) {
$('#modal-body').html(data);
$('#ticketsModal').modal("show");
// Bind new submit event listener
$('#ticketForm').on('submit', ticketFormSubmit);
}
});
});

Why can't the edit-modal fetch the data(of the selected row) from my database?

So this is my brand.php file
And it portrays the edit part of the brand
so in this part we can probably see how the thing will look like
<!-- edit brand -->
<div class="modal fade" id="editBrandModel" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" id="editBrandForm" action="php_action/editBrand.php" method="POST">
<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"><i class="fa fa-edit"></i> Edit Brand</h4>
</div>
<div class="modal-body">
<div id="edit-brand-messages"></div>
<div class="modal-loading div-hide" style="width:50px; margin:auto;padding-top:50px; padding-bottom:50px;">
<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
<span class="sr-only">Loading...</span>
</div>
<div class="edit-brand-result">
<div class="form-group">
<label for="editBrandName" class="col-sm-3 control-label">Brand Name: </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="editBrandName" placeholder="Brand Name" name="editBrandName" autocomplete="off">
</div>
</div> <!-- /form-group-->
<div class="form-group">
<label for="editBrandStatus" class="col-sm-3 control-label">Status: </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<select class="form-control" id="editBrandStatus" name="editBrandStatus">
<option value="">~~SELECT~~</option>
<option value="1">Available</option>
<option value="2">Not Available</option>
</select>
</div>
</div> <!-- /form-group-->
</div>
<!-- /edit brand result -->
</div> <!-- /modal-body -->
<div class="modal-footer editBrandFooter">
<button type="button" class="btn btn-default" data-dismiss="modal"> <i class="glyphicon glyphicon-remove-sign"></i> Close</button>
<button type="submit" class="btn btn-success" id="editBrandBtn" data-loading-text="Loading..." autocomplete="off"> <i class="glyphicon glyphicon-ok-sign"></i> Save Changes</button>
</div>
<!-- /modal-footer -->
</form>
<!-- /.form -->
</div>
<!-- /modal-content -->
</div>
<!-- /modal-dailog -->
</div>
<!-- / add modal -->
<!-- /edit brand -->
> --this one is the end part
And this is the fetching part, wherein once you click the button from the row(example row 1), a modal(Edit Modal will likely appear), but the thing is, once the modal appear, the data that is supposed to be fetched from the row is not on that modal ;-;
<?php
require_once '../../includes/connection.php';
$brandId = $_POST['brandId'];
$sql = "SELECT brand_id, brand_name, brand_active, brand_status FROM brands WHERE brand_id = $brandId";
$result = $connect->query($sql);
if($result->num_rows > 0) {
$row = $result->fetch_array();
} // if num_rows
$connect->close();
echo json_encode($row);
?>
Now the JScript part
This part is the filler part(like getting the data and now portraying the data and filling the input boxes etc..)
function editBrands(brandId = null) {
if(brandId) {
// remove hidden brand id text
$('#brandId').remove();
// remove the error
$('.text-danger').remove();
// remove the form-error
$('.form-group').removeClass('has-error').removeClass('has-success');
// modal loading
$('.modal-loading').removeClass('div-hide');
// modal result
$('.edit-brand-result').addClass('div-hide');
// modal footer
$('.editBrandFooter').addClass('div-hide');
$.ajax({
url: 'fetchSelectedBrand.php',
type: 'post',
data: {brandId : brandId},
dataType: 'json',
success:function(response) {
// modal loading
$('.modal-loading').addClass('div-hide');
// modal result
$('.edit-brand-result').removeClass('div-hide');
// modal footer
$('.editBrandFooter').removeClass('div-hide');
// setting the brand name value
$('#editBrandName').val(response.brand_name);
// setting the brand status value
$('#editBrandStatus').val(response.brand_active);
// brand id
$(".editBrandFooter").after('<input type="hidden" name="brandId" id="brandId" value="'+response.brand_id+'" />');
// update brand form
$('#editBrandForm').unbind('submit').bind('submit', function() {
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
var brandName = $('#editBrandName').val();
var brandStatus = $('#editBrandStatus').val();
if(brandName == "") {
$("#editBrandName").after('<p class="text-danger">Brand Name field is required</p>');
$('#editBrandName').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#editBrandName").find('.text-danger').remove();
// success out for form
$("#editBrandName").closest('.form-group').addClass('has-success');
}
if(brandStatus == "") {
$("#editBrandStatus").after('<p class="text-danger">Brand Name field is required</p>');
$('#editBrandStatus').closest('.form-group').addClass('has-error');
} else {
// remove error text field
$("#editBrandStatus").find('.text-danger').remove();
// success out for form
$("#editBrandStatus").closest('.form-group').addClass('has-success');
}
if(brandName && brandStatus) {
var form = $(this);
// submit btn
$('#editBrandBtn').button('loading');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success:function(response) {
if(response.success == true) {
console.log(response);
// submit btn
$('#editBrandBtn').button('reset');
// reload the manage member table
manageBrandTable.ajax.reload(null, false);
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
$('#edit-brand-messages').html('<div class="alert alert-success">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
'</div>');
$(".alert-success").delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
}); // /.alert
} // /if
}// /success
}); // /ajax
} // /if
return false;
}); // /update brand form
} // /success
}); // ajax function
} else {
alert('error!! Refresh the page again');
}
} // /edit brands function
Can you check the Network tab to see the result from server? You can debug your app by seeing that result.
By the way, there're two things that you may need to edit:
1/ If brandId is interger, you need to get it from $_GET by intval($_POST['brandId']) to prevent SQL Injection.
2/
if($result->num_rows > 0) {
$row = $result->fetch_array();
}
else {
$row = array();
}
your code need to return empty array if sql result is empty to avoid Undefined variable error.

Sending data using ajax to the controller in rails

I am new to JS and rails so recently facing lots of difficulties about using ajax in rails environment. I will very appreciate if you contribute to developing my project. What I am trying to do is that Once a user selects data from the modal, I want to send the selected data to an action in the controller so that I can handle the data. I am not really sure where I can start with that. Please help guys :( Thanks a lot
view:
<form id= "selected_form" action="" method="">
<div id= "selected_form">
<p id="checkids"></p>
</div>
</form>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<div>
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Select Task</h4>
</div>
<div class="modal-body">
<fieldset>
<% #tasks.each do |task|%>
<div>
<label><input type="checkbox" value="<%=task.id%>" name="selected"><%=task.title%></label>
</div>
<% end %>
</fieldset>
</div>
<div class="modal-footer">
<button type="button" id="save" class="btn btn-default" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div>
JS
<script>
$(function(){
$(document).ready(function(){
$("#save").click(function(){
var checkedItem = [];
$.each($("input[name='selected']:checked"), function(){
checkedItem.push($(this).val());
});
$('#values').html("selected values are: " + checkedItem.join(", "));
$.ajax({
type: "POST", // request method for your action like get,post,put,delete
url: "/users/<%= current_user.id %>/test", // route of your rails action
data: {checked_items: checkedItem.join(", ")}, // attach data here you will get this data in your controller action with params[:checked_items]
success: function(data, textStatus, jqXHR){}, // do whatever you want when it success
error: function(jqXHR, textStatus, errorThrown){}
})
});
});
});
</script>
Please check script below
<script>
$(function(){
$(document).ready(function(){
$("#save").click(function(){
var checkedItem = [];
$.each($("input[name='selected']:checked"), function(){
checkedItem.push($(this).val());
});
$('#values').html("selected values are: " + checkedItem.join(", "));
$.ajax({
type: "POST", // request method for your action like get,post,put,delete
url: "/things", // route of your rails action
data: {checked_items: checkedItem }, // attach data here you will get this data in your controller action with params[:checked_items]
success: function(data, textStatus, jqXHR){...}, // do whatever you want when it success
error: function(jqXHR, textStatus, errorThrown){...}
})
});
});
});
</script>
For simplicity you can inject rails path to that controller as dataset attribute.
for e.g
<form method="post" data-url="<%= tasks_path %>">
and in js part
$('#save').on('click', function (e) {
e.preventDefault();
$.ajax({
type: $(this).method || "GET",
url: this.dataset.url,
data: $(this).serialize(),
success: function (response) {
console.log(response)
},
error: function (error) {
console.log(error);
}
});
});

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