ajax with return Json return blank page - ajax

**Hi I have Login and Register Page in one view.Login controller does not have view. i want to show error message when user enter wrong email and password. but it return blank page with {"Fail"} with url Account/Login
$(document).ready(function () {
$("#alertmessage").hide()
$("#logbut").on("click",function () {
//collect the user data
var data = {};
data.Email = $("#Email").val();
data.Password = $("#Password").val();
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
contentType: "application/json; charset=utf-8",
url: "/Account/Login",
type: "POST",
dataType: "json",
data: {
model: data,
__RequestVerificationToken: token,
},
success: function () {
$("#alertmessage").show()
},
})
})
})
<div class="login-container">
<div class="row">
<div class=" col-md-12 col-sm-12 col-12 login-form-1">
<h2>Login </h2>
<p>Log into your account</p>
#using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
<div id="alertmessage">
<div class=" alert alert-danger">
<span>
Email or Password is incorrect
</span>
</div>
</div>
#Html.AntiForgeryToken()
<div class="form-group col-md-12 col-sm-12 col-12">
<input id="Email" type="text" class="form-control" placeholder="Your Email *" value="" name="Emaillog" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12 ">
<input id="Password" type="password" class="form-control" placeholder="Your Password *" value="" name="Passwordlog" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12">
<input type="submit" class="btnSubmit" value="Login now" id="logbut" />
</div>
<div class="form-group col-md-6 col-sm-6 col-6">
Forget Password?
</div>
}
</div>
</div>
</div>
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(string Emaillog,string Passwordlog)
{
string result = "Fail";
User appUser = _context.Users.FirstOrDefault(u => u.Email == Emaillog);
if (appUser != null)
{
if (appUser.Password ==Passwordlog)
{
Session["ActiveUser"] = appUser;
return RedirectToAction("MainAccount");
}
}
return Json(result, JsonRequestBehavior.AllowGet); }
I tried change to JsonResult action but still the same. I don't know where gone wrong. **

Your ajax call is not being called because your submit button is submitting the form and doing a redirect.
Add a event.preventDefault() button click event so that it won't do a normal synchronous POST.
// add e parameter, this is for the event
$("#logbut").on("click",function (e) {
// this is to avoid the form being submitted, and proceed with your script call
e.preventDefault();
// ...
})

Related

Asp.Net Core: Send object and parameter to mvc controller using ajax?

