uploading files using jQuery and ajax gives error [duplicate] - javascript

I would like to know if it is possible to upload a binary file via ajax and php, and have a link to download it. I would like to avoid refreshing the entire page, as with a standard html form. So far I have been using forms to get information, such as radio and text boxes, and using javascript to override the default behavior. Is a similar thing possible for uploading a file?

It isn't possible to submit a file through Javascript.
Your options are:
The hidden iframe trick, popularized by Google. Implementing this yourself can result in some klunky stuff so there are libraries out there, such as jQuery, which have plugins, such as jQuery's popular Form Plugin, that automate this so you don't have to feel dirty inside when using it.
Using Flash to faciliate the process. Most notably SWFUpload is very popular. All things being equal, I'd probably go with the Javascript solution over this, but I've used this in the past with success. The cool thing about this solution is that it comes with a nicer interface such as loading indicators and thumbnails and such. At this point, though, you're asking for a user to have Flash + Javascript available, which may not work in some situations.
Using Silverlight instead of Flash, although I wouldn't really consider this as a viable solution, as it has a much lower penetration rate than the other two solutions.

While you can't upload a file via AJAX, you can put a file control in a popup and then update the page that spawned the popup when it closes.
I'm not too clear on how to update the page that spawned the popup, but I've seen it done in the ANGEL Learning Management Suite.

Have an IFrame (display:none) on your form and set your form's target to be that iframe.
My form looks like this:
<iframe id="upload_target" name="upload_target" src="" style="width:0px;height:0px;border:0px solid #fff;"></iframe>
<form enctype="multipart/form-data" name="frmXMLUpload" target="upload_target" action="scripts/uploadXML.php" method="POST" onSubmit="return checkExtension(fXMLFile.value, 'xml')">
<!--only allow up to 30k of data to be uploaded-->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input name="fXMLFile" id="fXMLFile" type="file" accept="text/xml" size="50" />
<p><input type="submit" value="Upload" /></p>
</form>
And deal with response in yuor IFRAME. basically this is not AJAX at all, but who would like JavaScript to have access to files on your local computer? It's fine the way it is.

It is not generally possible to do this in AJAX / Javascript alone.
Take a look at:
http://www.codeplex.com/SLFileUpload/
for a way to do it inside a silverlight application.
or:
http://www.element-it.com/Examples/MultiPowUpload/SimpleUpload.html
in flash.

As John Gietzen said, you can't do this directly through AJAX (ie send the actual data through AJAX). What you could do though, ispost your form to an invisible iframe, then use AJAX to ask the server for the URL. That would retain the basic user experience - not refreshing the page.

Have you considered jquery? There are nice plugins to do this gracefully.
Like this one for example: http://www.phpletter.com/Our-Projects/AjaxFileUpload/

Take a look at this example, I the plugin a little better than the one at phpLetter, though the phpLetter might have better examples for the PHP side of things.
http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Examples

You might also want to have a look at SwfUploader , which does file uploads using Flash, showing a progress bar, and without needing for the page to be refresh. Demonstrations can be seen here.

Related

Bookmarklet that uses current url in post request

Sorry if my question displays a lack of fundamental Javascripting knowledge as I have next to none.
I Frankensteined together the following bookmarklet during hours of obsessive Googling for a way to do what I want to do:
javascript:'<body onload="document.forms[0].submit()"><form method="post" action="https://generic.web.proxy/request.php?do=go"><input type="text" name="get" value=???></form>'
(Mostly based on this.)
Basically, it mostly does what it should: performing a post request on that web proxy's page with whatever string is used for value. The problem is what I want to use for value, namely the URL of the current Firefox tab. In other bookmarklet examples I've seen this seems to be accomplished with location.href, but if I do it like this
value=location.href
it simply assumes that it's the string "location.href". I assume that's because I'm stupidly trying to directly use a Javascript thingie in the html part of the script, but what is the alternative?
Oh boy, I think I just figured it out. Since the javascript treats the html like any other string, I can simply use normal string manipulation on it:
'<beginningofhtml'+location.href+'endofhtml>'
Applied to my bookmarklet:
javascript:'<body onload="document.forms[0].submit()"><form method="post" action="https://generic.web.proxy/request.php?do=go"><input type="text" name="get" value='+location.href+'></form>'
And it works!
(the fake example web proxy url still needs to be replaced with the correct one of corse; it works with a site called Proxfree)

Writing the full path of the file when it is browsed using php

