Ajax form submit calling method twice in ASP.NET MVC - ajax

I have a weird scenario happens when I send my ajax request that has 2 objects
first time it passes the second obj with the right value while the first object is null.Then second call it passes the first obj with value and the second obj as null
Here's my ajax method
var serializedForm = $(form).serialize();
var postData = {
merchTask: obj,
items: arrItems
};
$.ajax({
type: "POST",
url: $(form).attr('action'),
contentType: "application/json; charset=utf-8",
dataType:'json',
data: JSON.stringify(postData),
success: function (response) {
alert('done');
},
error: function (xhr, status, error) {
alert("Oops..." + xhr.responseText);
}
});
And here's my action in controller
public ActionResult EditTask(Task merchTask, string[] items)
{
short CompanyID = Convert.ToInt16((gSessions.GetSessionValue(gSessionsData.Company) as Company).ID);
try
{
merchTask.CompanyID = CompanyID;
if (merchTask.TaskID != 0)
{
taskTemplatesBF.Update(merchTask);
}
else
{
taskTemplatesBF.InsertMerchTask(merchTask);
}
string[] selectedLst = items;
foreach (string item in selectedLst)
{
taskTemplatesBF.InsertItemsLink(CompanyID,merchTask.TaskID,merchTask.ItemCode);
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
ModelState.AddModelError("", ex.InnerException.Message);
}
ModelState.AddModelError("", ex.Message);
}
return RedirectToAction("TasksTemplates", "Merch");
}
*I found a workaround to send each object separately in different ajax
but what's wrong when I send them in one request?

You have added a lot of code in the question but missed the code that was actually needed.
Okay add the event.preventDefault(); and event.stopImmediatePropagation(); functions inside your form summit event as follows:
$(document).ready(function(){
$("formId").on('submit',function(event){
event.preventDefault();
event.stopImmediatePropagation();
var serializedForm = $(form).serialize();
var postData = {
merchTask: obj,
items: arrItems
};
$.ajax({
type: "POST",
url: $(form).attr('action'),
contentType: "application/json; charset=utf-8",
dataType:'json',
data: JSON.stringify(postData),
success: function (response) {
alert('done');
},
error: function (xhr, status, error) {
alert("Oops..." + xhr.responseText);
}
});
});
});
Hope this will solve your problem.

Related

Ajax post method returns undefined in .net mvc

I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?

ajax call returning promis and resolve it by the calling function to its value

By now i read somewhere around 6 pages containing documentations and stackoverflow answers but I don't get the method.
My function is by now after reading all the stuff built like this:
async function getFToken(postId){
const response = await $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data:{
action:'get_f_token',
postId: postId,
},
success:function(response) {
}
});
return response;
}
and in my other function is like this:
function getFeedback(postId){
$(".show_company").hide();
$(".show_feedback").show();
$.ajax({
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data:{
action:'get_feedback',
postId: postId,
},
success:function(response) {
var postTitle = '';
for (i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
var test = getFToken(387);
alert(Promise.resolve(test));
};
$("#result").html(postTitle);
}
});
}
is there any chance, that this is a bigger issue because i call a async in another Ajax call trying to retrieve the value? I'm trying to get the string from the first ajax call and hand it to the second function in the ajax call to attach it to the posts i retrieve from WordPress
The alert is giving me [object Promise] but how do i get the value passed from the php script?
php-scrtipt:
//get fToken from specific feedbacks
add_action( 'wp_ajax_get_f_token', 'get_f_token' );
function get_f_token() {
if(isset($_POST['postId'])){
$postId = $_POST['postId'];
}
$fToken = get_post_meta($postId, 'fToken', true);
echo $fToken;
wp_die();
}
Don't use success callbacks when you can use async/await:
async function getFToken(postId) {
return $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data: {
action: 'get_f_token',
postId: postId,
}
});
}
async function getFeedback(postId) {
$(".show_company").hide();
$(".show_feedback").show();
const response = await $.ajax({
// ^^^^^
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data: {
action: 'get_feedback',
postId: postId,
}
});
let postTitle = '';
for (const i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
const test = await getFToken(387);
// ^^^^^
alert(test); // no Promise.resolve, you don't want to alert a promise
}
$("#result").html(postTitle);
}

Ajax call to Webmethod, cross domain