I want to send the form data $('#SearchProduct').serialize() with a parameter to the controller...
But whatever I do, only one parameter is sent!!!
Jquery :
const MainProducts = new Products();
MainProducts.LoadProducts(null, 1);
Search_Btn.click(function () {
const Form_Data = SearchProduct.serialize();
MainProducts.LoadProducts(Form_Data, 1);
});
Ajax :
LoadProducts(ObjSearch, page) {
console.log(page);
$.ajax({
url: GetUrlAdmin.Product.AllShowProducts,
type: "Get",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { ObjSearch, page },
dataType: 'json',
contentType: 'application/json;charset=utf-8',
success: function (result) {
})
Controller :
public async Task<JsonResult> GetAllShowProducts(ProductSearchViewModel model, int page)
{
var Products = await _admin.GetAllShowProducts(model, page);
return Json(new { data = Products });
}
I also tested the following code, but it was not sent again?
JSON.stringify(ObjSearch, page)
I want to send the form data $('#SearchProduct').serialize() with a
parameter to the controller... But whatever I do, only one parameter
is sent!!!
The issue might be relating to the form elements, when binding the form element and property, we need to bind it via the page model. You can refer to the following sample code (using VS 2022 and Asp.net 6 MVC) and then compare with your code.
Model:
public class Product
{
public int Id { get; set; }
public string Title { get; set; }
public string UrlImage { get; set; }
public string Detail { get; set; }
public decimal Price { get; set; }
}
Home controller:
public IActionResult ProductCreate()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ProductCreate(Product product)
{
return View();
}
ProductCreate.cshtml:
#model MVCWebApp.Models.Product
#{
ViewData["Title"] = "ProductCreate";
}
<h1>ProductCreate</h1>
<h4>Product</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form id="formprodcreate" asp-action="ProductCreate">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Id" class="control-label"></label>
<input asp-for="Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="UrlImage" class="control-label"></label>
<input asp-for="UrlImage" class="form-control" />
<span asp-validation-for="UrlImage" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Detail" class="control-label"></label>
<input asp-for="Detail" class="form-control" />
<span asp-validation-for="Detail" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
<input type="button" class="btn btn-primary" id="btnFormSubmit" value="Form Ajax Submit"/>
<input type="button" class="btn btn-primary" id="btnSubmit" value="Ajax Submit"/>
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
Js code: [Note] In the Ajax function, there is no need to set the datatype and contenttype.
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(function(){
//use the serialize method to serialize the form.
$("#btnFormSubmit").click(function(){
$.ajax({
url: "/Home/ProductCreate",
type: "Post",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
data: $('#formprodcreate').serialize(),
success: function (result) {
}
});
});
//create a JS object and get the entered value, then transfer the object to the controller.
$("#btnSubmit").click(function(){
var product = {};
product.Id = $("input[name='Id']").val();
product.Title = $("input[name='Title']").val();
product.UrlImage = $("input[name='UrlImage']").val();
product.Detail = $("input[name='Detail']").val();
product.Price = $("input[name='Price']").val();
$.ajax({
url: "/Home/ProductCreate",
type: "Post",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
data: product,
success: function (result) {
}
});
});
});
</script>
}
The output is like this:

Async Method returns 404

I got the following problem.
in my Controller, this method is supposed to return a JSON with the pets from the database. but is being called, the server returns a 404.
public async Task<JsonResult> GetPetsAsync(int ownerId )
{
var pets = await _dataContext.Pets
.Where(p => p.Owner.Id == ownerId)
.OrderBy(p => p.Name)
.ToListAsync();
return Json(pets);
}
=====================================================
This is the form that provides the OwnerId for the method to find the pets for that particular owner.
<div class="row m-auto align-content-center">
<div class="col-md-4">
<form asp-action="Assign" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="OwnerId" class="form-label fw-bold"></label>
<select asp-for="OwnerId" asp-items="Model.Owners" class="form-control"></select>
<span asp-validation-for="OwnerId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PetId" class="form-label fw-bold"></label>
<select asp-for="PetId" asp-items="Model.Pets" class="form-control"></select>
<span asp-validation-for="PetId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Remarks" class="form-label fw-bold "></label>
<textarea asp-for="Remarks" class="form-control"></textarea>
<span asp-validation-for="Remarks" class="text-danger"></span>
</div>
<div class="form-group mt-3">
<button value="Assign" type="submit" class="btn btn-primary btn-sm"><i class="bi bi-calendar-plus-fill"></i></button>
<a asp-action="Index" class="btn btn-success btn-sm"><i class="bi bi-arrow-return-left"></i> Go Back</a>
<span asp-validation-for="Remarks" class="text-danger"></span>
</div>
</form>
</div>
</div>
In my View -- the AJAX request to GetPetsAsync
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function () {
$("#OwnerId").change(function () {
$("#PetId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetPetsAsync", "Agenda")',
//Take the OwnerId and send it to the JsonResult Method to retrieve the pets
data: { ownerId: $("#OwnerId").val() },
dataType: 'Json',
success: function (pets) {
$("#PetId").append('<option value="0">(Select a pet...)</option>');
$.each(pets, function (i, pet) {
$("#PetId").append('<option value="'
+ pet.id + '">'
+ pet.name + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve pets. ' + ex.statusText);
}
});
return false;
})
});
</script>
It looks like this feature change is affecting you.
Async suffix for controller action names will be trimmed by default #14716
You can just drop the "Async" suffix from your view-side code. Which is why renaming your method "fixed" your problem.
You have control over this behavior in your app startup with SuppressAsyncSuffixInActionName
builder.Services.AddMvc(options =>
{
options.SuppressAsyncSuffixInActionNames = false;
});
Make sure the "httppost" attribute is used. If you continue to get an error, check the data part in the ajax section.
I found the solution. Incredibly just by changing the Method Name to GetPetAsyncronous the problem was solve. I don’t know why the previous method wouldn’t work. But It worked.

