How to know if Ajax Post was a success? - javascript

Current Code Example:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ActionName(ViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView(model);
}
var result = //something
if (result.Succeeded)
{
return PartialView(model);
}
AddErrors(result);
return PartialView(model);
}
Form Html
#model ViewModel
#using (Html.BeginForm("ChangePassword", "Manage", FormMethod.Post, new { #id = "Form"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #class = "text-danger" })
//Controls
<div class="form-group">
<input type="submit" value="Save" data-loading-text="Loading..." class="btn btn-default" />
</div>
}
JQuery code Template:
$("#Form").on('click', ".btn", function (e) {
e.preventDefault();
$.ajax({
url: "Something/ActionName",
//datatype: "text",
data: $('#Form').serialize(),
type: "POST",
success: function (data) {
$("#Form").html(data);
},
error: function (result) {
alert(result);
}
});
});
Now how can I know if an AJAX POST was a success and at the same time also returning the Partial View? Return PartialView to reset Form controls and clear error incase there were on the last post.
We can create a Json result with a var and RenderPartialView as string value. Please see MVC Return Partial View as JSON :
if (data.Result == "Success") {
alert("Data Saved");
}
$("#Form").html(data);
However, is there an easier option I am missing?

Related

How to get Ajax form to work in asp.net core

net core and I'm building a to do list app to learn but iv hit a road block trying to add an item to a to do list with out refreshing the page.
With my current setup the controller method to add a todo item to DB and a script to get refresh the html on page are called on form submit but the html is updated before item is added to DB.
Any suggestions on how to fix this or what is the best way to go about doing this would be greatly appreciated.
My Div for Table:
<div id="tableDiv"></div>
My Input form:
<div id="addTodoForm">
<form asp-action="AddToDoForm" method="post" data-ajax="true" >
<input asp-for="Item" class="form-control " placeholder="Add To Do Item.." />
</form>
</div>
My Script To update html (has a time out function as a temporary fix to this issue)
<script>
$("#addTodoForm").submit(function()
{
setTimeout(function(){
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
})
}, 500);
})
</script>
My method to add Item to DB:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddToDoForm([Bind("Id,Item")] ToDo toDo)
{
if (ModelState.IsValid)
{
string currentUserId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
IdentityUser currentUser = _context.Users.FirstOrDefault(x => x.Id == currentUserId);
toDo.User = currentUser;
toDo.Status = false;
_context.Add(toDo);
await _context.SaveChangesAsync();
}
return BuildToDoTable();
}
Not sure what is your whole code, here is a simple working demo about how to post data to backend and display the data from backend without refreshing:
View:
#model ToDo
<div >
<form method="post" id="addTodoForm">
<input asp-for="Id" class="form-control "/>
<input asp-for="Item" class="form-control " placeholder="Add To Do Item.." />
//focus here...it is type of button and add an onclick event here.....
<input type="button" value="Create" class="btn btn-primary" onclick="PostData()" />
</form>
</div>
<div id="tableDiv"></div>
#section Scripts {
<script>
function PostData() {
$.ajax({
type: "POST",
data: $("#addTodoForm").serialize(), //using this way to get the form data
url: '/Home/AddToDoForm',
success: function (result) {
$('#tableDiv').html(result);
}
})
}
</script>
}
Controller:
public class HomeController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddToDoForm([Bind("Id,Item")] ToDo toDo)
{
return PartialView("Partial", toDo);
}
}
Partial.cshtml(jsut a easy view for testing):
#model ToDo
#Model.Item //display the data
You can use e.preventDefault() which prevents the default behavior of submitting your form (refresh the page).
<script>
$("#addTodoForm").submit(function(e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
});
})
</script>
use this code:
<script>
$("#addTodoForm").submit(function(e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
});
location.reload();
})
</script>

asp.net mvc 4 - linq Contains operator is working as if it were a StartsWith operator

