JSFiddle - React, Tailwind, and code Playground
by ufomammut66
HTML
<form id="fakeform" name="fakeform" method="post" action="somewhere">
name: <input name="name" type="text" />
other: <input name="other" type="text" />
<input type="submit" id="dontDoIt" />
</form>
JavaScript
$(function(){
$('#fakeform').submit(function(e){
alert('stopped submit, now do ajax submit');
var url = $(this).prop('action');
var nameData = $('.name').val();
var otherData = $('.data').val();
// Do some ajax call - this is just a quick non-working example.
$.ajax({
type : "POST",
url : url,
data : {
'name' : nameData,
'other' : otherData
},
success : function(data){
console.log("yay! successful response back from server! Lets see what we got");
console.log(data);
},
error : function(x,h,r){
console.warn("Oh no! Ajax error - something went wrong!");
console.error(x);
console.error(h);
console.error(r);
},
dataType : 'json'
});
submitNormally = false;
// Something to check if you want to fall back to normal form submission
if(3 === 2){
submitNormally = true;
}
if(submitNormally == true){
// if we want to submit the form normally at this point we can
// by returning true out of this function
return true;
}
// return false to stop the page from submitting
return false;
});
});