How to show Validation Summary in a modal form with ajax post method?

I'm beginner in ASP.NET Core MVC. I have a problem in my website code.
My model is User that has some fields, and I wrote a view model based on these fields.
I've written the following code:
My view model: RegisterViewModel:
public class RegisterViewModel
{
[Display(Name = "Username")]
[Required(ErrorMessage = "Enter {0} value please.")]
[MaxLength(20, ErrorMessage = "{0} Shouldn't have more than {1} Characters")]
public string Username { get; set; }
[Display(Name = "Password")]
[Required(ErrorMessage = "Enter {0} value please.")]
[MaxLength(50, ErrorMessage = "{0} Shouldn't have more than {1} Characters")]
public string Password { get; set; }
}
My controller: AccountController:
public class AccountController : Controller
{
private IUser _iuser;
public AccountController(IUser iuser)
{
_iuser = iuser;
}
public IActionResult Register()
{
return View();
}
[HttpPost]
public IActionResult Register(RegisterViewModel register)
{
if (ModelState.IsValid)
{
if (_iuser.isUsernameExist(register.Username))
{
ModelState.AddModelError("UserName", "This User Exists!");
return PartialView(register);
}
else
{
User user = new User()
{
Username = register.Username,
Password = HashGenerators.EncodingPassWithMD5(register.Password),
RoleId = 2,
};
_iuser.AddUser(user);
string TabName = "UserTab";
return Json(new { redirectToUrl = Url.Action("Index", "Profile", new {TabName}) });
}
}
else
{
return PartialView(register);
}
}
}
Register action has a view that has displayed as a modal.
View Register.cshtml:
<div class="row">
<div class="col-md-8 col-md-offset-2">
<hr />
<form asp-action="Register">
<div asp-validation-summary="ModelOnly" class="text-danger text-right"></div>
<div class="form-group">
<input asp-for="Username" class="form-control" , placeholder="username" id="txtUsername"/>
<span asp-validation-for="Username" class="text-danger" id="ValidationSummery"></span>
</div>
<div class="form-group">
<input asp-for="Password" class="form-control" , placeholder="password" id="txtPassword"/>
<span asp-validation-for="Password" class="text-danger text-right" id="ValidationSummery"></span>
</div>
<div class="form-group">
<input type="button" value="Create" onclick='AddUser()' class="btn-red pull-left" />
<button href="#" type="button" onclick='ClearForm()' class="btn-red pull-right"> Clear Form </button>
</div>
</form>
</div>
</div>
Modal code (at the end of above code):
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div id="bodyModal" class="modal-body">
</div>
</div>
</div>
</div>
and at the end of view, I have these Ajax scripts:
<script>
function ClearForm() {
$.ajax({
url: "/Account/Register/",
type: "Get",
data: {}
}).done(function (result) {
$('#myModal').modal('show');
$('#bodyModal').html(result);
});
$('#myModal').modal('dispose'); }
</script>
<script>
function AddUser() {
$.ajax({
url: "/Account/Register/",
type: "Post",
data: {
Username: $("#txtUsername").val(),
Password: $("#txtPassword").val(),
},
success: function (response) {
window.location.href = response.redirectToUrl;
}
}).done(function (result) {
$('#myModal').modal('show');
$('#bodyModal').html(result);
});}
</script>
When program is running, the ClearForm button works well, the Create button works well when modelstate is valid. But when modelstate is not valid, it goes to an error page (Hello world!), I see validation errors for 1 second but browser opens an wrong page and doesn't stay on modal for showing validation error.
NOTE: When I delete: ( window.location.href = response.redirectToUrl;) from ajax AddUser function at success part, modal stays open and validation errors displays. But if modelstate is valid, modal stays open but it was empty and destination page(Index/Profile#UserTab) doesn't display.
Please help me, how can I change above code to solve this problem?
I think you can have a new partial view to show the validation message.
Add a hidden input field to the partial view:
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
Then in ajax success function determine whether to show the modal or redirect by judging the value of IsValid
A simple demo based on your codes.
Register.cshtml:
#model RegisterViewModel
#{
ViewData["Title"] = "Register";
}
<h1>Register</h1>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<hr />
<form asp-action="Register">
<div asp-validation-summary="ModelOnly" class="text-danger text-right"></div>
<div class="form-group">
<input asp-for="Username" class="form-control" , placeholder="username" id="txtUsername" />
<span asp-validation-for="Username" class="text-danger" id="ValidationSummery"></span>
</div>
<div class="form-group">
<input asp-for="Password" class="form-control" , placeholder="password" id="txtPassword" />
<span asp-validation-for="Password" class="text-danger text-right" id="ValidationSummery"></span>
</div>
<div class="form-group">
<input type="button" value="Create" onclick='AddUser()' class="btn-red pull-left" />
<button href="#" type="button" onclick='ClearForm()' class="btn-red pull-right"> Clear Form </button>
</div>
</form>
</div>
</div>
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div id="bodyModal" class="modal-body">
</div>
</div>
</div>
</div>
#section scripts{
<script>
function AddUser() {
$.ajax({
url: "/Account/Register/",
type: "Post",
data: {
Username: $("#txtUsername").val(),
Password: $("#txtPassword").val(),
},
success: function (response) {
$('#bodyModal').html(response);
var isValid = $('body').find('[name="IsValid"]').val() == 'True';
if (!isValid) {
$('#myModal').modal('show');
} else {
window.location.href = "#Url.Action("Index", "Profile")";
}
}
});
}
</script>
}
_Register.cshtml(Partial View):
#model RegisterViewModel
<form asp-action="Register">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<div asp-validation-summary="ModelOnly" class="text-danger text-right"></div>
<div class="form-group">
<input asp-for="Username" class="form-control" , placeholder="username" id="txtUsername" readonly />
<span asp-validation-for="Username" class="text-danger" id="ValidationSummery"></span>
</div>
<div class="form-group">
<input asp-for="Password" class="form-control" , placeholder="password" id="txtPassword" readonly />
<span asp-validation-for="Password" class="text-danger text-right" id="ValidationSummery"></span>
</div>
</form>
Controller:
public class AccountController : Controller
{
public IActionResult Register()
{
return View();
}
[HttpPost]
public IActionResult Register(RegisterViewModel register)
{
if (ModelState.IsValid)
{
// do some stuff
}
return PartialView("_Register",register);
}
}
Result:
With inspiring help of https://stackoverflow.com/users/11965297/mj1313, I Changed my code like following and my problem is solved entirely...
In controller, I send a parameter(Valid) by ViewBag to my view, to specify ModelState validity status.
[HttpPost]
public IActionResult Register(RegisterViewModel register)
{
if (ModelState.IsValid)
{
if (_iuser.isUsernameExist(register.Username))
{
ViewBag.Valid= "1"; // It's part of my change
ModelState.AddModelError("UserName", "This User Exists!");
return PartialView(register);
}
else
{
User user = new User()
{
Username = register.Username,
Password = HashGenerators.EncodingPassWithMD5(register.Password),
RoleId = 2,
};
_iuser.AddUser(user);
ViewBag.Valid= "0"; // It's part of my change
string TabName = "UserTab";
return Json(new { redirectToUrl = Url.Action("Index", "Profile", new {TabName}) });
}
}
else
{
ViewBag.Valid= "1"; // It's part of my change
return PartialView(register);
}
}
And in My view, I use a hidden input for save ViewBag.
<form asp-action="Register">
<input name="IsValid" type="hidden" value="#ViewBag.Valid" /> #*It's part of my change*#
<div asp-validation-summary="ModelOnly" class="text-danger text-right"></div>
<div class="form-group">
<input asp-for="Username" class="form-control" , placeholder="username"
</div>
.....
</form>
At the end, I change Ajax function, success part:
function AddUser() {
$.ajax({
url: "/Account/Register/",
type: "Post",
data: {
Username: $("#txtUsername").val(),
Password: $("#txtPassword").val(),
},
success: function (response) {
$('#bodyModal').html(response);
var isValid = $('body').find('[name="IsValid"]').val();
if (isValid) {
$('#myModal').modal('show');
} else {
window.location.href = response.redirectToUrl;
}
}
}).done(function (result) {
$('#myModal').modal('show');
$('#bodyModal').html(result);
});}

