i'm trying to submit forms without post back via ajax ..my code doesn't work
whats wrong in my script?
i'm new to ajax..help me with ajax scripts..
below is my code
note: i have two submit buttons with in single view. I want to make ajax call for both submit actions
my view
#model AjaxEF.Models.Customer
#using (Html.BeginForm("Index", "Main", FormMethod.Post,new { id="idForm"}))
{
#Html.EditorForModel()
<br />
<input type="submit" name="save" value="Save" />
<input type="submit" name="cancel" value="Cancel" />
}
<script>
$("#idForm").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var url = "~/Main/Result"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function (data) {
alert(data); // show response from the php script.
}
});
});
</script>
my controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Customer obj, string save, string cancel)
{
if (!string.IsNullOrEmpty(save))
{
ViewBag.Message = "Customer saved successfully!";
}
if (!string.IsNullOrEmpty(cancel))
{
ViewBag.Message = "The operation was cancelled!";
}
return View("Result", obj);
}
public ActionResult Result()
{
return View();
}
Not sure why the other answer was deleted, but it was 100% correct. The URL you're hitting with your AJAX is your Result action, which does nothing but return a view. You need to post to your Index action, and since the form is already set to post there, the best way to get that URL for your AJAX is to select it from the form:
var url = $('#idForm").attr("action");
Related
I have an Edit action. When the Action is invoked I expected the Edit view to render but it does not. The view is Edit.cshtml. I have a similar view Add.cshtml which works fine (Add is a button and Edit is a link inside the grid.
The Controller method
[HttpPost]
public IActionResult Edit(int Id)
{
try
{
var jurisdictionId = _user.Current().JurisdictionId;
OrganizationType ot = new OrganizationType();
ot.Id = Id;
ot.OrganizationName = _electedOfficials.getOrgTypeName(jurisdictionId, Id);
return View(ot);
//return View("Edit", ot);
}
catch (Exception e)
{
_logger?.LogCritical(new EventId(101, "CAdminOrganizationType"), e, $"Error when loading Edit Orginization Type View");
throw;
}
}
The Edit View (Edit.cshtml)
#model Platinum.Entities.OrganizationType
#{
ViewData["Title"] = "Editing Organization Type";
}
<div class="card pd-20 pd-sm-40">
<div class="form-layout">
<form asp-action="Edit">
<div class="row mg-b-25">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="Id" hidden />
<div class="col-md-2">
<div class="form-group">
<label asp-for="OrganizationName" class="form-control-label">Name</label>
<input asp-for="OrganizationName" class="form-control" />
<span asp-validation-for="OrganizationName" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-layout-footer">
<input type="submit" value="Create Organization Type" class="btn btn-default mg-r- 5" />
<a asp-action="Index" class="btn btn-danger mg-r-5">Back</a>
</div>
</form>
</div>
</div>
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
});
</script>
}
The Javascript that executes when Edit is clicked in the Index view
function Edit(id) {
var url = '/CAdminOrganizationType/Edit/' + id
$.ajax({
type: "POST",
url: url,
contentType: "application/json"
}).fail(function () {
magalert.communicationError();
});
}
As far as I know, we couldn't render page without returning to ajax response.
Since the ajax will send the request to the controller action and the action returns the view as html response back to the ajax.
But you do not handle the response in ajax so that the current page will not change.
If you just want to pass the Id to Edit method and return the Edit view, I suggest you could try to use window.location, this will make this page redirect to the Edit view which achieve refresh the whole page.
Besides window.location only supports get method.I suggest you use [HttpGet] method to render the page, and then load the page in the success function in ajax.
Here is my code:
Ajax
#section Scripts
{
<script>
function Edit(id) {
var url = '/Home/Edit/' + id
$.ajax({
type: "get",
url: url,
contentType: "application/json",
success:function(){
window.location.href="/Home/Edit/"+id
},
error:function () {
magalert.communicationError();
}
});
}
</script>
}
The Controller Method
[HttpGet]
public IActionResult Edit(int Id)
{
try
{
var jurisdictionId = _user.Current().JurisdictionId;
OrganizationType ot = new OrganizationType();
ot.Id = Id;
ot.OrganizationName = _electedOfficials.getOrgTypeName(jurisdictionId, Id);
return View(ot);
}
catch (Exception e)
{
_logger?.LogCritical(new EventId(101, "CAdminOrganizationType"), e, $"Error when loading Edit Orginization Type View");
throw;
}
}
Then,you can load the View
I'm uploading a file via a form with the following script tag:
#using (Html.BeginForm("CreateCompResponse", "Surveys", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "return myFunction()" }))
Upon successful upload, the controller should RedirectToAction:
return Json(new
{
redirectUrl = Url.Action("CreateBenefitSummary", "Surveys"),
isRedirect = true
});
In the view, I'm handling the function as follows (I copied and pasted this from another SO post, as I don't know JavaScript):
<script type="text/javascript">
success: function(json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
}
</script>
Rather than returning my desired controller action, it returns a JSON string:
{"redirectUrl":"/Surveys/CreateBenefitSummary","isRedirect":true}
How can I get this to redirect to the proper action?
Thanks!
You are using Html.BeginForm which means that the ActionResult you expect is in the PostBack. The way return Json will work is if you use Ajax.BeginForm and pass the function name to it for onsuccess. You should be doing this:
#using (Ajax.BeginForm("CreateCompResponse", "Surveys", new AjaxOptions { OnSuccess = "onSuccess",HttpMethod = "Post" }))
And your function should be
<script type="text/javascript">
function onSuccess(json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
}
</script>
If you want to use PostBack then you can use RedirectToAction within the processing controller action to check if the upload is successful or not based on the result you can use the above mentioned return RedirectToAction or return View()
Is there a way I can get the returned value from an action using .submit event listener in jQuery?
I have a problem which is when the action is completed it returns a JSON file and my browser navigates to an empty page and just display the JSON returned. I don't want that to happen, I want to be able to read the JSON result and based on it decide what to do.
Here's my POC:
View:
#using (Html.BeginForm("SubmitTest", "DMS", FormMethod.Post, htmlAttributes: new { id = "formId" }))
{
<input type="submit" value="Sumbit" />
}
Controller:
public JsonResult SubmitTest()
{
return Json("Done");
}
Script:
$(document).ready(function () {
$("formId").submit(function () {
alert("Submitted");
});
});
you can add event.preventDefault or return false to prevent the default event from occurring . so it won't navigate to an empty page.
$(document).ready(function () {
$("formId").submit(function () {
alert("Submitted");
return false;
});
});
EDIT:
if you want to get the response you need to make an ajax request and get the form data from the fields. you can't get the response with submit function.
$(document).ready(function () {
$("formId").submit(function () {
/// make an AJAX request
$.post(
$(this).attr('action'), //// action url
$(this).serialize(), //// serialize form fields
function(json) {
alert(json);/// json response
}, 'json');
return false; /// prevent navigation
});
});
Use an AJAX form instead of the HTML form, this way you can check the response after it is submitted and do whatever you need using the OnSuccess handler.
For detailed info refer to this article
I have a special case where I need to have a grid with an "Add New Record" row, that exists within an MVC form.
Since I can't submit the new record details, without submitting the entire form, I decided to make the record submit button call a Javascript method that should POST the data to a method on my controller. In short, here is an example of what I'm doing. The code below is copy-and-pasted from my project, with only minor modifications for brevity.
...
<table>
CODE HERE FOR MY GRID...
</table>
...
<input class="data_field" id="MainSession_Name" type="text" />
<input class="data_field" id="MainSession_Type" type="text" />
<button id="btnAddMainSession" class="button" onclick="SubmitMainSession()" type="button">Add Session</button>
...
<script>
var SubmitMainSession = function()
{
var data = {
Name: $('MainSession_Name').val(),
RecType: $('MainSession_Type').val(),
};
$.post(
{
url: "/Session/Add",
data: data,
callback: function(res, status)
{
if (res !== "OK")
alert("There was a problem processing the request. " + res);
else
location.reload(true);
}
});
}
</script>
My intent is simple. After the user enters new details for a session, they will click on the Add Session button. JQuery will make a POST request passing my data to my page controller.
Here is an abbreviated variation of my controller:
//Index that initially loads the data.
public ActionResult Index(int id = -1)
{
SessionModel sm = new SessionModel(id);
sm.CanEdit = true;
return View(sm);
}
//The containing model manages a HUGE form,
//across multiple BootStrap.js tabs. We save
//all other, non-sub-record related deets here.
public ActionResult Submit(SessionModel model)
{
model.Save();
return Redirect(Url.Content("~/"));
}
//Since there are multiple grids, I need to
//have a way to add new Session records.
//This is my first attempt at trying to
//create a POST method on my controller.
[HttpPost]
public string Add(AddSessionObject data)
{
//If I can ever get here, I'll save the data.
return "OK";
}
public class AddSessionObject
{
public string Name;
public string RecType;
}
What I'm experiencing is that when I make the $.post(...) call in JQuery, MVC always calls the Index(...) method, rather than the Add(...) method. What am I doing wrong?
try using this syntax:
var data = {
Name: $('MainSession_Name').val(),
RecType: $('MainSession_Type').val(),
};
$.post("/Session/Add", data, function(res, status) {
if (res !== "OK")
alert("There was a problem processing the request. " + res);
else
location.reload(true);
});
https://api.jquery.com/jquery.post/
I have a panel within a form that has 3 buttons save, edit and cancel.
When the user clicks on edit, the labels inside the panel change to textboxes wherein the user can edit the content. This part is done.
Now if the user has edited the content, but does not wish to save it, he clicks on cancel. When he does so, the edited text will be replace with the original content of the labels(data comes from the model).
I have followed the accepted answer given here
Controller:
[HttpPost]
public ActionResult Submit(int id, string actionType)
{
var model = new CustomerDetailsViewModel();
var custid = db.Customers.Find(id);
if(actionType == "Cancel")
{
model.Company = custid.Company;
model.Address = custid.Address;
model.FullName = custid.FirstName + " " + custid.LastName;
model.EMail = custid.EMail;
model.Phone = custid.Phone;
model.EntryDate = custid.EntryDate;
model.LastInterestShown = custid.LastInterestShown;
model.ID = custid.ID;
model.Status = custid.Status;
}
return PartialView(model);
}
View:
<input type="submit" value="Cancel" id="btncancel" name="actionType" class="btn btn-default" />
JS:
$("#btnCancel").click(function(e){
e.preventDefault();
$.ajax({
url: '/Client/Submit',
type: 'POST',
async: false
});
});
Can someone tell me where am I going wrong?
You are sending an ajax request with type: "GET" and to url: "/Client/Cancel"
If you don't have a seperate
public ActionResult Cancel() {...}
field in your controller, this ajax don't work.
What you need to do is;
var postdata = { "id": id-here, "actionType": actionType-here };
$("#btnCancel").click(function(e){
e.preventDefault();
$.ajax({
url: '/Client/Submit',
type: 'POST',
data: JSON.stringfy(postdata),
async: false
});
});
in your ClientController.
You don't need to use AJAX to reset the input fields to their original data. Assuming you've passed your model data to your view, you can use hidden inputs to store the original values and later on get them back when the user clicks on the cancel button (just use a regular button).
View:
<input type="hidden" name="tempCompany" id="tempCompany" value="#Model.Company">
<input type="hidden" name="tempAddress" id="tempAddress" value="#Model.Address">
<input type="hidden" name="tempFullName" id="tempFullName" value="#Model.FullName">
JS:
<script>
$("#btnCancel").click(function (e) {
$('#Company').val($('#tempCompany').val());
$('#Address').val($('#tempAddress').val());
$('#FullName').val($('#tempFullName').val());
});
</script>