Upload local file contents without page refresh - ajax

I have a page in my web flow where I want to upload a file without refreshing the page. I tried using an Ajax call for that, but failed. I couldn't figure out how to send the data in the uploaded file to the server side/back end for further processing. I'm using the Spring MVC framework and I don't want to use PHP.
Can anyone suggest a solution or some sample code with which I can get my job done? I am very new to JavaScript.
One more thing is i have to get back to the same page after going to server side to process uploaded file and return to same page with a string from server side.all this happen without refreshing the current page
Any suggestion would be highly appreciated.

Assuming you've already gotten your form built and server-side controller set up to handle the upload, this little snippet should get you on your way to AJAX-y refresh-less file uploading glory!
//create a new FormData reference
//(note: you could use getElementById or querySelector)
var myForm = document.forms.myUploadForm;
var fd = new FormData(myForm);
//create and open an XHR
var xhr = new XMLHttpRequest();
xhr.open("POST","http://www.example.url/the/path/to/your/upload/controller");
//set up event listeners (optional)
xhr.onreadystatechange = monitorStatusFunction;
xhr.onprogress = updateProgressBarFunction;
//send the form (w/ no page refresh!)
xhr.send(fd);

I Struggled for lot many days and at last i figured out a solution which may not be the best solution but i am posting it here so that anyone like me can get help from this..
To meet all my requirements
I opened a jsp page as a popup from my jsp page and from that page i landed on my controller and done with my work on the server side and returned a string depending upon the content of the file uploaded to the same popup page and from the popup i transfered that string to my parent page.
Hence my work is done without refreshing the page...
Steps to do this
1.open a popup as follow
window.open('//url of jsp page to open','//somename','//properties of popup page');
2.land on your controller from the popup and return to the same jsp page with a string i want from the jsp page.
3.pass that string to the parent page as follow.
window.open.urparentjspfuntion(valuefromcontroller);
4.in parent page define a function to do what ever you want.....
I hope this solution may help so of those like me...

Related

Django - download file without reloading the page

The flow looks like that:
user is filling the form
form is passed to the server by ajax
form is saved to db, then the pdf with the form data is created and saved in the app folder (probably a bad move here...)
ajax success causes the page to append a button 'Download' with value equal to current pdf's name so button 'Download' appears to the user
If user presses the button the very pdf that was just saved is gonna download.
Refreshing the page makes the button disappear.
I've got stuck on point 5. I have created another ajax (to avoid reloading the page) bound to the Download button. It correctly asks the server to look for the file, creates a django File object: pdf_file = File(open(file_path, 'rb'))
and creates a HttpResponse with file, and content_type='application/pdf' or 'application/download'.
response['Content-Disposition'] is attachment.
Then the ajax returns response - only it does not. Server raises no error but ajax error function is called.
I've read that downloading with ajax is not possible. Could you help me a bit to get it straight? If above snippets are not clear, I shall provide more code.
Python 3.5, Django 1.10
Do like
window.location.href = "/url/to/downloadfile/"
in javascript after success of posting form. OR
#html
<button onclick="myfiledownload()">Download</download>
#javascript
function myfiledownload(){
window.location.href = "/url/to/downloadfile/"
}
Instead of using ajax to download the file bind the button to a download link where the file may be hosted
https://www.mywebsite/download/?fileid=3247023
You should at least seperate your file in a media root
Note: in production you will have to use a cdn to host your static files

Django AJAX Navigation

As a test i have have decided to see if i can get the hashchange navigation trick think working with my django app...
So far i have it at the stage where the hash change triggers and only needs to load the data in, this is where i have problems.
Now, I am new to django and django/ajax and i dont know where to start, did a few googles and had no luck. In a nutshell I need a way to load in the pages without the template using the extend syntax.. Would i just be able to parse an additional value to the url and exclude it from the template?? im not sure
Please give some code guidance or something
Your template creates the html that is sent to the browser, once it reaches the client your template can't make changes on that page, the page would need to be reloaded for the template to make any changes. So your options when the hash change is triggered is to either have the information you want load as part of the page but be hidden, which means you must know everything the user needs when the page loads, or use AJAX. With AJAX we can make changes without reloading the page when the user gives us new information by making a XMLHttpRequest using Javascript, which doesn't have to return XML it can be JSON or even just a singe text string. So when your hash change triggers you will be sending a request to the site, usually a GET or POST, and a script on the site will process the information sent from the client side and respond accordingly. Here is an example that would be inside the change trigger function
data = "somedata";
request = new XMLHttpRequest(); //create the request object
request.open("POST", "app/handler", false); // set its parameters
request.send("data="+data); // send it to the server
response = request.responseText; // get the response
responseHandler(response) // do something with the data the server sent back
On the server side this could be the sole purpose of the app. All the formatting can be done with the base template, javascript and css for the site. Just load the new information after each response. There are some AJAX libraries for Django, check out the wiki page or look into the django.core.serialization which will let you return your apps model as json, xml or yaml.
from django.core import serializers
def my_json_view(request):
data = serializers.serialize("json", MyModel.objects.all()[:5])
return HttpResponse(data, mimetype="application/javascript")

How to page refresh after page redirect in Jquerymobile MVC