controller:
[HttpPost]
public JsonResult Index(string search)
{
var data = LoadExplore_SP("sp_View_Explore");
List<ExploreModel> stuff = new List<ExploreModel>();
foreach (var row in data)
{
stuff.Add(new ExploreModel
{
Thing_Title = row.Thing_Title
});
}
//Searching records from list using LINQ query
var ThingList = (from N in stuff
where N.Thing_Title.Contains(search)
select new { N.Thing_Title });
return Json(ThingList, JsonRequestBehavior.AllowGet);
}
view:
<script type="text/javascript">
$(document).ready(function () {
$("#Thing_Title").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Index",
type: "POST",
dataType: "json",
data: { search: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Thing_Title, value: item.Thing_Title };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.Thing_Title, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
}
My problem is that I can't get the linq where clause to work the way it should. Instead of returning results like %search%, it is returning all records like 'search%' instead.
Do you know why it's behaving this way?

how to hit controller action from a-usercontrol-ascx using ajax request

this is the ascx user control , i am trying to do ajax request then hit the controller but i have a problem and error message i can not find this CreateSubscribe/Create 404 (Not Found) error message.
any advice
<input type="text" id="subscribe-form-email" name="email" class="bg-transparent text-small no-margin border-color-medium-dark-gray" placeholder="Enter your email...">
<button id="button-subscribe-newsletter" type="button" class="btn btn-arrow-small position-absolute border-color-medium-dark-gray">
<i class="fa fa-caret-right no-margin-left"></i></button>
<script type="text/javascript">
$("#button-subscribe-newsletter").click(function () {
debugger
if ($('#subscribe-form-email').val().length > 0)
{
var dataToPost = {
subscriberemail: $("#subscribe-form-email").val(),
}
$.ajax({
dataType: "json",
url: 'CreateSubscribe/Create',
type: 'post',
data: JSON.stringify(dataToPost),
success: function (result) {
if (result) {
$("#Subscribe-Area").hide();
$("#Success-Message").show();
}
else {
$("#Failed-Message").show();
}
},
error:function
(err)
{
alert(err.message);
}
});
}
});
</script>
this is the controller
public class CreateSubscribeController : Controller
{
// GET: CreateSubscribe
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Create(string subscriberemail)
{
var keys = new Dictionary<string, string>() {
{ "Email",subscriberemail }
};
if (SitefinityWebApp.Helpers.SitefinityHelper.CreateSubscriberAndAddToMailingList(MailList.Maillist, subscriberemail))
{
SitefinityWebApp.Helpers.SitefinityHelper.SendEmailByTemplate(EmailTemplates.SubscribeEmail, subscriberemail, keys);
return Json(new { val = true }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { val = false }, JsonRequestBehavior.AllowGet);
}
}

How to serialize forms and post using jQuery Ajax

I'm trying to remove records from my DB......
this is how my form looks like.........
#using (Html.BeginForm("RemoveDoctor", "Doctor", FormMethod.Post, new { #id = "form" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.Id)
#Html.HiddenFor(model => model.Name)
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" id="submit" /> |
</div>
}
I'm trying to get these records from the view and pass to my controller Action method............................. i'm trying to serialize this form and send it to that action method as following...................
var jsonObj = $('#form').serialize();
it serialize the form put my Ajax POST function wont run with that result......
it just gives me an error!!!!................. I just need to pass that serialize value to my Action method............... This is how my Script looks like.....................
$('#submit').click(function () {
var jsonObj = $('#form').serialize();
alert(jsonObj);
$.ajax({
type: "POST",
url: '../Doctor/RemoveDoctor',
data: JSON.stringify({ "doctor": jsonObj }),
success: function (data) {
alert(data.Message);
},
error: function () {
alert("Error!!!");
}
});
return false;
});
This is how my action method looks like....................
public ActionResult RemoveDoctor(DoctorModel doctor)
{
bool confirmationResult = doctorManager.RemoveDoctor(doctor.Id);
string displayMessage = string.Empty;
if (confirmationResult == true)
displayMessage = "You have successfully removed your record!!";
else
displayMessage = "Error!! Some Thing Went Wrong, Please Try Again!!";
return Json(new { Message = displayMessage });
}
I'm trying to send this 'displayMessage' to my jQuery code........ please some give me an idea how to solve this....... thanks!!!!!
Try this
$.ajax({
type: "POST",
url: '../Doctor/RemoveDoctor',
data: $('#form').serialize(),
success: function (data) {
alert(data.Message);
},
error: function () {
alert("Error!!!");
}
});
It will serialize your form.
Use only $('#form').serialize() for serialization.
Edit
If you don't want to refresh page then you should use type="button" instead type="submit"
And
You should do this also
[HttpPost]
public ActionResult RemoveDoctor(DoctorModel doctor)
{
//...................
return Json(new { Message = displayMessage } , JsonRequestBehavior.AllowGet);
}
And change ajax error function to this (For getting error )
error: function(jqXHR, textStatus, errorThrown)
{
alert("Error: "+errorThrown+" , Please try again");
}

Return javascript to view from controller

I am returning javascript from controller to view through ajax. but it gives me failure message, my code is given below.
My controller is
public ActionResult GetJava()
{
if (Request.IsAjaxRequest())
{
return JavaScript("<script>alert(\"some message\")</script>");
}
else
{
return View();
}
}
and view is
#{
ViewBag.Title = "GetJava";
Scripts.Render("~/bundles/jquery");
}
<h2>GetJava</h2>
<div><input type="button" value="GetJava" onclick="Getjavascript()" /></div>
<script type="text/javascript">
function Getjavascript() {
$.ajax({
url: '#Url.Action("GetJava","BindingJson")',
dataType: 'applicaiton/javascript;charset=utf-8',
type: 'Get',
data: 'script',
success: function (status) { status.value },
error: function (status) { alert("failure") }
});
}
</script>
What could be the possible issue?
You can create a script with src to your action, as suggested in this answer: https://stackoverflow.com/a/6778069/4251546
var script = $('<script />', {src: '#Url.Action("GetJava","BindingJson")'});
$(document).append(script)

Categories