.NET Make second ajax call after success of first - javascript

I've got 2 ajax calls to go to 2 separate controller methods, one to create a floorplan object and save it to the database, the other sends an array of any plan objects (chairs, tables etc.) to the same database.
I have the second ajax call within the success of the first call, however it seems to not occur initially. I have set up breakpoints to check the data, and a floorplan is definitely added with valid data. If I attempt to create another, it works then, so I'm not sure if it is a database issue or if my JavaScript is wrong.
This is the ajax calls I have for my JavaScript save function
$.ajax({
url: "/Floorplans/Create",
type: "POST",
contentType: "application/json",
data: JSON.stringify($floorplan),
success: function () {
$.ajax({
url: "/planObjects/Create",
type: "POST",
contentType: "application/json",
data: JSON.stringify($objArray)
//objArray is an array of planObjects
});
}
});
My floorplan controller:
[HttpPost]
//Floorplan controller
public ActionResult Create(Floorplan floorplan)
{
if (ModelState.IsValid){
db.Floorplans.Add(floorplan);
db.SaveChanges();
return Json(new {success = true});
}
else{
return Json(new {success = false});
}
}
planObjects controller:
[HttpPost]
public void Create(List<planObject> newObjects)
{
var model = new planObject();
if (ModelState.IsValid)
{
newObjects.ForEach(r => db.planObjects.Add(r));
db.SaveChanges();
}
}
With this code, the ajax call within the success of the first ajax call is not executed on first attempt, but if I make another floorplan it works perfectly. Can you guys see a fix to the problem? I was attempting to use a single controller action method but I was unable to get it working correctly.

Modified your code a bit (I could make it work locally). I suspect it could be the "data" element in second call causing the trouble. I would check the progress step by step and go from there.
If you add some alert or log messages like below, what do you see?
<script>
$.ajax({
url: '#Url.Action("Create", "FloorPlans")',
type: "POST",
contentType: "application/json",
data: JSON.stringify($floorplan),
success: function(result) {
if (result.success) {
Log("Floor plan created successfully, adding plan objects...");
$.ajax({
url: '#Url.Action("Create", "PlanObjects")',
type: "POST",
contentType: "application/json",
data: JSON.stringify($objArray),
//objArray is an array of planObjects
success: function(result2) {
if (result2.success) {
Log("Plan objects created successfully");
} else {
Log("Failed to create plan objects");
}
}
});
} else {
Log("Failed to add floor plan");
}
}
});
function Log(data) {
//alert(data);
console.log(data);
}
</script>

Related

MVC Get method not hit after javascript ajax post

So I have these two controller methods that works:
[HttpGet]
public ActionResult EditWork(string work)
{
// do the bla bla
return Json(new {Success = true});
}
[HttpPost]
public ActionResult EditWork(WorkObjet work)
{
// Do the bla bla!
var listWork = TempData.Peek("myWorks") as List<WorkObjet>;
// Edit the value of the correct work object.
return Json(new {Success = true});
}
And they get called via Javascript like this:
function EditWork(event, anc) {
event.preventDefault();
var param = anc.attributes["data-id"].nodeValue;
$.ajax({
type: 'GET',
url: #Url.Action("EditWork", "Work"),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { work: param }
}).done(function (data) {
if (data.Success === true) {
// Update the fields
} else {
console.log("Error:" + param);
}
}).fail(function (xhr) {
console.log(xhr.responseText);
});
}
function SaveEdit(){
var myWork = GetMyWork() // calls the field via jQuery
$.ajax({
type: 'POST',
url: #Url.Action("EditWork", "Work"),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ work: myWork })
}).done(function (data) {
if (data.Success === true) {
// reload the page?
windows.location.reload();
} else {
console.log("Error:" + param);
}
}).fail(function (xhr) {
console.log(xhr.responseText);
});
}
And they work really well. So let's do the following:
Click on the button to edit a work
The Controller Get method EditWork is hit via breakpoint;
Edit the work, then save
The Controller Post method EditWork is hit via breakpoint and the work is updated in a list;
The page gets refreshed
Click on the button to edit again
The GET method is not hit via breakpoint, The old work gets shown at screen. Very odd.
Edit the work, then save
The POST method is hit with the values...
How is step seven even possible?
Add this to your GET request:
cache: false
By default jQuery allows browser to cache the result of GET Ajax requests. Look at the documentation for more info.

