Why is my dialog form data not being passed to my controller in my Ajax Post? - ajax

I have created a partial view which takes one parameter on a form "email address", and I would like that string passed to my controller called "InviteTeam" which is decorated as an "HttpPost".
so here is the partial view and the ajax command
<form id="inviteTeam">
<label class="sr-only" for="communityCity">Team Email Address</label>
<input class="form-control" type="text" name="teamEmailAddress" id="teamEmailAddress" placeholder="Team Email">
Invite
</form>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
var formdata = $("#inviteTeam").serialize();
alert(formdata);
$.ajax({
type: "POST",
url: "/habitats/InviteTeam",
data: formdata,
success: function () {
$("#inviteModal").modal("hide");
window.location.href = "/Habitats/EditCommunity/"
},
error: function (errorData) { alert(errorData); }
})
});
});
</script>
and here is my controller code: my input string is "email" is null
public ActionResult InviteTeam()
{
return PartialView();
}
[HttpPost]
public ActionResult InviteTeam(string email)
{
return RedirectToAction("EditCommunity", "Habitats");
}

Change name="teamEmailAddress" to name="email" Try the following:
<form id="inviteTeam">
<label class="sr-only" for="communityCity">Team Email Address</label>
<input class="form-control" type="text" name="email" id="teamEmailAddress" placeholder="Team Email">
Invite
</form>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
var formdata = $("#inviteTeam").serialize();
alert(formdata);
$.ajax({
type: "POST",
url: "/habitats/InviteTeam",
data: formdata,
success: function () {
$("#inviteModal").modal("hide");
window.location.href = "/Habitats/EditCommunity/"
},
error: function (errorData) { alert(errorData); }
})
});
});
</script>
Another solution is change the name of the parameter in your action method like:
[HttpPost]
public ActionResult InviteTeam(string teamEmailAddress)
{
return RedirectToAction("EditCommunity", "Habitats");
}
Also if you only want to redirect then you dont need any ajax call. You can simply redirect in javascript as:
window.location.href = "/Habitats/EditCommunity/"
But if you have to do some logic with your email address, then hit that controller action and return JSON as RedirectToAction will not work in AjaxCall like:
return Json("true");
In your success method of Ajax, you can check:
success: function (data) {
if (data == true){
$("#inviteModal").modal("hide");
window.location.href = "/Habitats/EditCommunity/";
}
}

Related

Ajax call is being accidently triggered

I'm creating a login page and at the bottom of the pop-up form, there is another button that takes you to the registration page. The issue appears to be that when navigating to the new page it all sits under the original sign-in form which uses an ajax call to check if the user exists so when they try to submit the registration form it then calls that ajax call from the sign-in form.
Sign-in form
<div id="myForm">
<form onsubmit="return false;" id="loginForm">
<h1>Login</h1>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="psw" placeholder="Enter Password" name="psw" required>
<div id="message" class="alert-danger"></div>
<br />
<button type="submit" id="submit" class="btn">Login</button>
<button type="button" class="btn cancel" onclick="closeForm();">Close</button>
</form>
<div class="d-inline">
<button class="btn-info">#Html.ActionLink("User Registration", "SignUp", "SignUp_SignIn")</button>
</div>
</div>
Then the ajax call is
$(document).ready(function () {
$("form").on('submit', function (event) {
var data = {
'email': $("#email").val(),
'psw': $("#psw").val()
};
$.ajax({
type: "POST",
url: 'SignUp_SignIn/CredentialCheck',
data: data,
success: function (result) {
if (result == true) {
$("#message").text("Login attempt was successful");
}
else {
$("#message").text("Email/Password didn't match any results");
}
},
error: function () {
alert("It failed");
}
});
return false;
});
});
After looking at the comments I realized that the reason that the login form was being called from the layout.cshtml so when the ajax call was being called it was grabbing all the form tags that existed on any page that was loaded up. After changing the ajax so it was calling a specific id for the login form instead of form it allowed for proper actions to take place.
An example of what I'm refusing to
$(document).ready(function () {
$("form").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});
The above will try to redirect you on the submit of any form that is loaded up, but if we go through and change the way it accesses the form like below then it will only work if the one specific form is submitted.
$(document).ready(function () {
$("#loginForm").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});

Model validation in Asp.Net Core before making an Ajax call from java script

