Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder darksecu's Avatar
    Join Date
    Dec 2011
    Location
    India
    Posts
    146
    Thanks
    15
    Thanked 2 Times in 2 Posts

    Image Uploading With Ajax Jquery

    Iíve been looking for this for a while now but could not find any solution.

    I need to post file upload request with form via ajax jquery.

    Can someone please guide.
    When You Begin To Practice,That's The Time You Begin To Learn New Things.

  2. #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Location
    Here
    Posts
    3,934
    Thanks
    58
    Thanked 699 Times in 694 Posts
    assuming you have googled the title of your post (which brings up over 5.6 million results), what else have you tried and what is the problem you are having?

  3. #3
    Regular Coder
    Join Date
    Sep 2014
    Posts
    311
    Thanks
    1
    Thanked 55 Times in 53 Posts
    Assume:
    <input type='file' id='fileDialog' />
    2) handler = uploadhandler.php
    3) ajaxXMLHttpRequest() = a routine that determines that creates the xmlhttp object

    PHP Code:
    var fileDialog document.getElementById('fileDialog');

    fileDialog.onchange = function () {
        try {
            var 
    files = (fileDialog.files) ? fileDialog.files : [fileDialog.value];
            
    //fileDialog.parentNode.removeChild(fileDialog);
            //fileDialog = null;

            
    if (files.length 0) {
                var 
    formData = new FormData();
                
    formData.append('name''testname');      // in case you need other infos passed to handler
                
    formData.append('file'files[0], files[0].name);

                
    sendAjaxRequest(handlerformData, function (stateresponse) {
                     if (
    state) {
                       if (
    response.result != "okay") {
                        
    alert("Load of file failed: ");
                        
    response null;
                        }
                    } else {
                        
    response null;
                    }
                    
    localHandlerOfResponse(response);
                });
            }
            } catch (
    e) {
               
    console.log(e.toString());
               
    alert(e.toString());
            }
    }; 
    PHP Code:
    var sendAjaxRequest = function (handlerformDataCB) {

        var 
    xhr ajaxXMLHttpRequest();  // either window.XMLHttpRequest or window.ActiveXObject
        
    if (!xhr) {
        
    CB(false);
        }

        
    xhr.open("POST",   handler);
        
    xhr.setRequestHeader("Cache-Control""no-cache");
        
    xhr.setRequestHeader("X-Requested-With""XMLHttpRequest");
        var 
    retvalue "";

        
    xhr.onload = function () {
        switch (
    xhr.status) {
            case 
    200// ok
                
    retvalue JSON.parse(xhr.responseText);
                
    CB(trueretvalue);
                break;

             default:
                           
    // whatever -- review how to use xmlhttp
                
    break;
            }
        };
        }
     } 
    and this is your handler on the server side. eg uploadhandler.php

    PHP Code:
    <?php

    // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
    // of $_FILES.

    $uploaddir 'uploads/';
    $result 'unknown';

    $url $_SERVER['REQUEST_URI'];
    $idx strpos($url,'?');
    if (
    $idx > -1) {
        
    $url substr($url,0,$idx);
    }

    $idx strrpos($url,'/');
    if (
    $idx 0) {
        
    $idx strlen($idx);
    }
        
    $url substr($url,0,$idx);

    if (
    ob_start()) {
        echo(
    'file to upload <br />');
        
    var_dump($_POST);
        echo(
    "\n<br />File Object<br />\n");
        
    var_dump($_FILES);
        
    $dump ob_get_contents ();
        
    ob_end_clean();
    }
    else {
        
    $dump 'unknown';
    }

    $uploadfile $uploaddir basename($_FILES['file']['name']);


    if (
    move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
        
    $result 'okay';
    } else {
        
    $result 'bad';
    }

    // - send back the response
    // - return the result back as a json string

    $resp = new stdClass();
    $resp->dump $dump;                            // just a dump
    $resp->result $result;                        // the result ('okay','bad')
    $resp->target $uploadfile;                    // local target
    $resp->mimetype $_FILES['file']['type'];        // the mime type (image/*.png)'
    $resp->url $_SERVER['REQUEST_URI'];            // the full url
    $resp->fullpath $url '/' $uploadfile;        // path of the file

    header("Content-type:application/json; charset=UTF-8");
    echo(
    json_encode($resp));
    Note: FormData is not supported by IE 9 or less

    Also, I did not test the code above, but I use the same algorithm in some of my projects.

    Good luck
    Last edited by josephm; Aug 12th, 2018 at 02:59 AM. Reason: comment out removeChild


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •