Reputation: 684
I'm trying to posting form using jQuery. I saw many tutorial but any works in my cas. So now i'm trying from the simples cases.
Now when I submit my form I woudl like to show message in console :
$("#new-period-form").submit(function (event) {
console.log("Form submitted");
});
But this event newer occured.
<form action="#" id="new-period-form"
th:object="${currentPeriodForm}" method="post">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text"
id="period"
th:field="*{period}"
pattern="^((19|20)\d\d)-(0?[1-9]|1[012])$"/>
<label class="mdl-textfield__label" for="period">Text...</label>
<span class="mdl-textfield__error">Input is not a valid format</span>
</div>
<input id="submit-new-period" type="submit" value="save"> SUBMIT</input>
</form>
I noticied thatmapping /admin/newperiod is never invoked. Submit button send request directly to main page ( sow at beginning I was havins all times errors of POST not allowed).
What I do wrong ?? :(
Upvotes: 1
Views: 9415
Reputation: 684
OK I was find the solution.
I dont know why exactly it works like that.. but...
$(document).on('click', '#button-new-period', function(e) {
var url = "/admin/gestion-period-new";
$.ajax({
type : "GET",
url : "/admin/gestion-period-new",
timeout : 100000,
dataType: "html",
success : function(data) {
**$("#content-period").replaceWith(data);
window.componentHandler.upgradeDom();**
},
error : function(e) {
console.log("ERROR: ", e);
},
done : function(e) {
console.log("DONE");
}
});
e.preventDefault();
});
What is still a secret for me, that why this works :
$("#content-period").replaceWith(data);
window.componentHandler.upgradeDom();
And this not :
$("#content-period").load(url);
window.componentHandler.upgradeDom();
Controller for load new period form
@RequestMapping("gestion-period-new")
public String gestionPeriodNew(CurrentPeriodForm currentPeriodForm) {
return View.PAGE_ADMIN_CONTENT_GESTION_PERIOD_NEW;
}
And View.PAGE_ADMIN_CONTENT_GESTION_PERIOD_NEW
public static final String PAGE_ADMIN_CONTENT_GESTION_PERIOD_NEW = "admin-page/gestion-period :: content-new-period";
Upvotes: 0
Reputation: 5948
To make it work you just need to do few small changes.
In your submit button change the type to button, as you will handle it now with jquery
<input id="submit-new-period" type="button" value="save"> SUBMIT</input>
Create an event click for that button and attach a jquery function similar to this.
$(function() {
$('#submit-new-period').click(saveForm);
});
function saveForm(){
$.ajax({
method: "POST",
url: "/your/action/endpoint",
data: $('#idYourForm').serialize(),
success: function(status){
if(status) {
//here you check the response from your controller and add your business logic
}
}
});
}
Remember in your controller add the annotation @ResponseBody as you are going to handle it by JS
Upvotes: 3