Controller
[HttpPost]
public IActionResult Index(string mainFin, string actNumber, int actTypeId)
{
int userId = Int16.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
Act act = new Act()
{
ActTypeId = actTypeId,
CreateDate = DateTime.Now,
ApproveDate = null,
UserId = userId,
StatusId = 1,
};
_unitOfWork.ActRepository.Add(act);
_notyf.Success("Arayış əlavə edilid !");
_unitOfWork.Complete();
return RedirectToAction("Marriage");
}
AJAX
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
},
error: function () {
console.log("------");
}
});
e.preventDefault();
$("#questForm1").submit();
});
});
Problem : When I click submit button data inserts twice to database (AJAX makes 2 request at same time )
If you want to submit the form via AJAX then you need to remove the last line of the click event handler.
$("#questForm1").submit();
This line is submitting the form and essentially negating the e.preventDefault() above.
You are submitting your data twice: at first using ajax and after that using using the form submit.
You have to remove one of them, I would guess the form submit.
Also, since ajax is called async, if you want to do something after ajax has been called and returned successfully, you have to put the code in success section.
So the code should look like:
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
e.preventDefault();
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
// do your thing here, once the ajax requst has returned successfully
},
error: function () {
console.log("------");
}
});
// NOTICE: form submit removed
});
});
Related
I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.
Here's my AJAX call
function GetRecord() {
var elemEmployee = 55;
var startDT = $('#searchFilterStartDate').val();
var endDT = $('#searchFilterEndDate').val();
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data);
}
});
}
here's my controller:
[HttpGet]
public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
return entity.GetDTR(data);
}
As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.
You need to return JSON from your Controller method. You can change your method to:
[HttpGet]
public JsonResult GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
var getDTR= entity.GetDTR(data);
return Json(new {dtrData= getDTR});
}
And in your Ajax call:
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data.dtrData);
},
error: function(error) {
console.log(error)
}
});
After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:
$(document).ready(function () {
//On Clink "Search Button"
$("#searchbtn").click(
function () { GetRecord(); });
});
The data seems to be coming as expected.
I need to get an id from the URL , comment value from textbox, save it to database and show on page with ajax.
Im not sure how should look correct syntax in my controller and ajax function.
Controller
[HttpPost]
public JsonResult AddComment(int id, string comment)
{
if (ModelState.IsValid)
{
return Json(true); // what should be here
}
return Json(true);
}
Ajax
$('#submit').click(function () {
$.ajax({
url: '/Form/AddComment',
method: 'POST',
data: {
id: 4, //how to get id from url?
comment: 'test' //how to get textbox value?
},
success: function (data) {
console.log(data)
},
error: function (a, b, c) {
console.log('err')
}
})
});
this just show me that it work but i dont know how to move forward
Based upon your requirement, you would have to do the appropriate form handling at client side in order to get your variables like id and comment. You can use strongly typed model binding to get your form values and process them on submit or you can use JavaScript techniques to process your form variables. To extract out id from a URL, you can use a Regular Expression or other JavaScript string parsing techniques. I am giving you a simple example of getting your id from a URL and comment from a text box using JavaScript:
Your input control would look like:
<input type="text" id="commentBox" name="Comment" class="form-control" />
In order to achieve your desired functionality using AJAX to POST your form variables to controller, refer to the following code snippet:
AJAX:
<script type="text/javascript">
var url = 'http://www.example.com/4'; //Example URL string
var yourid = url.substring(url.lastIndexOf('/') + 1);
var yourcomment= document.getElementById('commentBox').value;
var json = {
id: yourid, //4
comment: yourcomment
};
$('#submit').click(function (){
$.ajax({
url: '#Url.Action("AddComment", "Form")',
type: "POST",
dataType: "json",
data: { "json": JSON.stringify(json)},
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('err')
},
});
};
</script>
And you can get your values in your Controller like this:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult AddComment(string json)
{
if (ModelState.IsValid)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
string id= jsondata["id"];
string comment=jsondata["comment"];
// Do something here with your variables.
}
return Json(true);
}
My solution looks like this:
controller:
[HttpPost]
public JsonResult AddComment(int id_usr,string comment)
{
if (ModelState.IsValid)
{
Comments kom = new Comments();
kom.DateComment = DateTime.Now;
kom.Id_usr = id_usr;
kom.Comment = comment;
db.Comments.Add(kom);
db.SaveChanges();
return Json(kom);
}
return Json(null);
}
View
var url = window.location.pathname;
var idurl = url.substring(url.lastIndexOf('/') + 1);
$('#submit').click(function () {
console.log('click')
$.ajax({
url: '/form/AddComment',
method: 'POST',
data: {
comment: $("#Comments_Comment").val(),
id_usr: idurl,
},
success: function (data) {
console.log(data),
thank you all for guiding me to the solution
When I make ajax request to the server with breakpoint in the action method it stops on this breakpoint only the first time. After clicking for second, third etc. it goes but never stops on this breakpoint. When I change the method from GET to POST it stops every time. What is the reason for this behaviour ?
CLIENT SIDE:
$(function () {
setListAction();
});
function setListAction() {
$("li.list").on("click", function () {
alert("active");
var id = $(this).attr("file-id");
$.ajax({
type: "GET",
url: "TechAcc/ManageFile/" + id,
beforeSend: function myfunction() {
$("#loading").css("display", "block");
$("#fade").css("display", "block");
},
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}
});
});
}
SERVER SIDE:
[HttpGet]
public ActionResult ManageFile(int id = 0)
{
FileModel model = null;
if (id != 0)
model = new FileModel() { File = _repository.GetFileBy(id), GetAllFiles = _repository.GetAllFiles() };
else if (Session["Model"] != null)
model = (FileModel)Session["Model"];
else
model = new FileModel() { GetAllFiles = _repository.GetAllFiles() };
return View(model);
}
if your div with id "content" has list, it will not work.
<div id="content">
if your list is here, it won't work.
...
<li class="list">...</li>
...
</div>
if your design is like that, you need to bind click event after you replace your HTML response. i.e.,
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
//adding code here.
$("div#content").find("li.list").on("click", function() {
//same above click code should come here.
//Note: this newly added code block should not come here in click.
});
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}
I have a MVC4 single page website with a form. The loading of the contents is achieve with ajax. I do not know how to get the data out from JSON in C#? Here is my code:
JavaScript:
$("#subnt").click(function (event) {
event.preventDefault();
var url = "/Home/Submit";
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
})
});
});
C#:
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Please check below working code -
I have used exactly your working code -
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Then I used following JQuery to hit the above action -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click').click(function (e) {
$.ajax({
url: "#Url.Action("Submit")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response);
},
success: function (data) {
if (data.Success == true)
alert(data.SomeOtherData);
}
});
});
});
</script>
<input type="submit" value="click" id="click" />
And as the output I was able to get an alert as shown below -
Easiest thing to do is use the superior json.net
[HttpPost]
public string Submit()
{
var result = new { success = true, someOtherDate = "testing"};
var json = JsonConvert.SerializeObject(result);
return json;
}
Your code is ok bu you can add debugger.and open developer tools check your data .
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
debugger;
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
No, the other way around. How to retrieve the data from the form (json).
I have a partial view that contains all my buttons and it needs to display updated values after a form is submitted. At the submission I already have it rendering another partial view, is there a way to make it work where on success of that one being rendered it re-renders. Here is the code I am trying to get to work now based on what I've seen in other places.
jQuery in my view:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#ChangeGrade').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#HeatGradeDiv').find('input[name="grade"]').first().val();
var newname = $('#HeatGradeDiv').find('input[name="updatedGrade"]').first().val();
var heatname = $('#HeatGradeDiv').find('input[name="hiddenHeat"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
grade: origname,
updatedGrade: newname,
hiddenHeat: heatname
},
url: '#Url.Action("ChangeGrade","Home")',
success: function (result) { success(result); }
});
});
function success(result) {
$('#HeatGradeDiv').dialog('close');
$("#Partial_Chem_Analysis").html(result);
//ajax call I'm trying to get working
$.ajax({
type: "POST",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});
}
});
</script>
Here is the controller method I'm calling. When I run it now it is not getting hit.
public ActionResult ButtonsPartial()
{
ButtonsModel B = new ButtonsModel();
B.GetData(searchQ);
return PartialView(B);
}
Any help is appreciated.
If you attach it to a debugger such as (chrome developer tools or firebug) are you seeing any http or js errors?
It looks like you might need to make it a GET rather than POST...
$.ajax({
type: "GET",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});