Hi all i have create a small jquerymoblie mvc3 aplication in that i have a list-view controle when click on the link in the list-view it render to the next page, in that page i have upload some data into database using text-boxes.After updated completed i have redirect to the previous page,Now i again redirect to same page for upload some other data but the text boxes fields are not clear it shows old data how can i clear that data when i page redirect.
I am using jquerymobile mvc3(Razor) application please help me how can i solve this probles..
If you go back to the "list page" with:
$.mobile.changePage("/control/list/", { reloadPage: true });
It should reload the page from scratch with AJAX.
There are also several more options for the changePage method which you can find in the docs: http://jquerymobile.com/test/docs/api/methods.html

Handling an ASP.NET MVC FileResult returned in an (jQuery) Ajax call

Goal:
I want to let my users download a file on my webpage. I want a new window to open and the file to be either displayed or downloaded there.
My implementation:
This file however, first has to be generated on the server-side, which might take a while. When the user clicks the button to download the file, I do an ajax call and show a waiting animation until I get a response. The controller action that handles the call will generate the file (PDF) and return a FileResult. Now in the succes function of my ajax call back in javascript, I get the file data.
Problem: I have no Idea what I'm supposed to do with this data to get it to the user.
Workaround:
Right now I use a workaround where I do not return the file in the ajax call, but store it in session. In the succes function I do window.open("/controller/getPDFFromSession") which will download the file. However, I prefer not to use the session for these kind of things.
Thanks in advance.
Problem: I have no Idea what I'm supposed to do with this data to get it to the user.
You shouldn't use AJAX for downloading files for this reason. You could do the following:
The user clicks on the download button
Using javascript you show some progress image informing him that he will have to wait
Using javascript you generate and inject a hidden iframe into the DOM having its src property pointing to the controller action supposed to generate the file
Once the iframe is loaded you could hide the progress image

browser autocomplete/saved form not work in ajax request

Its really hard to search the any combination of keywords in search engine about this because it used by most popular developer wanted a custom autocomplete by ajax.
Most developer search about the custom autocomplete to get result from db by ajax or about how to disable browser autocomplete due to security reason or they wantted to use another autocomplete extender.
However I am not talking about the autocomplete. I finding about simple normal browser autocomplete or browser saved form either IE or FF that will act like dropdown recent choice during filling a text in a textbox.
It simple and normal filling a form like username and password in a login form. After the form submitted (the form data post) browser will save the autocomplete or event in FF will ask to save along with the password.
Now, think about the login submitted via ajax. The form data not automatically saved by either IE or FF simply because the form not sent by post method. I am pretty sure it is because of ajax vs post method.
CMS like DotNetNuke using this way and its really hard to me to type username and password for 5 user login for development purpose, event I want to let user save their own form data in the browser without any custom or extender. By another example, user can see and use same email to fill an any email form across web site or domain.
How to workaround with this?
Did you have suggestion what keywords is more suitable to search?
CallMeLaNN
I'm having the same problem. I was able to solve it for FireFox by adding a hidden iframe that I submit via JavaScript before doing my AJAX post. I still haven't found anything that works in Chrome/IE.
I've been faced with same issue and searched a bit. I think the solution below is the most convenient way to solve this if you have a login page. If we consider the login submitted via ajax, none of the browsers remember or offer autocomplate feature for user name and password field additionally ask to remember the credentials. But if you use the javascript submit feature (Probably it's not compatible with older versions of browsers), All of the browsers offers to save the username and password except IE. But I've found another javascript tricky for IE to make it offer to save username and password.
In my login page, I've handled the username and password and send them to serverside by ajax request and if the login is succeeded, i submitted the form by the method below otherwise It had been shown an Alert box to the user that the login was failed.
Please Check the link below:
[EDIT]: Link is broken
There is a fixed page about this issue in the page linked, i can not give you another link because of my reputation. Please search for the quotation below in the page:
Look at the fixed page.
Of course,this approach does not fit if you have a login section in the default page because of the form submitting. This causes the page flickering. I wonder if someone has an idea about it?
Here is some unobstrusive js jQuery code that will submit a form both via ajax ($.post method) to a real backend script and also to a dummy script via an iFrame, so the browser will save the submitted data for subsequent autocompletion.
This is working great under chrome. Any feedback is more than welcome!
var formframesindex = 0;
function onSubmitAjax(evt){
var $form = $(this);
var framesubmitting = $form.hasClass('framesubmitting');
var action = $form.attr('action');
var original_action = action;
if(!framesubmitting){
$.post(action,$form.serialize()+"&ajax=1", function(responseText,message,request){
formResponseHandler(responseText);
}, "json");
formframesindex++;
var formframe = $("<iframe name='formframe_id_"+(formframesindex)+"' id='formframe_id_"+(formframesindex)+"' class='formframe' src='/fakeformreceiver.php'></iframe>");
$('body').append(formframe);
var target = $form.attr('target');
$form.data('originaltarget',target);
$form.data('originalaction',original_action);
$form.attr('target','formframe_id_'+formframesindex);
$form.attr('action','/fakeformreceiver.php');
$form.addClass('framesubmitting');
$form.submit();
} else {
var current_target = $form.attr('target');
var original_action = $form.data('originalaction');
var original_target = $form.data('originaltarget');
var $frame = $('#'+current_target);
setTimeout(function(){
if($frame && $frame.length){
$frame.remove();
}
$form.attr('action',original_action);
$form.attr('target',original_target);
$form.removeClass('framesubmitting');
},100);
}
return framesubmitting;
}

Resources