MVC javascript ajax call results in xmlhttprequest warning - javascript

When running the following code I get the desired results updating my view on success, but I also get a warning in the console and certain items on the page don't work any more. I though putting the async option in would have sorted it but obviously not.
Can anyone suggest how I should change this?
xmlhttprequest on the main thread is deprecated because of its
detrimental effects to the end user's experience
$("#addSelectedModules").on("click", function () {
event.preventDefault();
$('#createLearningPathForm').validate();
if ($('#createLearningPathForm').valid()) {
var request = $.ajax({
async: true,
type: "POST",
url: "/umbraco/Surface/CreateLearningPath/SetSelectedList",
data: $('#createLearningPathForm').serialize(),
success: function (data) {
$("#top").html(data);
},
error: function (data) {
//$('#failModal').removeClass("d-none").addClass("d-block");
}
})
}
}
);

Related

Javascript - How to pass data from two API ajax calls to one function

I am attempting to make two seperate ajax calls to a third party API end point and display both its data on a HighChart graph. I am attempting to pass the data from both calls into my drawHighcharts function in order to display the data.
I am having issues with properly passing the data from both ajax calls. I've attempted to call back my drawHighcharts function in both my ajax calls. When console.logging both data I am only seeing the first stData but the odData is returning undefined. I am returning back stData twice and I believe that is because I am calling my function twice.
What is the proper way of handling both data into one function?
My expected outcome is to be able to access odData and stData in my drawHighCharts function.
function getStData() {
$.ajax({
type: "GET",
url: stUrl,
async: true,
success: function (stData) {
drawHighCharts(stData)
},
error: function (e) {
// handle exception
console.log("Error occured while reading resource file: ", e);
}
});
}
function getOdData() {
$.ajax({
type: "GET",
url: odUrl,
async: true,
success: function (odData) {
drawHighCharts(odData)
},
error: function (e) {
// handle exception
console.log("Error occured while reading resource file: ", e);
}
});
}
function drawHighCharts(stData, odData) {
console.log(stData, "st")
console.log(odData, "od")
}
You're getting undefined because in your ajax calls you're only passing one argument. In getStData you're passing only stData to drawHighCharts and for getOdData you're only passing odData. It would make sense why in the drawHighCharts function one of the two arguments (the second one) is undefined since you're only passing one argument. Instead, you can wrap multiple get requests in Promise.all. This way your requests will be made and when they are both finished the promise will resolve and you can access both API results in the then following the Promise.all. See below.
function getStData() {
$.ajax({
type: "GET",
url: stUrl,
async: true,
success: function (stData) {
return stData
},
error: function (e) {
// handle exception
console.log("Error occured while reading resource file: ", e);
}
});
}
function getOdData() {
$.ajax({
type: "GET",
url: odUrl,
async: true,
success: function (odData) {
return odData
},
error: function (e) {
// handle exception
console.log("Error occured while reading resource file: ", e);
}
});
}
function drawHighCharts(stData, odData) {
console.log(stData, "st")
console.log(odData, "od")
}
Promise.all([
getStData(),
getOdData(),
]).then(([stData, odData]) => drawHighCharts(stData, odData))
This post is related to fetch requests in React but Promise.all can be used with ajax in regular JS.
You can call getOdData() inside success of getStData() and pass stData to it. And then inside success of getOdData() you will have access to both stData and odData. Now you can call drawHighCharts() with both stData and odData.

TypeScript : Ajax call call always calling Error rather than success on success