So far I wrote a script so that I can browse for a file and see the printed name of the file. Here is the script:
<form action="upload.php" method="post" enctype="multipart/form- data">
Select:
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
When I hit the browse button and choose a file, only the name of the file gets printed on my web page (My web-browser is Firefox and I am using a local server). Is there a way to print the whole address of the file? What I have found on the web so far were mostly suggesting ways when we know in advance "/path/to/file". But how can it be done if I randomly choose a file? If there is no way to do it with PHP because of security issues according to:
How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?,
Is it possible t do it with C, C++, html, etc?
I really need to show the local path of the directory. What are the alternatives? The answer is it can't be done? I found this website http://www.htaccesstools.com/articles/full-path-to-file-using-php/
Don't know how it works though.
The other alternative would be to define a fixed path and let the user only choose that directory and since it is known I can print it out. Does it make sense?
Older browsers used to allow unrestricted access to the full path, so it's not impossible, but due to security concerns, your best answer will be a workaround.
Internet Explorer
HTA Application
If you're working locally, one option is that you can run your page as an HTML Application. Sadly this uses Internet Explorer as the engine. But if you can get away with an HTA, this does what you want:
<!--test.hta-->
<HTML>
<HEAD>
<HTA:APPLICATION ID="testFile" BORDER="thick" BORDERSTYLE="complex"/>
<TITLE>HTA - Test file</TITLE>
</HEAD>
<BODY>
<input type="file" onchange="alert(this.value)">
</BODY>
</HTML>
Trusted Site
A much better option, is simply to use Internet Explorer and then add your page to Internet Explorer's trusted sites. Then your solution is as simply as:
<input type="file" id="fileUpload" onchange="alert(this.value)">
Here's how to add a site to your trusted sites:
Custom Security Level
You can also enable this behavior globally for Internet Explorer:
Firefox
Firefox does not appear to have support for grabbing the full URL. But as mentioned here there does seem to exist a "mozFullPath" property:
https://developer.mozilla.org/en-US/docs/Web/API/File/mozFullPath
I tried it in my browser and it seems to be a non-existent property. I cannot find any documentation anywhere regarding how to take advantage of this property. But it's a property to keep an eye out for in case it ever becomes useful.
HTML5
In HTML5, you can write this.files[0] to refer to the File object. Properties include "name" and "lastModifiedDate", "size", and "type" as mentioned here:
https://developer.mozilla.org/en-US/docs/Web/API/File
In HTML5 you can actually work with blobs and create an object url from the selected file and show a preview. This can be done with URL.createObjectURL(...) then creating an image and settings its src to the resulting temporary url. See this fiddle.(credit goes to this post)
Finally, you might greatly enjoy:
https://blueimp.github.io/jQuery-File-Upload/
There is no way to do it, as the display is controlled by browsers. Some browsers will display the whole path while others will only display the name of the file.
You can do this because of security reasons. Javascript don't have permission to acces to the File System, look at this answer: How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?
I did hit the same issue but not in the same circumstances. Only IE10 gave me the full path while firefox (and probably all others) doesn't. In my case, i use a server with php, so i ask the user to select the file and i upload it on the server to use it how i need. I hope it helped.
This seems you wanting full path of your file.
Kindly try to use :__FILE__
Using JavaScript and a hidden field you can do this:
$('#someHiddenField').val( $('#myFileField').val() );
but keep in mind that not all browsers return the full path (specifically FF only returns the file name).
Getting full path of client-side file to serverside is something exposing file system access of client-side. This is not allowed because there are several security reasons.
You need to change the settings of your browser and then you can access the relative path of your file.
Chrome you will get real path using this.files[0].webkitRelativePath
FirFox you will get using this.files[0].mozFullPath

Is it possible to create a searchbox for my site using javascript?

I'd like to create a search box on the home page of my site that would be able to search the entire site. I know it's a very general question but I'd be very happy with just a general conceptual answer is there anyway to do this?
You can't really do this using Javascript. You'll have to use some sort of server-side language that has access to your database. Alternately, you can use something like Google Custom Search Engine to provide searching capabilities.
Once you start wanting users to be able to search your site, it implies that your site is larger than just a few simple HTML pages. Have you thought about using something like Drupal, Joomla!, Wikimedia, or some other CMS? Most of those have search capability built in (one way or another).
People are going to tell you no. They're mostly right that his probably isn't the best way to do this.
But depending on your site, it may be technically incorrect to say this can't be done with JavaScript. If all the documents you want to be searchable have a unique URL that's used throughout the site, and if their graph is connected, I think you could write a spider in JavaScript that begins indexing all these pages as soon as a user hits your site. It'd do what any other spider did: look for links on the current page, request the documents behind them (using XMLHTTPRequest or a frame or popup window of some kind), process the document and index keywords based on some scheme, and store the results (possibly in a a cookie).
Of course, duplicating all this work for each visitor doesn't make a lot of sense, which is why the other people telling you no are mostly right. But it's theoretically possible.
This is would involve much more than just Javascript and depends on a number of different variables. Often, sites are built on a MySQL (or similar) database. If this is true in your case you may want to use some PHP to get into it and search through each record. Here's an example using PHP and MySQL.
For the form, something like this will work:
HTML
<form action="?" method="get">
<input type="text" id="search" name="search" />
<input type="submit" name="submit" id="submit" value="Search" />
</form>
Then you'll need to use some PHP, assuming you want to search the title and body of one table of blog posts:
$search_terms = mysql_real_escape_string($_GET['search']);
$resc = mysql_query("SELECT * FROM blog_posts WHERE title LIKE '%".$search_terms."%' OR body LIKE '%".$search_terms."%'");
$posts = mysql_fetch_assoc($resc);
now $posts is an array containing all of your posts which match the search terms in their title or body.
NOTE: In order to search for text type MySQL fields you will need to make the field a FULLTEXT index.
Check this link out for more info: http://devzone.zend.com/article/1304
This is a VERY SIMPLE solution, but it will get you on the right track.