I have two Asp projects. On close of a dialog box in project A I am trying to call a static webmethod in project B using ajax call.
Instead of calling the Webmethod it is calling the PageLoad.
Any ideas what I am doing wrong?
WebMethod
[WebMethod]
public static string UpdateSession()
{
return "Test";
}
$(function () {
$('div#DialogDiv').on('dialogclose', function (event) {
CloseDialog("http://localhost:1330/Application_Default.aspx/UpdateSession");
return false;
});
});
function CloseDialog(URL) {
jQuery.support.cors = true;
$.ajax({
type: "GET",
url: URL,
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (response) {
alert("success");
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}
Try this with pure javascript
function CloseDialog(URL) {
var request = new XMLHttpRequest();
request.open("GET", URL);
request.onload = function() {
if (request.status === 200) {
alert(request.responseText);
// to convert to JSON object-> JSON.parse(request.responseText);
} else {
alert("Failed to trying to find the method: " + URL );
}
};
request.send();
return false;
}
With jQuery I would just do this, you don't need more. It should work with cross-domain too.
function CloseDialog(URL) {
$.ajax({
url: URL,
success: function (response) {
jQuery.each(result.list, function(i, val) {
// iterate the JSON object
// val.node;
});
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}

Pass action with model to jquery ajax success call

My Jquery Ajax Call. How to return model from action to ajax and pass to another action.
function ChangeName(id)
{
var name=$("#name").val();
$.ajax({
cache:false,
url: "#Url.Action("EditName", "Order")",
data: "Name=" +name+"&Id="+id ,
type: "POST",
success: function (data) {
window.location.href=data.Url;//doesnt work passes null model
}
});
}
public ActionResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(new
{
Url = Url.Action("Test","Order",new{model=model})
},JsonRequestBehavior.AllowGet);
}
public ActionResult Test(ProdModel model)//Model null
{
return RedirectToAction("List", "Product");
}
I have tried this but not getting success.
Try this
function ChangeName(id)
{
var name=$("#name").val();
var params = {
Name: name,
Id: id
};
$.ajax({
cache:false,
url: '#Url.Action("EditName", "Order")',
data: JSON.stringify(params),
type: "POST",
success: function (data) {
window.location.href=data.Url;//doesnt work passes null model
}
});
}
[HttpPost]
public ActionResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(new
{
Url = Url.Action("Test","Order",new{model=product})
},JsonRequestBehavior.AllowGet);
}
Try as follows
In Edit Action try returning the model instead of url,
public josnResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(model,JsonRequestBehavior.AllowGet);
}
Then in ajax Success call you can make another call to Test Action
$.ajax({
cache:false,
url: '#Url.Action("EditName", "Order")',
data: JSON.stringify(params),
type: "POST",
success: function (data) {
CallTestAction(data);
}
});
var CallTestAction = function(data) {
$.ajax({
cache:false,
url: '#Url.Action("Test", "Order")',
data: {model = data},
type: "POST",
success: function (data) {
}
});
};

asp.net mvc 3 json does not work

This is my jquery with json
$('#btnVerificationOk').click(function () {
var verId = $('#trans_verification_id').val();
var verCode = $('#trans_verification_code').val();
$.ajax({
url: '/Profile/CompleteTransactions',
type: 'POST',
data: { },
dataType: 'json',
success: function (result) {
alert(result);
},
error: function () {
alert('ERROR ERROR !!!!!!!!!!!!');
}
});
});
And My C# method:
[Authorize]
[HttpPost]
private JsonResult CompleteTransactions()
{
return Json("Done");
}
Its always alerts 'ERROR ERROR !!!!!!!!!!!!' i tried debugging but CompleteTransactions method is not firing
And this is my second json which is bellow and works good
$('#btnTransfareOk').click(function () {
var userName = $('#transfare_username').val();
var amount = $('#transfare_amount').val();
if (userName == '' || amount == '') {
$('#transfare_error_list').html('Please fill boxes.');
} else {
$.ajax({
url: '/Profile/TranfareMoney',
type: 'POST',
data: { ToUsername: userName, Amount: amount },
dataType: 'json',
success: function (result) {
$('#transfare_error_list').html(result.text);
$('#trans_verification_id').val(result.id);
$('#transfare_username').val("");
$('#transfare_amount').val("");
},
error: function () {
$('#transfare_error_list').html('Oops... Error.');
}
});
}
});
I'm not 100% sure, but shouldn't you controller action handler be public ?

Resources