I do have form within a modal . What I’m trying to accomplish is to override the default POST method and use AJAX. I do it to prevent page switches. However it seems like script is not getting triggered. If I remove script normal POST occurs. Here is the code:
<div class="modal" id="modal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="process.php" method="POST" id="submitform">
<div class="modal-body">
<div class="form-group">
<label for="source">source:</label>
<textarea class="form-control" id="kaynak" name="kaynak" rows="6"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">İptal</button>
<button type="submit" class="btn btn-primary ">Kaydet</button>
</div>
</form>
</div>
</div>
$(document).ready(function() {
$('#submitform').submit(function(event) {
event.preventDefault();
var post_url = $(this).attr("action");
var request_method = $(this).attr("method");
var formData = $(this).serialize();
var username = "<?php echo $username ?>";
formData.push({
name: 'username',
value: username
});
$.ajax({
type: request_method,
url: post_url,
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
})
2
Answers
Try:
You want to use
.serializeArray()
not serialize since it returns a string and you want an array to add fields to it.