In typescript I have a DataAccess Class so that all Ajax calls are routed through a single object to save repetition of code in a lot of places within my application.
In using this approach I have needed to use call backs to get the response back to the calling class so that the success and error can be handled accordingly.
This is the typescript
ajaxCall(retVal, retError) {
$.ajax({
type: this.callType,
data: this.dataObject,
dataType: this.dataType,
url: this.url,
contentType: this.contentType,
traditional: this.traditional,
async: this._async,
error: retError,
success: retVal
});
}
This is the compiled Javascript
AjaxDataAccessLayer.prototype.ajaxCall = function (retVal, retError) {
$.ajax({
type: this.callType,
data: this.dataObject,
dataType: this.dataType,
url: this.url,
contentType: this.contentType,
traditional: this.traditional,
async: this._async,
error: retError,
success: retVal
});
};
return AjaxDataAccessLayer;
This calls through to the ASP.Net MVC controllers perfectly fine, however the problem that I have is regardless of Success or Error the call back is always retError.
This is the calling Typescript
var _this = this;
var dataAccess = new DataAccess.AjaxDataAccessLayer(Fe.Upsm.Enums.AjaxCallType.Post,
Fe.Upsm.Enums.AjaxDataType.json,
"../../PrintQueue/DeletePrintQueueItems",
jsonObj);
dataAccess.ajaxCall(data => {
// success
new Fe.Upsm.Head().showGlobalNotification("Selected Items Deleted");
_this.refreshPrintQueueGrid();
(window as any).parent.refreshOperatorPrintQueueCount();
}, xhr => {
// failure
alert("An Error Occurred. Failed to update Note");
});
When stepping through and looking at this the Status is OK and the response is 200.
So, Problem (as mentioned above) always calling xhr \ retError regardless of success.
Question: How do I get it to go into the right call back?
In your error handler, you were not passing all the parameters, so you are only checking whether the request finished successfully. However, there can be errors after that, like when the response is processed. You can handle errors betters like this:
dataAccess.ajaxCall(data => {
// success
new Fe.Upsm.Head().showGlobalNotification("Selected Items Deleted");
_this.refreshPrintQueueGrid();
(window as any).parent.refreshOperatorPrintQueueCount();
}, (xhr, errorText, errorThrown => {
// failure
console.log(xhr, errorTest, errorThrown);
alert("An Error Occurred. Failed to update Note");
});
Based on the discoveries using this method, the error is that your controllers are returning empty responses, so you're getting an exception when jQuery tries to parse them, because an empty string is not valid JSON.

Highcharts Ajax

This was something that I struggled with, and found the answer on stackoverflow, so I thought I should share it.
This is Jquery syntax.
$.ajax({
url: 'AjaxPHPScript.php'
type: 'POST',
data: "chartdata="+chartdata, // this is what I pass to the Ajax call
success: function(result) {
// this is when it comes back from Ajax
// this will NOT work
$("#"+contentdiv).highcharts(result);
// this will
// the parentheses around the JSON results inside the eval function is the key!
var chartstuff=eval("("+result+")");
$("#"+contentdiv).highcharts(chartstuff);
// I did not discover this on my own, I got the lead from this post:
// http://stackoverflow.com/questions/13718326/javascript-string-to-object
},
error: function(e) {
console.log(e);
console.log(JSON.stringify(e));
}
});

Calling a C# method from JavaScript

I want to to call a method GetAccount from my controller AccountController.cs, in my JavaScript factory LoginFactory.js. Something like this:
AccountController.cs:
public Account GetAccount(string userName)
{ ... }
LoginFactory.js:
if(x>y) {
var account = <%AccountController.GetAccount(someParam);%>
}
I've tried using [WebMethod] and Ajax, but I can't get it to work: I get a 404 response.
Assuming your GetAccount method can be reached at /Account/GetAccount when your application runs, you could use the following:
$.ajax({
type: 'GET',
url: '/Account/GetAccount',
data: { 'username' : 'a-username' },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('error');
}
});
Note - this is dependant on jQuery.
This causes the browser to make a request to /Account/GetAccount as if you had done so by entering the URL in the URL bar, but of course, captures the returned json for use in your client side (javascript) script.
If this returns a 404, it would be worth checking your routing.

javascript frameworks prototype to jquery

I have found the following script which is apparently written using the javascript framework prototype.
Event.observe(window, 'load', function() {
Event.observe( 'btnSubmit', 'click', purchaseCD);
connectToServer();
});
function connectToServer()
{
new Ajax.Updater(
{ success: 'CD Count', failure: 'errors' },
'server_side.php',
{
method: 'get',
onSuccess: function(transport)
{
if (parseInt(transport.responseText)) connectToServer();
}
});
}
function purchaseCD()
{
new Ajax.Updater(
{ success: 'CD Count', failure: 'errors' },
'server_side.php',
{
method: 'get',
parameters: { num: $('txtQty').getValue() }
});
}
Is anyone here able to convert this script to use jQuery instead of prototype? I don't know prorotype at all so I don't understand it.
Ajax.Updater takes, as parameter 1, two containers into which it will update the successful or failed response of a request to the URL given in parameter 2.
What this script does is that upon page load (I translated it below to DOMReady which is not exactly the same, but jQuery convention) an AJAX request is sent to server_side.php. If it gets a response that it understands, it immediately sends off another request, in order to keep the session alive.
This looks like a terrible design. If you're going to do something like that, you definitely want a timeout between the requests.
Another thing that's not very neat with this script is that every AJAX request is handled by the same page - server_side.php - relying on different parameters for instructions on what action to perform. It would appear cleaner to simply request different pages for different actions.
$(function() {
$('#btnSubmit').click(purchaseCD);
connectToServer();
});
function connectToServer() {
$.ajax({
url: "server_side.php",
success: function(res) {
$('#CD Count').html(res);
if(parseInt(res))
connectToServer();
},
error: function(xhr) {
$('#errors').html(xhr.responseText);
}
});
}
function purchaseCD() {
$.ajax({
url: "server_side.php",
success: function(res) {
$('#CD Count').html(res);
},
data: { num: $('#txtQty').val() },
error: function(xhr) {
$('#errors').html(xhr.responseText);
}
});
}

Categories

Resources