Upload a file into SharePoint using FORM POST

I would like to upload a file into share point using FORM POST. I am trying in this way
<FORM NAME="oForm" id="oForm" ACTION="<site>/_layouts/Upload.aspx?List={A4793E2B-3081-4668-B6F1-0A013159F9B1}&RootFolder=/sites/servdeldocmgr/Test SOAP2" ENCTYPE="multipart/form-data" METHOD="POST">
<input type="file" name="file1" id="file1" />
</FORM>
In onclick of a button I am doing form post. But It's not uploading. I found .net based solutions but my case is only with javascript and html.
The best is to rely on SharePoint API, populate the item (e.g SPList) and upload the file. I will provide some sample code later as I can't recall the exact function.
EDIT:
http://msdn.microsoft.com/en-us/library/dd587349(office.11).aspx has some good code snippets to get you started.
I am able to add attachment to list item. I put my experience here. Instead of uploading to upload.aspx, I achieved differently. I am able to achieve without .net, I found many .net solutions but again it will be one more programming language in application stack so I didn't use it.
http://myveda-yvb.blogspot.com/2010/01/my-learnings-sharepoint-web-services.html

how AJAX application should behave when Javascript is disabled - common practice?

I’m in the process of developing pretty basic web application, that is mostly so I could learn jQuery/ajax/php on the way (and have some fun). I want to make it as accessible to users as possible so it should work with Javascript disabled, validate to AAA and all that. With JS disabled would be of course without all the bells and whistles, but nevertheless should do the job.
I would like to make good use of Ajax, but I don’t fully understand how should I cope when JS is off.
So let’s say JS is on, user submits the form, clicks submit button and thru ajax, data is submitted to register.php (register.php is specified in forms action attribute). register.php returns data and jQuery displays appropriate message. All without reloading the page.
Now, if JS is disabled, submitting form to register.php won’t do much good.
The way I understand it, solution would be to create one php script for JS enabled, other for JS disabled. So by default form would have action attribute with nonjs_register.php, and if JS would be enabled, it would force the form to be submitted to js_register.php rather than default nonjs_register.php.
I can imagine that would be quite tedious to create two scripts pages for each user interaction with the application but that’s the only way I can think of at the moment.
I hope all that makes sense but please let me know if my explanation is not quite clear.
Now if anyone could explain to me what is the common practice to deal with that kind of problem that would be great.
Take a look at the Hijax technique, it's a way of using AJAX as a progressive enhancement.
The way I would deal with this sort of thing is to use an event with javascript that cancels the default action of the form. The default action of the form is to submit to a different url:
html
<form id="AjaxForm" action="/nonJS_register.php" method="POST">
<!-- form input elements -->
</form>
js
document.getElementById("AjaxForm").onsubmit = function ()
{
//- do ajax posting...
ajaxPostForm();
//- Cancel the default action of the form
event.preventDefault();
return false;
}
The ajax function could submit to nonJS_register or you could even just add a parameter that tells the script to return the data in a different format and not encapsulated by HTML.
the recipe is very basic:
always pull everything on the page
before JS is even called.
then change everything via JS - e.g. hide
elements as required etc.
AJAX needs to hook up on the events and cancel
the original events (e.g. clicking
the link will get you to another
HTML/PHP generated page without JS
available, but with JS available you
can change targets to pull AJAX only
and return false, so click won't
actually change the page)
The best thing I could suggest would be to build it how you would want it to work without the AJAX calls. That way you can get an accurate portrayal of how it will work with JavaScript disabled. Then start to work in your JavaScript and continue to test with/without JavaScript enabled.
If you use AJAX to implement some ESSENTIAL part of a page, then the whole page will have to require Javascript.
This is a thing you have to point out BEFORE you start implementing it.
If you want to make Javascript optional, then you can't use AJAX to implement all the communication. You'll have to use postbacks, and eventually override the "click" events of buttons to make the postback asynchronous (a.k.a. with AJAX).
So, I would suggest you to write the page as if you don't have Javascript, then override some functionalities later on if Javascript is enabled.
One solution would be to have your register.php file recognize the HTTP header: Accept in requests it receives and it would respond one of several ways:
If the incoming request has
Accept: application/xhtml+xml, text/html, multipart/mixed, */*
Then return an HTML page as a response.
Or if it's something else, such as
Accept: application/json, application/javascript, text/javascript
It would return JSON (in this case), or XML if it had the appropriate mime types listed for example.
Then in your Javascript code, you'd handle the onsubmit event and override the normal behavior to perform what you suggest in your question (but also changing the Accept header, like above). If javascript is disabled, the form will submit normally and will pass along a header that should trigger your PHP to return a web page.

Categories