I've got the following ajax call:
var blind = Ext.create('MyApp.view.blind.Progress', {});
blind.show();
Ext.Ajax.request({
url: config.url,
params: {
nodeId: config.data[0].value,
fileName: config.data[1].value,
startDateTime: config.data[2].value,
endDateTime: config.data[3].value,
reportFormat: config.data[4].value
},
success: function (response) {
console.log(response);
blind.close();
}
});
I want to display a blind with a loading graphic, and close it upon completion. Is there any way to use this ajax callback to download the file from the response? Am I on the right track? I would like to avoid using iframes or opening new tabs if possible. I'm open to using other libraries like jquery if it's easier.
Don't think its possible to respond with a file to an ajax request. a simple form submit should do the trick.
Well I don't like being told what I can't do so I kept researching and found this jquery plugin. It works by polling a cookie made by the server when the file is delivered, and the typical iframe method for downloading files. No bloat, no flash, exactly what I was looking for:
Jquery File Download
Download the plugin, link it somewhere in your site, and add this cookie generation code to wherever your file request is going (there are more examples at the link, I'm using ASP.NET):
HttpContext.Current.Response.SetCookie(new HttpCookie("fileDownload", "true") { Path = "/" });
Sample code from my app, using the success and fail callbacks of the plugin to control my extjs blind:
$.fileDownload(config.url, {
successCallback: function (url) {
//Show a message here or perform some task
blind.close();
},
failCallback: function (html, url) {
blind.close();
alert("The report generation failed.");
},
httpMethod: "POST",
data: {
nodeId: config.data[0].value,
fileName: config.data[1].value,
startDateTime: config.data[2].value,
endDateTime: config.data[3].value,
reportFormat: config.data[4].value
}
});
Related
I'm using Google App Engine for a backend service and I'm trying to upload a file using an AJAX post and their Blobstore API. I got that part working. If you are not familiar with the service, is quite simple. Blobstore API uploads is a two step process: You need to get an upload url and then upload into that url.
Now, I'm implementing an editor, medium.com-like.
The thing is this plugin needs an endpoint for the upload. As my endpoint is not static and I need to update that URL each time, I have prepared an API in the backend that responds with a JSON file with that URL. I'm trying to do an AJAX request to get that URL but I'm getting an error, as the POST request is done to bad url.
This is the POST requet:
INFO 2014-10-19 08:58:22,355 module.py:659] default: "POST /admin/%5Bobject%20Object%5D HTTP/1.1" 200 2594
An this is my Javascript code:
function getURL(callback) {
return $.ajax({
type: "GET",
url: "/admin/upload_url",
dataType: "json",
success: callback
});
};
$('.editable').mediumInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: getURL().done(function(json){return json['url']})
},
embeds: {
oembedProxy: 'http://medium.iframe.ly/api/oembed?iframe=1'
}
}
});
I guess I'm doing something wrong with the AJAX return, but if I console.log it I get the result I want. I've read this answer and try to apply it, but I didn't manage to get it working.
Thanks for your time and your help ! :)
If someone ever has the same problem this is the way I solved it. If you are reading this and you now a better one, please, every help is appreciated.
var url; // Set a global variable
// Define the AJAX call
function AJAXURL() {
return $.ajax({
type: "GET",
url: "/admin/upload_url",
success: function(response){
// Sets the global variable
url = response['url'];
}
});
};
// Gets a first upload URL doing an AJAX call while everything keeps loading
AJAXURL();
$('#editable').mediumInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: function getURL() {
// makes a request to grab new url
AJAXURL();
// But returns the old url in the meanwhile
return url;
}
},
embeds: {
urlPlaceholder: 'YouTube or Vimeo Link to video',
oembedProxy: 'http://medium.iframe.ly/api/oembed?iframe=1'
}
}
});
I'm writing a small ASP.NET MVC site which also includes a WEB API in it that I wrote.
I've configured the project on my local IIS as http://localhost/mysite
On the main page of my site I'm including a js script that I wrote:
<script src="#Url.Content("~/Content/js/home.js")"></script>
on the page ready event of that js I call:
$.ajax({
url: 'api/getdetails',
accepts: 'application/json',
cache: false,
type: 'GET',
success: function (data) {
alert(data);
}
});
when looking with Fidler I see that the page call returns a 404 since it doesn't try to load it to the relative path I'm in (http://localhost/mysite) and it tries to load the root of the server - so the call looks like this http://localhost:80/api/getdetails
when I was writing web forms I used to do ajax calls such as this all the time and it always worked.
what am I missing?
Thanks
What I ended up doing is in my layout html I've added a js var:
var baseUrl = '#Url.Content("~/")';
then on my ajax call I've added that base url:
$.ajax({
url: baseUrl + 'api/getdetails',
accepts: 'application/json',
cache: false,
type: 'GET',
success: function (data) {
alert(data);
}
});
this does the trick no matter how the page looks like. even if I navigate to http://localhost/mysite/home/index
It's probably not the perfect solution, and I definitely think the old webforms way which worked was better - but I guess there are pros and cons to any technology.
Still would be happy to hear if someone has a better solution. for now - this does the trick.
When you navigate to
http://localhost/mysite
The behavior is a little different from
http://localhost/mysite/
Try that to confirm. Without the trailing slash, the "mysite" looks like a document name, not a folder, so relative paths would form from the root of the server.
What you may need to do is pass in the site content URL into your home.js and form absolute paths from it in your code.
Very new to code in general so apologies in advance if i dont explain myself properly,
But I have a form, that actions a piece of JavaScript on submit.
If the form validates successfully then it calls a php file for server side processing.
Once the server side processing is complete the php file returns some data (a url) which the user is then redirected to (client side)
This all works fine on desktop (chrome, IE, FF) and via modern mobile devices, however the redirect is not working on some devices (blackberry for one), and a i assume other older devices. Instead of the redirect URL going straight into the address bar, it is being placed after the url of the original page - as such causing the user to be redirected to a page that of course doesnt exist.
Below is the script that is called on submit. Again apologies if none of the above makes sense...I am very new to all this:
$(function () {
$('#wait').hide();
$('form#leads_form').on('submit', function (e) {
if (validateFrm()) {
$(":submit", this).attr("disabled", true);
$('#wait').show();
var jqxhr = $.ajax({
type: 'post',
timeout: 300000,
url: 'sell-save-leads.php',
cache: false,
data: $('form').serialize(),
success: function (data) {
//alert("Submit success: " + data);
window.top.location.href = data;
}
});
} else {
//alert("validation errors");
$('#wait').hide();
}
e.preventDefault();
});
});
If anyone is able to help or offer some advice that would be great.
As your form is located in an iFrame I suggest you to use this jQuery plugin to send messages from an iframe to its parent:
http://benalman.com/projects/jquery-postmessage-plugin/
With this you could send a message from inside your success function, containing the new url, and catch it in the parent window.
You can also use
window.top.location.assign(data);
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window.location
I'm using Laravel 3, and I am AJAXing in a user comment. We are adding images to this comment and I can't seem to get the File Data to go through. When I set processData to false, I am also unable to access the other data such as the comment and privacy. Any insight?
var commentforms = $('form.compose');
commentforms.on('submit', function(e){
e.preventDefault();
var file = document.getElementById('file_input').files[0];
$.ajax({
type: 'POST',
url: '/issue/comment/' + issue_id,
processData: false,
data: {
side: side,
comment: comment,
privacy: privacy,
file: file,
},
success: function(response){
console.log(response);
new_comment = comment_template(response);
updateSide(new_comment);
},
});
Going off of what Kevin B commented, there are a couple ways to do this.
First, the reason it is not working is that, by default, you cannot send files with an AJAX request. That is it, and that is why it isn't working. No matter what you do to your form and your AJAX request, you are stuck. (AJAX here meaning NOT XMLHttpRequest2)
SOLUTION 1
Kevin B recommended the Javascript formData object which is part of the XMLHttpRequest Level 2. Information on how to use it can be found: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
In relation to your code, you code do something along the lines of:
commentforms.on('submit', function(e){
e.preventDefault();
var oData = new FormData(document.forms.namedItem("composeForm"));
var oReq = new XMLHttpRequest();
oReq.open("POST", '/issue/comment/' + issue_id, true);
//on a side note, issue_id isn't declared anywhere...
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
console.log("Uploaded!");
} else {
console.log("Error " + oReq.status + " occurred uploading your file.");
}
};
oReq.send(oData);
});
PROBLEM
Again, as Kevin B said, it isn't widely supported. Checking here: http://caniuse.com/xhr2 you can see that IE9 and below isn't supported, which is XP, Vista, and non-upgraded Windows 7. If your app is on your own controlled network, and you can ensure everyone is using Firefox/Chrome/IE10+, you are good to go. If you are going to be using this feature with the public, then you need another solution.
OTHER SOLUTIONS
Many sites currently use AJAX to upload files, or trick you into thinking it is AJAX. What other websites do is one of two things: hidden iFrames or Flash.
The hidden iFrame trick is to create an iframe that populates the data of your current form, and then sends it off like it normally would, meaning a page reload. Because it is in an iFrame and hidden, the user never sees the page reload and the content is uploaded like you would expect.
The Flash trick is to use a little Flash app/plugin that finds the file and then sends it to your server. It is fairly easy to use, and since Flash is widely supported, it can do the trick on most browsers. You just have to include the plugin and you are good to go.
Plugins
I prefer to use plugins, as they do all the hard work for me. The one I am fond of right now for it's simplicity is Fine Uploader. It is easy to configure, looks great, can be Bootstrapped, or used with jQuery. Plugins may use one or both methods to upload the files, or they may even try the XMLHttpRequest2 first, then fall back on one of the other methods to upload the files. Ultimately, most of the popular plugins are easy to configure and provide fairly decent documentation to get it to do what you want.
Other popular plugins:
Uploadify
BlueImp
Plupload
read this:
With XHR2, File upload through AJAX is supported. E.g. through
FormData object, but unfortunately it is not supported by all/old
browsers.
Try with this:
Tutorial
And see this code:
var data= new FormData();
data.append( 'file', $('#file') );
$.ajax({
url: 'file.php',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(response){
console.log(response);
}
});
Suerte!
I am doing application in Extjs, i am calling Ext.data.JsonP.request. In below code url path will come dynamically generate by appending name to base url of pdf. But Here i am hard coded. I am passing this url and testing jsonp request. if this url returns success i can write code success logic else failure, but here always going to failure method. also i have tried Ajax.request but no use. Some time i will get pdf path but that pdf is not in server that time i need showcase alert message like pdf is not found. Can tell me how can achieve this one? is it possible by calling jsonp request or any other method? Thank you
here is my code:
Ext.data.JsonP.request({
url: 'http://jmlr.csail.mit.edu/papers/volume10/mannor09a/mannor09a.pdf',
method: 'GET',
params: {
//fileID: feed_id, //this.form.getComponent('file').value,
},
failure: function () {
alert('failed !');
},
success: function () {
alert('success!');
}
});
Are you sure, that you need ajax to get pdf file? If you want to display this file to user, you can just put direct link to this file (without ajax or other tricks) and browser will show it.
Hard to understand, what do you want to get in the success function.
My recommendation to use plain link (you still can generate it dynamically to user)
Link
against using JSONP in this situation :)