How to serialize forms and post using jQuery Ajax - javascript

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");
}

Related

How to make a post request without form and without getting error 400

I'm sending a post request without a form in asp.net. I'm getting error 400.
AJAX
function deteleCategorieBtn(id) {
if (confirm("Are you sure you want to delete ?")) {
$.ajax({
type: "POST",
url: 'categories/delete/' + id,
success: function () {
var dataTable = $('#kt_datatable').DataTable();
dataTable.ajax.reload(null, false);
},
error: function (request, error) {
console.log(request, error);
}
})
}
CONTROLLER
// POST: Categories/Delete/5
[Route("delete/{id?}")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id)
{
var category = await _context.Categories
.FirstOrDefaultAsync(m => m.Id == id);
if(category != null){
_context.Categories.Remove(category);
await _context.SaveChangesAsync();
}
else
{
return Json(new { error = true, messages = "Categorie doesn't exist" }, new Newtonsoft.Json.JsonSerializerSettings());
}
return Json(new { success = true, messages = "Registered well" }, new Newtonsoft.Json.JsonSerializerSettings());
}
}
On the console, the url is correct
I tried changing the type from POST to DELETE in ajax part, and HttpPost to HttpDelete - Didn't work
I used the very same controller code successfully with a form that looks like that :
<form asp-action="Delete" asp-route-id="#item.Id" onclick="return confirm('Are you sure you want to delete ? ?');">
<button type="submit" value="Delete" class="btn btn-sm btn-clean btn-icon"></button>
</form>
EDIT :
Found this error message :
System.InvalidOperationException: The provider for the source IQueryable doesn't implement IDbAsyncQueryProvider. Only providers that implement IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations.
You need to add an Antiforgery token while doing the ajax post.
Add an antiforgerytoken like below in your page
#Html.AntiForgeryToken()
This will be added in a hidden input field
While doing the ajax post, send the token like below
$.ajax({
type: "POST",
url: 'categories/delete/' + id,
beforeSend: function (xhr) {
xhr.setRequestHeader('XSRF-TOKEN',
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () {
var dataTable = $('#kt_datatable').DataTable();
dataTable.ajax.reload(null, false);
},
error: function (request, error) {
console.log(request, error);
}
});

MVC Asp.Net Controller returns raw JSON to new window

like my title says, I have a problem where my MVC Controller alwas returns the JsonResult in an new window and don't return it back to the ajax success event.
I also tried to GET the data from the Controller via Ajax or change the contenttype to something like "application/json", but I always get a new window with my raw Json data. In my opinion, the problem has to be something with the controller or the javascript is unable to catch the json data.
It's also not a browser specific problem, I have this in every common browser.
Is there anything I miss or is it just weird?
Controller:
public JsonResult Update(ChangeUserInformationViewModel model)
{
var user = UserManager.FindById(User.Identity.GetUserId());
user = model.User;
UserManager.Update(user);
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
Ajax:
$(document).ready(function () {
$('#save-user-alert').click(function () {
$("#ChangeUserInformation").submit();
});
$('#save-user-alert').on("submit", function (event) {
event.preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
contentType: "json",
success: function (resp) {
if (resp.success) {
swal("Goo Job!", "Yippii", "success");
};
},
error: function (resp) {
swal("Failes", "Upps.. something went wrong", "danger");
}
});
});
});
Html:
#using (Html.BeginForm("Update", "User", FormMethod.Post, new { id = "ChangeUserInformation" }))
{
<div class="form-group">
<label for="Username">Username</label>
#Html.TextBoxFor(x => x.User.UserName, new { #class = "form-control", value = Model.User.UserName, id = "Username" })
</div>
<div class="form-group">
<label for="FirstName">First Name</label>
#Html.TextBoxFor(x => x.User.Firstname, new { #class = "form-control", value = Model.User.Firstname, id = "FirstName" })
</div>
<div class="form-group">
<label for="LastName">Last Name</label>
#Html.TextBoxFor(x => x.User.LastName, new { #class = "form-control", value = Model.User.LastName, id = "LastName" })
</div>
}
<button class="btn btn-danger waves-effect waves-light btn-sm" id="save-user-alert">Click me</button>
Pleas help me!
Sebastian
You are gettting the JSON response in the browser because your code is not doing an ajax post, instead it is doing a normal form submit.
Why is it not doing the ajax submit ?
Because you do not have any code which says to do so. You are binding the submit event to the wrong element. You should bind it to the form, not the button.
$('#ChangeUserInformation').on("submit", function (event) {
event.preventDefault();
// do your ajax call
});
Now when user clicks the other button, it will call the submit event on the form and the above submit event handler will be invoked and it will make an an ajax call..
I think the problem is that you are using the form Submit for your ajax call.
Change your javascript code into this to remove the submit behavior:
$('#save-user-alert').click(function () {
event.preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
contentType: "json",
success: function (resp) {
if (resp.success) {
swal("Goo Job!", "Yippii", "success");
};
},
error: function (resp) {
swal("Failes", "Upps.. something went wrong", "danger");
}
});
});

Laravel & Ajax - Insert data into table without refreshing

