I created an Ajax call & tried to debug its success & failure in chrome using debugger;
.
The first debugger statement works properly but the flow is not stopping at the second debugger statement and instead I see following in sources panel:
<script type="text/javascript" id="debugbar_loader" data-time="1611085354" src="http://localhost/my_project/public/?debugbar"></script><script type="text/javascript" id="debugbar_dynamic_script"></script><style type="text/css" id="debugbar_dynamic_style"></style>
Ajax is also working properly as I receive POST data in server. Kindly advise.
<form action="#" method="POST">
<button type="submit" name="submit_form" class="btn" id="submit_form">Save Changes</button>
</form>
$(document).ready(function() {
// First Debugger
debugger;
$("#submit_form").submit(function(e) {
e.preventDefault();
var fd = new FormData($(this)[0]);
// Second Debugger
debugger;
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: fd,
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
},
});
});
});
The issue is because the submit
event fires on the form
element, not the button
you've selected.
In fact the entire submit
handler assumes that this
refers to the form
element, given you use of attr('action')
and passing the reference to the FormData()
constructor.
Also note that if you're sending FormData in the AJAX request then you will also need to include processData: false
and contentType: false
in the AJAX options.
With all that said, try this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST" id="submit_form">
<button type="submit" name="submit_form" class="btn">Save Changes</button>
</form>
$(document).ready(function() {
console.log('A'); // debugger
$("#submit_form").submit(function(e) {
e.preventDefault();
var fd = new FormData(this);
var url = this.action;
console.log('B'); // debugger
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: fd,
contentType: false,
processData: false,
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});