<script>
function Test()
{
var selected = new Array();
$('input:checked').each(function () {
selected.push($(this).attr('id'));
});
var postData = { values: selected };
var url = '#Url.Action("ExportExcelFilesToDropBox", "Home")';
$.ajax({
type: "POST",
url: url,
data: postData,
success: function (result) {
if (result == "Success")
{
AfterCreationOfFiles(selected);
}
}, dataType: "json",
traditional: true
});
}
function AfterCreationOfFiles(selected)
{
var MyFiles = [];
jQuery.each(selected, function (i, val) {
if(val=="Address")
{
MyFiles.push({ 'url': 'http://-----/Content/File/Addresses.xlsx', 'filename': 'Addresses.xlsx' });
}
if (val == "DebitDetail")
{
MyFiles.push({ 'url': 'http://-----/Content/File/DebitDetails.xlsx', 'filename': 'DebitDetails.xlsx' });
}
if (val == "AddressAssociated") {
MyFiles.push({ 'url': 'http://-----/Content/File/AddressAssociatedCompanies.xlsx', 'filename': 'AddressAssociatedCompanies.xlsx' });
}
if (val == "DebitDetailAssociated") {
MyFiles.push({ 'url': 'http://-----/Content/File/DebitDetailsAssociatedCompanies.xlsx', 'filename': 'DebitDetailsAssociatedCompanies.xlsx' });
}
});
var options = {
files: MyFiles,
// Success is called once all files have been successfully added to the user's
// Dropbox, although they may not have synced to the user's devices yet.
success: function () {
// Indicate to the user that the files have been saved.
alert("Success! Files saved to your Dropbox.");
DeleteFiles(selected);
},
// Progress is called periodically to update the application on the progress
// of the user's downloads. The value passed to this callback is a float
// between 0 and 1. The progress callback is guaranteed to be called at least
// once with the value 1.
progress: function (progress) { },
// Cancel is called if the user presses the Cancel button or closes the Saver.
cancel: function () { },
// Error is called in the event of an unexpected response from the server
// hosting the files, such as not being able to find a file. This callback is
// also called if there is an error on Dropbox or if the user is over quota.
error: function (errorMessage) { }
};
Dropbox.save(options);
}
function DeleteFiles(selected)
{
var postData = { values: selected };
var url = '#Url.Action("DeleteEXCELFiles", "Home")';
$.ajax({
type: "POST",
url: url,
data: postData,
success: function (result) {
if (result == "Success") {
}
}, dataType: "json",
traditional: true
});
}
</script>
Above code runs successfuly on my localhost
But when i upload it to server then I am having the following Error, i cant understand it
POST http://------/Home/ExportExcelFilesToDropBox 500 (Internal Server Error)
i.support.ajax.i.ajaxTransport.send # jquery?v=JzhfglzUfmVF2qo-weTo-kvXJ9AJvIRBLmu11PgpbVY1:1
i.extend.ajax # jquery?v=JzhfglzUfmVF2qo-weTo-kvXJ9AJvIRBLmu11PgpbVY1:1
Test # Dashboard:216
onclick # Dashboard:192
jquery?v=JzhfglzUfmVF2qo-weTo-kvXJ9AJvIRBLmu11PgpbVY1:1
XHR finished loading: POST "http://------//Home/ExportExcelFilesToDropBox".
i.support.ajax.i.ajaxTransport.send # jquery?v=JzhfglzUfmVF2qo-weTo-kvXJ9AJvIRBLmu11PgpbVY1:1
i.extend.ajax # jquery?v=JzhfglzUfmVF2qo-weTo-kvXJ9AJvIRBLmu11PgpbVY1:1
Test # Dashboard:216
onclick # Dashboard:192
Related
I am doing a few recurring AJAX calls where I pass an array from the front-end to the back-end and whenever it comes back to the front-end, the array gets smaller (by 1) and ultimately it'll be empty, therefore my recursive calls will stop.
Here's my calls:
function download_required_files(demo_data) {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
return false;
}
if(data.can_continue !== 'yes') {
return false;
}
if(data.remaining_steps && data.remaining_steps.length) {
demo_data.steps_to_take = data.remaining_steps;
download_required_files(demo_data);
}
$('.demo-loader-content').fadeOut();
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
Assuming I have 2 steps to download files for, this download_required_files will run twice, then it'll be done, but if I do:
var download_process = download_required_files(demo_data) //Runs 2 times
download_process.done(function() { //Do stuff here once that function ran 2 times });
It gives me the: Cannot read property 'done' of undefined error and for good reason. That download_process is not a promise object for it to have that property, it's just...empty.
Where should I intervene in my download_required_files so that it signals to outside code that "Hey, in a promise environment, I'm done!"?
Although the result of the call to $.ajax is a jqXHR object, which is promise-like, for what you describe I think I'd go with your own native Promise (or Deferred if you prefer) to represent the overall recursive process:
function download_required_files(demo_data) {
return new Promise(function(resolve, reject) {
function worker() {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
// *** All done
$('.demo-loader-content').fadeOut();
resolve();
} else if(data.can_continue !== 'yes') {
// *** All done; but is this an error condition? If so
// use `reject` instead of `resolve` below.
$('.demo-loader-content').fadeOut();
resolve();
} else {
demo_data.steps_to_take = data.remaining_steps;
worker(); // This is the internal recursive call
}
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
worker();
});
}
Or using Deferred instead:
function download_required_files(demo_data) {
var d = $.Deferred();
function worker() {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
// *** All done
$('.demo-loader-content').fadeOut();
d.resolve();
} else if(data.can_continue !== 'yes') {
// *** All done; but is this an error condition? If so
// use `d.reject` instead of `d.resolve` below.
$('.demo-loader-content').fadeOut();
d.resolve();
} else {
demo_data.steps_to_take = data.remaining_steps;
worker(); // This is the internal recursive call
}
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
worker();
return d.promise();
}
This would be my approach, separating the individual AJAX requests from the looping over the content, and that also from the DOM updates:
function download_one_file(demo_data) {
return jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: setup_page_params.ajax_nonce,
content_install_request_data: JSON.stringify(demo_data),
}
});
}
function download_loop(demo_data) {
return download_one_file(demo_data).then(function(data) {
if (!data) {
return Promise.reject();
} else if (data.remaining_steps && data.remaining_steps.length) {
demo_data.steps_to_take = data.remaining_steps;
return download_loop(demo_data);
} else {
return Promise.resolve();
}
});
}
function download_required_files(demo_data) {
return download_loop(demo_data).finally(function() {
$('.demo-loader-content').fadeOut();
});
}
I have some code on a file that makes Ajax calls. This file is being called as a function by multiple other files that creates a new instance each time.
This is the JS code that is being called:
define(["underscore", "homeop", "domReady!"],
function (_, homeop, domready) {
var timeout = 500;
return function (opUrl, opList, onCallback) {
// IRRELEVANT CODE
var getFetch = function (optionName) {
$.ajax({
url: optionsUrl,
data: { optionNames: [optionName] },
type: "POST",
dataType: "json",
async: false,
traditional: true,
success: function (data) {
_.each(data, function (optionData, optionName) {
if (homeop.globalCache[optionName] === null) {
homeop.globalCache[optionName] = optionData;
}
});
},
error: function (message) {
console.error(message.responseText);
}
});
};
self.getInfo = function (optionName) {
if (homeop.globalCache[optionName] === undefined) {
if (!_.contains(homeop.getOption(), optionName)) {
getFetch(optionName);
}
// MORE IRRELEVANT CODE GOES HERE
In other JS files, I call the get function; for example
var these = new getOptions(optionsUrl, optionsList, onLoadCallback);
var getOpt = these.get(OptionsUrl);
The problem is I am making multiple calls to the get information from the database causing multiple call to my JS file. Each new instance of the JS file will create a ajax call.
Is there a way to wait for all the calls to be done and then get data from the database? In other words how can I somehow combine all the call to my 'getOption.js'?
Thanks
Try this.. You can also implement queue in place of stack
var optionStack = [];
var isAvailable = true;
var getFetch = function (optionName) {
if(isAvailable){
isAvilable = false; // function not available now
}
else {
optionStack.push(optionName)
return;
}
$.ajax({
url: optionsUrl,
data: { optionNames: [optionName] },
type: "POST",
dataType: "json",
async: false,
traditional: true,
success: function (data) {
_.each(data, function (optionData, optionName) {
if (homeop.globalCache[optionName] === null) {
homeop.globalCache[optionName] = optionData;
}
});
},
error: function (message) {
console.error(message.responseText);
},
done: function (){
isAvailable = true;
if(optionStack.length > 0){
getFetch(optionStack.pop());
}
}
});
};
I am now trying to build a dnn module using ajax calls. But there is a jquery error stating
SyntaxError: Unexpected token <
I have tried to work around with ajax "url: " and tried to create a new ascx at the root folder but still showing error 404.
My ajax call is as below
$.ajax({
url: "NewsManagement.ascx/Add",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "POST",
beforeSend: function () {
},
cache: false,
data: {
title : $('#txt_Title').val(),
news_content : $('#txt_Content').val(),
image : $('#file_Image').val(),
chapter_id : $('#sel_Chapter').val(),
is_draft : $('#chk_Draft').val(),
posted_date : $('#dp_PostDate').val(),
created_by : "",
lastupdate_by : ""
},
success: function (data) {
console.log(data);
if (data == "success") {
console.log(data);
}
else {
initMdlError("SERVER : " + data);
}
},
error: function (data, textStatus, error) {
// ERROR IS BEING CALLED FROM HERE
console.log("JQUERY JAVASCRIPT : " + error);
initMdlError(error);
},
complete: function () {
console.log('complete');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is there any way to solve the issues?
The problem you're running into is that DNN isn't handling the requested URL properly that you are calling. If you want to call a service URL in DNN you're going to want to setup routes to handle the calls.
namespace Christoc.Com.Modules.SlidePresentation.services
{
public class SlidePresentationRouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapRoute("SlidePresentation", "{controller}.ashx/{action}",
new[] {"Christoc.Com.Modules.SlidePresentation.services"});
}
}
}
In the Controller you can define the methods available
[DnnAuthorize(AllowAnonymous = true)]
public ActionResult ListOfSlides()
{
try
{
var slides = Slide.GetSlides(ActiveModule.TabID, ActiveModule.ModuleID);
return Json(slides, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
DnnLog.Error(exc);
return Json(null, JsonRequestBehavior.AllowGet);
}
}
https://slidepresentation.codeplex.com/SourceControl/latest#DesktopModules/SlidePresentation/services/SlidePresentationController.cs
sample Javascript
//get slides on initialization
this.init = function(element) {
//var data = {}; //removed because we don't need this
//data.moduleId = moduleId; //removed because we don't need this when calling setModuleHeaders
//data.tabId = tabId; //removed because we don't need this
//serviceFramework.getAntiForgeryProperty(); //removed because we don't need this
$.ajax({
type: "POST",
cache: false,
url: baseServicePath + 'ListOfSlides',
//data: data,
//dataType:"json",
beforeSend: serviceFramework.setModuleHeaders
}).done(function(data) {
viewModel.slides = ko.utils.arrayMap(data, function(s) {
return new slide(s);
});
ko.applyBindings(viewModel);
$(element).jmpress();
}).fail(function () {
Console.Log('Sorry failed to load Slides');
});
};
Here's an example module that does this
https://slidepresentation.codeplex.com/
And a user group video I did years ago on this module.
https://www.youtube.com/watch?v=hBqn5TsLUxA
I have below code, it executes when I click on a button.
I need to display a progress bar/waiting image in the browser for 5 seconds, when user clicks on a button. How to set time out and how to display progress bar/waiting page image in the page when user clicks on a button
$("#btnSubmit").click(function(){
var formData = $("form").serialize();
$.ajax({
url: 'cgi-bin/config',
type: 'POST',
data: formData, // An object with the key 'submit' and value 'true;
success: function (result) {
console.log(result);
},
failure: function () {
alert("Ajax request failed!!!");
},error: function () {
alert("Ajax request failed to update data!!!");
}
});
});
i could able to fix my code with the link jsfiddle.net/joshdavenport/Qw6uv/4 , this works fine..
Use beforeSend and complete
$("#btnSubmit").click(function(){
var formData = $("form").serialize();
$.ajax({
url: 'cgi-bin/config',
type: 'POST',
data: formData, // An object with the key 'submit' and value 'true;
success: function (result) {
console.log(result);
},
failure: function () {
alert("Ajax request failed!!!");
},error: function () {
alert("Ajax request failed to update data!!!");
},
beforeSend: function(){
$('.progress').show();
},
complete: function(){
$('.progress').hide();
}
});
});
HTML
<div class="progress" style="display:none;"><img src="loading.gif" />Loading...</div>
$("#btnSubmit").click(function(){
var startTime = Date.now(),
// finish function is called at the end - when request is completed and at least 5s passed
// result will be null on error or whatever was received by success callback
finish = function (result) {
if (result === null) {
// probably error, handle it..
} else {
// handle result
}
$('#progress').hide();
},
checkDone = function (result) {
var r = Date.now() - startTime; // time taken by request
if (r < 5000) { // if less than 5s then set timeout for remaining time
setTimeout(function () {
finish(result);
}, 5000 - r);
} else { // if there was already 5s finish immediately
finish(result);
}
},
formData = $("form").serialize();
$('#progress').show();
$.ajax({
url: 'cgi-bin/config',
type: 'POST',
data: formData, // An object with the key 'submit' and value 'true;
success: function (result) {
console.log(result);
checkDone(result);
},
failure: function () {
alert("Ajax request failed!!!");
checkDone(null);
},
error: function () {
alert("Ajax request failed to update data!!!");
checkDone(null);
}
});
});
progress div example (just put in body):
<div id="progress" style="display:none;position:absolute;z-index:99999;top:0;left:0;width:100%;height:100%;opcity:0.7;background:url('/img/progress.gif') 50% 50% no-repeate #000"></div>
in my MVC layout page I have the following:
$("body").ajaxError(
function (e, request) {
if (request.status == 403 || request.status == 500) {
window.location = '#Url.Action("LogOn", "Account", new {area = "", msg = "forbidden", returnUrl = HttpContext.Current.Request.RawUrl})' + window.location.hash;
return;
}
window.location = '#Url.Action("Index", "Error")';
}
);
on another page I'm performing an ajax call like so:
...
$.when(refreshActionLinks(row, machineId, packageId)).done(function(a1) {
row.find("span").text(opStatus).removeClass("pending");
progressbar.progressbar("destroy");
$(row).flash(bg[1], 1000);
});
...
javascript function:
function refreshActionLinks($row, machineId, packageId) {
try {
var json = JSON.stringify({ packageId: packageId, machineId: machineId, tabType: $("#TabType").val() });
console.log("refreshActionLinks => " + json);
$row.find("td.options div.actionLinks").html("<img src='#Url.Content("~/Content/images/ajax-load2.gif")' />"); // pending
return $.ajax({
url: "#Url.Action("GetActionLinks", "Packages")",
data: json,
timeout: 50000,
contentType: 'application/json',
type: 'POST',
success: function (data) {
if ($row.length) {
$row.find("td.options div.actionLinks").html(data);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
} catch(e) {
// hide icons
$row.find("a.action").remove();
}
}
The issue is that while refreshAction function is executing, clicking a menu link causes the ajax call to error out - which in this case is correct. BUT it does take me to /Index/Error page which is NOT correct. I would like "$("body").ajaxError" to handle all ajax errors on the site EXCEPT on the page I'm calling refreshActionLinks. Notice, I already have try/catch surrounding my ajax call. why doesn't that work?
thanks
figured it out:
ajax has a settings:
global: false
now my function looks like this:
function refreshActionLinks($row, machineId, packageId) {
try {
var json = JSON.stringify({ packageId: packageId, machineId: machineId, tabType: $("#TabType").val() });
console.log("refreshActionLinks => " + json);
$row.find("td.options div.actionLinks").html("<img src='#Url.Content("~/Content/images/ajax-load2.gif")' />"); // pending
return $.ajax({
url: "#Url.Action("GetActionLinks", "Packages")",
global: false, // disable error pages on failed ajax calls
data: json,
timeout: 50000,
contentType: 'application/json',
type: 'POST',
success: function (data) {
if ($row.length) {
$row.find("td.options div.actionLinks").html(data);
}
}
});
} catch(e) {
// hide icons
$row.find("a.action").remove();
}
}