Input values are null in controller(ASP.Net MVC) using ajax

In my Login Page I want to show error message when user enter wrong email and password without refreshing page. I am trying to send data from view to controller using ajax. But in the controller, user.Email and user.Password are null when I debug, but the Ajax call works. I want to know what is wrong there?
<div class="login-container">
<div class="row">
<div class=" col-md-12 col-sm-12 col-12 login-form-1">
<h2>Login</h2>
<p>Log into your account</p>
#using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
<div id="alertmessage">
<div class=" alert alert-danger">
<span>
Email or Password is incorrect
</span>
</div>
</div>
#Html.AntiForgeryToken()
<div class="form-group col-md-12 col-sm-12 col-12">
<input id="Email" type="text" class="form-control" placeholder="Your Email *" value="" name="Emaillog" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12 ">
<input id="Password" type="password" class="form-control" placeholder="Your Password *" value="" name="Passwordlog" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12">
<input type="submit" class="btnSubmit" value="Login now" id="logbut" />
</div>
<div class="form-group col-md-6 col-sm-6 col-6">
Forget Password?
</div>
}
</div>
</div>
</div>
$(document).ready(function () {
$("#alertmessage").hide()
$("#logbut").click(function (e) {
e.preventDefault();
// collect the user data
var data = {};
data.Email = $("#Email").val();
data.Password = $("#Password").val();
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/Account/Login",
type: "POST",
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: {
model: data,
__RequestVerificationToken: token,
returnUrl: "Account/Login" // you can modify the returnUrl value here
},
success: function (result) {
if (result == "Fail") {
$("#alertmessage").show()
}
else {
window.location.href = "/Account/MainAccount";
}
},
})
})
})
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User user)
{
string result = "Fail";
User appUser = _context.Users.FirstOrDefault(u => u.Email == user.Email);
if (appUser != null)
{
if (appUser.Password ==user.Password)
{
Session["ActiveUser"] = appUser;
return RedirectToAction("MainAccount");
}
}
return Json(result, JsonRequestBehavior.AllowGet);
}
How can I solve this problem?
Instead of using User Model in MVC action, use parameters in
Login(string email, string password)
And in Ajax pass
data:
{
email : email,
password : password,
__RequestVerificationToken: token
}
Can you please try this.
Note: you model class property same as inside form control name
Like example
UserName
Password
In you example
you are sending a request using ajax but your button type is submit when you click on button two requests come in server one is ajax and the second one is form.
Please see this example.
<div class="login-container">
<div class="row">
<div class=" col-md-12 col-sm-12 col-12 login-form-1">
<h2>Login </h2>
<p>Log into your account</p>
#using (Html.BeginForm("Login", "Account", FormMethod.Post,new {id="LoginFrom" }))
{
<div id="alertmessage">
<div class=" alert alert-danger">
<span>
Email or Password is incorrect
</span>
</div>
</div>
#Html.AntiForgeryToken()
<div class="form-group col-md-12 col-sm-12 col-12">
<input id="Email" type="text" class="form-control" placeholder="Your Email *" value="" name="Email" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12 ">
<input id="Password" type="password" class="form-control" placeholder="Your Password *" value="" name="Password" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12">
<input type="button" class="btnSubmit" value="Login now" id="logbut" />
</div>
<div class="form-group col-md-6 col-sm-6 col-6">
Forget Password?
</div>
}
</div>
</div>
</div>
Jquery Code
$(document).ready(function () {
$("#alertmessage").hide()
$("#logbut").click(function (e) {
$.ajax({
url: '#Url.Action("Login","Account")',
type: "POST",
data: $("#LoginFrom").serialize(),
success: function (result) {
if (result == "Fail") {
$("#alertmessage").show()
}
else {
window.location.href = "/Account/MainAccount";
}
},
})
})
})
For more detail -> check this link https://www.w3schools.com/jquery/ajax_serialize.asp