First of all, I have to say that I'm beginner with using Ajax... So help me guys.
I want to insert the data into db without refreshing the page. So far, I have following code...
In blade I have a form with an id:
{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}
<img align="right" src="{{ asset('/img/icon_add_fav.png')}}">
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idArticle" id="idArticle" value="{{$docinfo['attrs']['sid']}}">
<input type="submit" id="test" value="Ok">
{!! Form::close() !!}
And in controller I have:
public function addFavorites()
{
$idUser = Input::get('idUser');
$idArticle = Input::get('idArticle');
$favorite = new Favorite;
$favorite->idUser = $idUser;
$favorite->idArticle = $idArticle;
$favorite->save();
if ($favorite) {
return response()->json([
'status' => 'success',
'idUser' => $idUser,
'idArticle' => $idArticle]);
} else {
return response()->json([
'status' => 'error']);
}
}
I'm trying with ajax to insert into database:
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"{{ url('addFavorites') }}",
dataType="json",
data:$('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
}
error: function(data){
alert("Error")
}
});
});
Also in my web.php I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {"status":"success","idUser":"15","idArticle":"343970"}... It actually inserts into the db, but I want the page not to reload. Just to display alert box.
As #sujivasagam says it's performing a regular post action. Try to replace your javascript with this. I also recognized some syntax error but it is corrected here.
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
You could just replace <input type="submit"> with <button>instead and you'll probably won't be needing event.preventDefault() which prevents the form from posting.
EDIT
Here's an example of getting and posting just with javascript as asked for in comments.
(function() {
// Loads items into html
var pushItemsToList = function(items) {
var items = [];
$.each(items.data, function(i, item) {
items.push('<li>'+item.title+'</li>');
});
$('#the-ul-id').append(items.join(''));
}
// Fetching items
var fetchItems = function() {
$.ajax({
type: "GET",
url: "/items",
success: function(items) {
pushItemsToList(items);
},
error: function(error) {
alert("Error fetching items: " + error);
}
});
}
// Click event, adding item to favorites
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
// Load items (or whatever) when DOM's loaded
$(document).ready(function() {
fetchItems();
});
})();
You are using button type "Submit" which usually submit the form. So make that as button and on click of that call the ajax function
Change your button type to type="button" and add onclick action onclick="yourfunction()". and just put ajax inside your funciton.
Replace input type with button and make onClick listener. Make sure you use this input id in onclick listener:
So:
$('#test').on('click', function(event){
event.preventDefault()
... further code
I would also change the id to something clearer.

How to know if Ajax Post was a success?

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?

How to not able to hit the controller in my asp.net mvc application using this code

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
GOTO = function () {
alert("yes");
$.ajax({
cache: false,
type: "POST",
url: "/Home/Index/",
data: datastring,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
}
</script>
<input type="button" value="submit" onclick="JavaScript:GOTO()" />
</asp:Content>
My Controller ActionResult is something like this
JsonResult
[HttpPost]
public System.Web.Mvc.JsonResult Index(FormCollection collection)
{
//return Content("<xml>this is just test</xml>", "text/xml");
//return Content("this is just test", "text/plain");
if (Request.AcceptTypes.Contains("application/json"))
{
return Json(new { id = 1, value = "new" });
}
else if (Request.AcceptTypes.Contains("application/xml") ||
Request.AcceptTypes.Contains("text/xml"))
{
}
if (Request.AcceptTypes.Contains("text/html"))
{
//return View();
}
return Json(new { foo = "bar", baz = "Blech" });
}
I am not able to return the JsonResult here allways I am getting popupmessage saying u have choosen to open this dialogue? is there something I am doing wrong?
thanks
Try this instead -- and make sure jQuery is loaded first. Note the changes to apply the handler via jQuery instead of inline, serializing the data, generating the URL in code dynamically rather than hard-coded, and returning false from the click handler to prevent normal form submission.
<script type="text/javascript">
$(function() {
$('input[type=button]').click( function() {
var data = $('form').serialize(); // or however you get your data
$.ajax({
cache: false,
type: "POST",
url: "<%= Html.Action( "index", "home" ) %>",
data: data,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
return false; // don't do the normal submit
});
});
</script>
<input type="button" value="submit" />
you need to put the button in a form tag and call the GOTO function in onsubmit event
It looks like your data: datastring might be the problem. Check to make sure that the name of your data parameter is the same as your method parameter.
I would try to approach it more like this ...
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$(form).submit(function() {
alert("yes");
$.post({
cache: false,
type: "POST",
url: "/Home/Index/",
data: datastring,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
});
}
</script>
<form>
// your form fields
<input type="button" value="submit" />
</form>
</asp:Content>
And then your controller should look more like this.
Notice how we changed the parameter to a string that matches your jQuery data field.
[HttpPost]
public System.Web.Mvc.JsonResult Index(string datastring)
{
// you can deserialize your Json here.
//return Content("<xml>this is just test</xml>", "text/xml");
//return Content("this is just test", "text/plain");
if (Request.AcceptTypes.Contains("application/json"))
{
return Json(new { id = 1, value = "new" });
}
else if (Request.AcceptTypes.Contains("application/xml") ||
Request.AcceptTypes.Contains("text/xml"))
{
}
if (Request.AcceptTypes.Contains("text/html"))
{
//return View();
}
return Json(new { foo = "bar", baz = "Blech" });
}

Categories