Below is the sample code, i am calling this code on button click event. My question is, can i validate my viewmodel object before making ajax call? i can see model errors in java script, not sure how to check.
My viewmodel class properties has Data Annotation Validator Attributes. I don't want make ajax call if the viewmodel is not valid, want to check (ModelState.IsValid) in java script code, before making ajax call.
Any help, would be greatly appreciated.
$(function () {
$("#btnGet").click(function () {
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: viewModelobject,
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
}
ModelState.IsValid is server side code.Browser has no idea about what it is,so you could not validate ModelState in client side. You can use Jquery Validation at client side.
Here is a working demo:
1.Model:
public class UserModel
{
[Required(ErrorMessage = "The Name field is required.")]
[Display(Name = "Name")]
public string Name { get; set; }
}
2.View(Index.cshtml):
#model UserModel
<form id="frmContact">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" id="txtName" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-secondary" id="btnGet">Click</button>
</div>
</form>
#section Scripts
{
#*you could also add this partial view*#
#*#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}*#
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<script>
$(function () {
$('#btnGet').click(function () {
if ($("#frmContact").valid()) {
$('#frmContact').submit();
}
else {
return false;
}
});
$("#frmContact").on("submit", function (event) {
event.preventDefault();
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: JSON.stringify(viewModelobject),
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
})
</script>
}
3.Controller:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AjaxMethod([FromBody]UserModel user)
{
//do your stuff...
return Json(user);
}
}
Result:
Please use jQuery form validation as shown below inside the button click callback:
var form = $('form[name="' + formName + '"]');
form.validate();
if (form.valid()) {
//Do something if the form is valid
}
else {
//Show validation error messages if the form is in-valid
}

Ajax Call to PartialViewResult does not Replace Div with PartialView

I've done this dozens of times before and have been testing all morning, I must be missing something very obvious.
I have a form that submits data and if the data already exists, I just want to overwrite that form using a PartialView. I can debug the code and watch the POST get called and I even watch the PartialView reciev its model and data but the PartialView doesn't get rendered on the screen and my AJAX doesn't return anything to the console so I'm not sure how to Troubleshoot this.
My Controller
[HttpPost]
[Route("Send")]
public PartialViewResult Send([FromBody] InstantAlert InstantAlert)
{
string view = "~/views/shared/_InstantAlert_Exists.cshtml";
}
My View
<!-- Form -->
<div id="DivSubmitForm">
<partial name="~/views/home/_Partials/_SubmitForm.cshtml", model="Model" />
</div>
<!-- End Form -->
My Script
$(function () {
$(document).on("click", '#btnSubmit', function () {
if ($('form').valid()) {
Submit();
}
});
function Submit() {
//JSON data
var InstantAlert = {
url: $('#url').val(),
userId: $('#userId').val(),
institutionId: $('#institutionId').val()
}
var jsonToPost = JSON.stringify(InstantAlert);
$.ajax({
url: '/home/Send',
contentType: "application/json; charset=utf-8",
data: jsonToPost,
type: "POST",
success: function (result) {
console.log("Success");
//$('#DivSubmitForm').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
PartialView
<div class="form-group">
<div class="alert alert-danger alert-dismissible" role="alert">
<strong>This article has already been submitted</strong>
<hr class="message-inner-separator">
<p>
test
</p>
</div>
</div>
Argh, so I discovered a form tag on my page which means the controller was inevitably always reloading my initial controller....

AJAX Post to MVC Controller model every time empty

I am trying to send some data from a modal dialog to my controller with Ajax. But my modelfields are always null, but I enter my actionmethod in the controller.
This is a shortend version of my cshtml-file.
#model anmespace.MyModel
<form method="post" id="formID">
...
<div class="row">
<div class="col-md-5">#Resource.GetResource("MyModal", "Firstname")</div>
<div class="col-md-7"><input type="text" class="form-control" id="firstname" value="#Html.DisplayFor(model => model.FirstName)"></div>
</div>
...
<input type="submit" class="btn btn-primary" value="Submit" />
</form>
<script>
$("#formID").on("submit", function (event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("ActionName", "Controller")",
data: frmValues,
success: function (data) {
alert(data);
}
});
});
</script>
Sorry MVC/Ajax are really new for me.
If you want to bind the form data to model then, the names of HTML elements should match with Model properties.
Note: name attribute value of html input field should match to the property of a model.
When you use form and submit button then it will try to reload the page by posting data to the server. You need to prevent this action. You can do this by returning false on onSubmit event in the Form element.
When you use jquery, do not forget to keep the ajax call/events inside the $(document).ready(function(){}) function.
I have written a simple code which takes First Name as input and makes an ajax call on clicking on submit button.
Html & Jquery Code:
<script>
$(document).ready(function() {
$("#formID").on("submit", function(event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("PostData", "Home")",
data: frmValues,
success: function(data) {
alert(data.FirstName);
}
});
});
});
</script>
<div>
<form method="post" id="formID" onsubmit="return false;">
<input id="FirstName" name="FirstName"/>
<input type="submit" value="submit" />
</form>
</div>
My Model :
public class Person
{
public string FirstName { get; set; }
}
Action Method:
public ActionResult PostData(Person person)
{
return Json(new { Success = true, FirstName = person.FirstName });
}
Output:

ajax alert is not working using codeigniter

I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.

Resources