I try to insert data to database with .NET Core Framework with AJAX hope this can return json response when it success, it success but i don't know it throws me to page fill it the response of json, not still in page when i insert the data. (sorry for link image, i'm not yet proper to upload image, stackoverflow say)
This is output i get;
https://i.stack.imgur.com/x7UY4.png
This is create in contoller;
https://i.stack.imgur.com/0StbY.png
This is my javascript code;
var isDuplicate = true;
$("#formProduct").validate({
rules: {
NameProduct: {
required: true,
minlength: 5
}
},
messages: {
NameProduct: {
required: "Data tidak boleh kosong",
minlength: "Minimal 5 huruf"
}
},
submitHandler:function(form){
debugger;
if (isDuplicate) {
return false;
} else {
submitAJAX(form);
}
debugger;
}
});
function submitAJAX(form) {
var fromData = new FormData();
var dataForm = $(form).serializeArray();
$.each(dataForm, function (key, input) {
fromData.append(input.name, input.value);
});
var file = $("#ImageFile").prop("files");
if (file.length > 0) {
fromData.append("ImageFile", file[0]);
}
$.ajax({
url: "/Product/Create",
data: fromData,
method: "post",
dataType: "json",
success: function (response) {
var data = response;
if (data.success) {
$("#modal_sm").modal("hide");
toastr.success("Data success input");
window.location.reload();
}
else {
$("#modal_sm").modal("hide");
toastr.error("Data failed input");
}
}
});
}
I hope can run ajax without get throw to page json result
CodePudding user response:
I guess you used <input type="submit"/>
or <button></button>
which will automatically submit the form when it is clicked.
Here is a whole working demo:
Model
public class VMProduct
{
public string Name { get; set; }
public int Age { get; set; }
public IFormFile ImageFile { get; set; }
}
public class VMResponse
{
public bool Success { get; set; }
public string Message { get; set; }
}
View
@model VMProduct
<form>
<input type="file" asp-for="ImageFile" />
<input asp-for="Age" />
<input asp-for="Name" />
<input type="submit" value="Post"/>
</form>
@section Scripts
{
<script>
$('form').on('submit', function(e) {
var submittedform = $(this);
e.preventDefault(); //be sure add this if you use submit button
submitAJAX(submittedform);
});
function submitAJAX(form) {
var fromData = new FormData();
var dataForm = $(form).serializeArray();
$.each(dataForm, function (key, input) {
fromData.append(input.name, input.value);
});
var file = $("#ImageFile").prop("files");
if (file.length > 0) {
fromData.append("ImageFile", file[0]);
}
$.ajax({
url: "/Product/Create",
data: fromData,
method: "post",
contentType: false, //be sure add this...
processData: false, //be sure add this...
dataType: "json",
success: function (response) {
var data = response;
if (data.success) {
//do your stuff...
}
else {
//do your stuff...
}
}
});
}
</script>
}