Laravel : Insert data into database using Bootstrap Modal

I want to insert some data into database using Bootstrap Modal. But the problem is Save button doesn't work properly on Bootstrap Modal as I couldn't insert the data into database through form. If anyone could help me to find it please!?
Here is the form part in blade:
<div id="myAlert" class="modal hide">
<div class="modal-header">
<button data-dismiss="modal" class="close" type="button">×</button>
<h3>Create User</h3>
</div>
<div class="modal-body">
<div class="row-fluid">
<div class="span12">
<div class="widget-box">
<div class="widget-content nopadding">
<form action="#" method="get" id="userForm" class="form-horizontal">
<div class="control-group">
<label class="control-label">Name :</label>
<div class="controls">
<input class="span11" placeholder="Name" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label">Email :</label>
<div class="controls">
<input class="span11" placeholder="Email" type="email">
</div>
</div>
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<input class="span11" placeholder="Enter Password" type="password">
</div>
</div>
<div class="control-group">
<label class="control-label">Confirm Password</label>
<div class="controls">
<input class="span11" placeholder="Confirm Password" type="password">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" href="#">Confirm</a> <a
data-dismiss="modal" class="btn" href="#">Cancel</a>
</div>
</div>
Here is the Ajax Part :
$('#userForm').on('success.form.fv', function(e) {
e.preventDefault();
$.ajax({
method: 'POST',
action:"{{ url('/register') }}",
data: $form.serialize()
});
});
You need the submit button. Try to put this code inside your form.
<button type="submit" class="btn btn-primary">Register</button>
Problem with your current Confirm button is: 1) he don't have type=submit; 2) he is outside the form.
first of all add type="submit" to your button
secondly check your network tab in the dev tools in your browser and check the request does it go to /register or not ?
if the request is hitting /register what's the parameters ?
Change form method get to post
I answer here for ajax call
Laravel ajax internal servor 500 (internal server-error)
Your input type elements are missing name attribute
<input class="span11" placeholder="Name" name="name" type="text">
<input class="span11" placeholder="Email" name="email" type="email">
<input class="span11" placeholder="Enter Password" name="password" type="password">
<input class="span11" placeholder="Confirm Password" name ="confirm_password" type="password">
You then retrieve the content using Request or Input by passing the value of the name attribute
At first change your form method from get to post. Then add save button with id btnSave.
Ajax :
$("#btnSave").click(function(e){
e.preventDefault()
var $form = $("#userForm");
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function (data, status) {
if(data.error){
return;
}
alert(data.success); // THis is success message
$('#myModal').modal('hide'); // Your modal Id
},
error: function (result) {
}
});
});
In controller :
public function store(Request $request)
{ try {
$inputs = $request->all();
ModelName::create($inputs);
$data = ['success' =>'Data saved successfully'];
} catch (\Exception $e) {
$data = ['error' =>$e->getMessage()];
}
return Response::json($data);
}
Form part in blade:
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" id="btnAdd">Confirm</a></div>
Ajax Part
$('#btnAdd').click(function () {
$.ajax({
url: '{{url('/register')}}',
type: 'POST',
data: $('#userForm').serialize(),
success: function (object) {
},
error: function (result) {
}
});
});

Resources