Reputation: 22556
I am submitting a form with JavaScript.
Here is my form:
<form id="rolesSelectForm" class="stdform" action="" onsubmit="return submitForm()">
<p>
<label>Select User</label>
<span class="field">
<select name="selectUser" id="selectUser">
@foreach (var item in Model.Users)
{
<option value="@item.Id">@item.UserName</option>
}
</select>
</span>
</p>
<p class="stdformbutton">
<button class="submit radius2" type="submit">Save</button>
</p>
And here is my script:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.userId = jQuery('#selectUser').val();
model.rolesList = usersRoles;
console.log('model: ' + 'user: ' + model.userId + 'roles: ' + model.rolesList);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "@Url.Action("AddUser")",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { showSuccessMessage(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
//Shows the success message
function showSuccessMessage(data) {
alert(data);
}
Now when I click the button, the page does refresh and I never get my alert.
In chrome its at least makes the ajax post request but in Firefox, it just reloads the page before the post is even made.
From what I read if I made my form return the JavaScript function, it would not reload. However this is not my case.
Upvotes: 0
Views: 50
Reputation: 12117
Please add return false
in function
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.userId = jQuery('#selectUser').val();
model.rolesList = usersRoles;
console.log('model: ' + 'user: ' + model.userId + 'roles: ' + model.rolesList);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "@Url.Action("AddUser")",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { showSuccessMessage(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
return false;
}
Upvotes: 0
Reputation: 943214
From what I read if I made my form return the java script function it would not reload.
No. You have to return false
.
This is typically done by returning the return value of the function, and then returning false
from that function. A lot of the time this will be done conditionally (since often you will be testing the user input to make sure it is OK before allowing the form to submit.)
You don't have a return
statement in your function.
Upvotes: 2