Calling Action with ajax doesnt show page

I want to call a controller method with an Ajax call. If this is called, another view should be returned.
When I debug the code, I also reach my controller method. However, the new view is not displayed.
What am I doing wrong?
Controller:
public ActionResult RequestDetails(string requestId, string requestState)
{
// ToDo handle parameter
return View();
}
JS:
ShowDetails = function (e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
$.ajax({
type: 'GET',
data: {
'requestId': dataItem.RequestId,
'requestState': dataItem.RequestState
},
url: "/Controller/RequestDetails",
contentType: 'application/json; charset=utf-8'
});
}
What I am doing wrong?
best regards
It wouldn't show unless you direct it about what to do with the result that is returned from the ajax call.
You would need to create a container html element on the main View which is currently being displayed on the page firstly:
<div id="RequestDetailsContainer">
</div>
and then in the success callback you will need to put the html returned by controller action to be displayed in that div :
$.ajax({
type: 'GET',
data: {
'requestId': dataItem.RequestId,
'requestState': dataItem.RequestState
},
url: "/Controller/RequestDetails",
contentType: 'application/json; charset=utf-8',
success: function(response) { // note this function
$("#RequestDetailsContainer").html(response);
}
});
A side note about the url property that, you should be using Url.Action for generating the urls instead of using string literals like:
url: "#Url.Action("RequestDetails","Controller")"
Hope it helps.

JQuery, Ajax and MVC6 parameter is null after ajax request

I'm new in asp.net core, c# and MVC 6. I'm trying to send data over ajax to my controller.
function ajaxMethodData() {
$.ajax({
url: "AjaxWithData", // hard coded for testing
type: "POST",
data: JSON.stringify({ username: "NeXT405" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
},
error: function () {
alert('error');
}
});
}
The method in the controller looks like this. The method gets invoked by the ajax request.
[HttpPost]
public IActionResult AjaxWithData([FromBody] string username )
{
Debug.WriteLine(username);
return Json(new { success = true } );
}
It looks like the data has been sent right.
If I have understood it correctly the string should now have the value from the passed data. But it is still null.
I have also tried it with void as return value (and no dataType).
<input type="button" value="Fatty2" onclick="ajaxMethodData()" />
What I'm doing wrong?
Just change
data: JSON.stringify({ username: "NeXT405" }),
To
data: JSON.stringify("NeXT405"),
WebApi only allow to get 1 parameter from body, so the variable name is not needed for basic types.
Just check: https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-1
The last example is exactly your case

Is it impossible to download file via AJAX call in ASP.NET MVC5?

I know it seems to be better to use normal call instead of AJAX call but for some reason i.e. displaying error message on modal dialog in case a problem during download, I need to download file by using an AJAX call in an MVC5 project. Here is what I did finally after lot of tries:
View:
Download
function downloadFile() {
$.ajax({
type: 'POST',
url: '/Experiment/GetFile',
data: '{id:' + 8 + '}', //For test purpose I used static id
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (returnValue) {
window.location = '/Experiment/GetFile?id=' + returnValue;
}
});
};
Controller:
In Controller, I have a method something like that, but I am really confused if I should do the same method for AJAX Post and success method or not.
[HttpPost]
public ActionResult GetFile(int id)
{
var dataContext = repository.FileAttachments.FirstOrDefault(m => m.Id == id);
if (dataContext == null)
{
return Json(new { success = true, returnValue = "8" });
}
else
{
return Json(new { success = false, message= "Error..." }, JsonRequestBehavior.AllowGet);
}
}
Is there a smart approach to perform this dosnload operation using AJAX call in ASP.NET MVC5?
You need to return file name or file path
Example "/file/download.doc"
And then you need to edit view page like follow
Download
<a href="" id="todownload" download>
function downloadFile() {
$.ajax({ type: 'POST', url: '/Experiment/GetFile', data: '{id:' + 8 + '}', //For test purpose I used static id
contentType: 'application/json; charset=utf-8', dataType: 'json',
success: function (returnValue)
$("#todownload").attr('href',returnValue);
$("#todownload").click();
}
});
};

When sending jQuery post to MVC controller getting 404 error

I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int

Categories

Resources