Jump to content

Ajax File Upload


johnsmith153

Recommended Posts

This is my Ajax code, but how would I do it so I can upload a file via Ajax. I can do all the PHP etc. just I know there is a problem with using the code below for file upload.

 

 


   function runajax() {
      var poststr = "name=<?php echo $name; ?>&address=<?php echo $address; ?>";
      makePOSTRequest('process.php', poststr);
   }
   
   	 var http_request = false;
   function makePOSTRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Error.');
         return false;
      }
      http_request.onreadystatechange = displayresult;
  http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
   }

   function displayresult(){
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
           result = http_request.responseText;
	  document.getElementById('resultdisplay').innerHTML = result;
	      } else {
            alert('Error.');
         }
      }
   }

Link to comment
https://forums.phpfreaks.com/topic/124151-ajax-file-upload/
Share on other sites

If you do a little Googling on the topic, you will quickly discover that, due to the type of data being transfered with file uploads, it cannot be accomplished with a typical AJAX request. Therefore, the solution most typically used is to take the form values and submit them (a true submit, mind you) through a hidden iframe or something like that to keep the main page from refreshing. So, it is not truly an AJAX upload, but to the user, it is the same effect.

Link to comment
https://forums.phpfreaks.com/topic/124151-ajax-file-upload/#findComment-641978
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.