Javascript code after file Download - javascript

I want to start some Javascript code after some file download from another domain.
jQuery.support.cors = true;
var formVars = $("form[name='myForm']").serialize();
var ajaxUrl = "http://some/path/openFilename.xlsx";
$.ajax({
url: ajaxUrl, type: 'GET', cache: false, data: formVars, timeout: 300000,
success: function (data) {
//Do some stuff here
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error" + thrownError);
},
complete: function (data) {
closeWaitScreen();
}
});
Often read solution is
window.location = ajaxUrl;
but this does not work for me, because it starts a new request without submitting the data from the form. (Same with window.open)
Here is my code that works without option to handle closeWaitScreen() after:
$("form[name='jasperlogin']").submit();
Of course also starts a new request when its used in the $.ajax
Any ideas how to handle it?

Related

Send ajax GET request to ASP .NET Web API

I use the following ajax script.
$.ajax({
dataType: 'json',
url: url,
data: tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
The attribute Route in Web API before method.
[Route("api/tudisp/Edit/{tuDispId}")]
public IHttpActionResult Edit(int tuDispId)
{
}
The genarated request from ajax.
http://localhost:xxxxx/api/tudisp/Edit/?179
How to force ajax to not generate sign '?' by id parameter.
The simplest way to do it is to change the url property of the Ajax options...
$.ajax({
dataType: 'json',
url: "http://localhost:xxxxx/api/tudisp/Edit/" + tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
GET parameters are automatically appended to the Url as a querystring, which is fine if that's what your application is expecting, but not when you're using routing as you are.
However, if you wanted to modify existing Ajax requests you can use prefiltering. This example modifies the Url of the ajax call, replacing {variable} with a given value from the data object...
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.data = ""; // this removes the querystring
for (key in originalOptions.data) {
options.url = options.url.replace("{" + key + "}", originalOptions.data[key]);
}
});
$.ajax({
url: "http://localhost:xxxxx/api/tudisp/Edit/{tuDispId}",
data: {
"tuDispId": 179
}
});
If you wanted to use something like that then I'd strongly recommend spending a bit of time making it more robust, but it's an example of how you could do what you want.

building wikipedia viewer with their API, always get error

I can't seem to get it working, I followed other code, and it didn't seem to get success, I then written it letter to letter, stil can't get success.
The url works great, I can put it in browser and it will show me the array which I need.
$(document).ready(function(){
$("#submitSearch").on("click", function() {
var searchInput = $("#txtName").val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + searchInput;
var wikiItemArray = [];
$.ajax({
url: url,
type: "GET",
async: false,
dataType: "json",
success: function (data) {
console.log(data);
},
error: function(error){
console.log("There was an error somewhere in &.ajax: " + url);
}
});
});
});
Change the dataType from "json" to "jsonp".
That api is not CORS enabled but does serve jsonp

JSONP Ajax calls not working parallel

I have Node.js server and jQuery ajax requests.
This works:
api(config.categoriesURL, success, config.err1);
setTimeout(function () {
api(config.randomURL, success1, config.err2);
},300);
But this doesn't:
api(config.categoriesURL, success, config.err1);
api(config.randomURL, success1, config.err2);
Here is the console output:
url: http://localhost:3000/categories/?callback=myCallback&_=1431726147454
url: http://localhost:3000/random/?callback=myCallback&category=55564cc42e366b34aa9a529d&callback=myCallback&_=1431726147455
responseText: undefined
status: 200
text status: parsererror
error: Error: myCallback was not called'
Is this server-side or client-side problem? Any idea why this is happening and how I should solve it? Is this normal behaviour?
Here is more code:
main.js
$(document).ready(function() {
var api = require('./api'),
config = require('./config');
function success (data) {
data.forEach(function (category) {
var div = document.createElement('div');
div.id = category._id;
div.textContent = category.name;
$('.container').append(div);
});
}
function success2 (data) {
console.log(data);
}
api(config.categoriesURL, success, config.err1);
api(config.randomURL, success2, config.err2);
});
api.js
function api(url, success, error) {
$.ajax({
type: 'GET',
url: url,
beforeSend: function (jqXHR, settings) {
console.log('url: ' + settings.url);
},
jsonpCallback: 'myCallback',
dataType: 'jsonp',
success: success,
error: error
});
}
module.exports = api;
You should try removing:
jsonpCallback: 'myCallback',
You are making two simultaneous JSONP ajax calls that use the same name for the callback function. I would think that would be a problem.
If you remove the jsonpCallback setting, jQuery will randomly generate the name of the callback function.

Retrieving data using ODATA with javascript

I'm trying to return a result set from crm using odata. i'm new to this.. i want to have an asp.net page displaying the values in a datagrid. i'm getting the error odata execution error popup. if i put in the correct server and query string it always fails though.. any suggestions on how to get this work properly
function ExecuteQuery(ODataQuery) {
//var serverUrl = Xrm.Page.context.getServerUrl();
var serverUrl = "https://server.server.com"; //would be the real server
// Adjust URL for differences between on premise and online
// if (serverUrl.match(/\/$/)) {
// serverUrl = serverUrl.substring(0, serverUrl.length - 1);
// }
alert("test");
var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataURL,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
//
// Handle result from successful execution
alert("success");
//data.d.results
},
error: function (XmlHttpRequest, textStatus, errorObject) {
//
// Handle result from unsuccessful execution
//
alert("OData Execution Error Occurred");
}
});
}
<script type="text/javascript">
ExecuteQuery("the query would go in here);
</script>

Reusable JS ajax pattern (jquery)

I'd like to know if there is a better approach to creating re-usable ajax object for jquery.
This is my un-tested code.
var sender = {
function ajax(url, type, dataType, callback) {
$.ajax({
url: url,
type: type,
dataType: dataType,
beforeSend: function() {
onStartAjax();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
callback.failure(XMLHttpRequest, textStatus, errorThrown);
},
success: function(data, textStatus) {
callback.success(data, textStatus);
},
complete: function (XMLHttpRequest, textStatus) {
onEndAjax();
}
});
},
function onStartAjax() {
// show loader
},
function onEndAjax() {
// hide loader
}
};
<script type="text/javascript">
var callback = {
success: function(data, textStatus) {
$('#content').html(data);
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error making AJAX call: ' + XMLHttpRequest.statusText + ' (' + XMLHttpRequest.status + ')');
}
}
sender.ajax(url, type, dataType, callback);
</script>
You can set the basic options that you always have the same separately.
for instance if you always use the same thing here:
type: type,
dataType: dataType,
for those types, you can set them separately.
Here is how you do that type of thing:
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}"
});
NOW those are set and you can simplify your individual ajax calls.
EDIT:
NOTE: Setting parameters to $.ajax override these defaults. Thus presetting “data” to an empty JSON string is safe and desired. This way, any $.ajax call that does specify a data parameter will function as expected, since the default will not be used. This helps avoid issues that can be difficult to find on a deployed site.
Here is what I did:
var ajaxclient = (function (window) {
function _do(type, url)
{
return $.ajax({
url:url,
type:type,
dataType:'json',
beforeSend: _onStartAjax
}).always(_onEndAjax);
}
function _onStartAjax()
{
console.log("starting ajax call");
}
function _onEndAjax()
{
console.log("finished ajax call");
}
return {
do:_do
}
}(this));
Example usage:
ajaxclient.do("get","http://...").done(function(data) {console.log(data);})
I'd probably go the whole hog and have an Ajax Object create.
var ajax = new MySuperAjax(url, data);
ajax.onComplete = function(){}
or similar. You seem to have a halfway between a function which has some defaults it extends with those you apss in and an object for it.

Categories