Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. JavaScript
  4. Uploading image using JQuery AJAX

Uploading image using JQuery AJAX

Scheduled Pinned Locked Moved JavaScript
javascriptphptools
8 Posts 3 Posters 10 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Alex Dunlop
    wrote on last edited by
    #1

    Hi, I want to upload an image file using JQuery AJAX and send it to php code for further processing including image cropping. I tried this code for Js:

    $(document).ready(function() {
    $('#uploadstatus1').hide();
    $('#uploadstatus2').hide();

        $('#btnupload').click(function() {
            var file = $('#formFile')\[0\].files\[0\];
            var filename = file.name;
            var filedata = $('#formFile').prop('files')\[0\];
            var formdata = new FormData();
            formdata.append("file", filedata);
            formdata.append("filename", filename);
            $.ajax({
                url: "../app/model/saveimage.php",
                type: "POST",
                dataType: 'script',
                cache: false,
                processData: false,
                data: formdata,
    
                success: function(data2) {
                    if (data2 == 1) {
                        location.reload();
                    } else {
                        alert(data2);
                        $('#uploadstatus1').show();
                    }
                }
            });
        });
    });
    

    Uploading modal:

    Upload image

    Upload file:

                                Only Jpeg files are supported.
                                
                            
    
                        
    
                        
    
                            Upload failed!
    
    Richard DeemingR J 2 Replies Last reply
    0
    • A Alex Dunlop

      Hi, I want to upload an image file using JQuery AJAX and send it to php code for further processing including image cropping. I tried this code for Js:

      $(document).ready(function() {
      $('#uploadstatus1').hide();
      $('#uploadstatus2').hide();

          $('#btnupload').click(function() {
              var file = $('#formFile')\[0\].files\[0\];
              var filename = file.name;
              var filedata = $('#formFile').prop('files')\[0\];
              var formdata = new FormData();
              formdata.append("file", filedata);
              formdata.append("filename", filename);
              $.ajax({
                  url: "../app/model/saveimage.php",
                  type: "POST",
                  dataType: 'script',
                  cache: false,
                  processData: false,
                  data: formdata,
      
                  success: function(data2) {
                      if (data2 == 1) {
                          location.reload();
                      } else {
                          alert(data2);
                          $('#uploadstatus1').show();
                      }
                  }
              });
          });
      });
      

      Uploading modal:

      Upload image

      Upload file:

                                  Only Jpeg files are supported.
                                  
                              
      
                          
      
                          
      
                              Upload failed!
      
      Richard DeemingR Offline
      Richard DeemingR Offline
      Richard Deeming
      wrote on last edited by
      #2

      Alex Dunlop wrote:

      var file = $('#formFile')[0].files[0];
      var filedata = $('#formFile').prop('files')[0];

      Why are you accessing the file twice, using two slightly different syntaxes? Just use:

      const file = document.getElementById("formFile").files[0];
      const formdata = new FormData();
      formdata.append("file", file);

      $.ajax({
      url: "../app/model/saveimage.php",
      type: "POST",
      processData: false,
      contentType: false,
      data: formdata,
      success: function(data2) {
      ...
      }
      });


      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

      A 1 Reply Last reply
      0
      • Richard DeemingR Richard Deeming

        Alex Dunlop wrote:

        var file = $('#formFile')[0].files[0];
        var filedata = $('#formFile').prop('files')[0];

        Why are you accessing the file twice, using two slightly different syntaxes? Just use:

        const file = document.getElementById("formFile").files[0];
        const formdata = new FormData();
        formdata.append("file", file);

        $.ajax({
        url: "../app/model/saveimage.php",
        type: "POST",
        processData: false,
        contentType: false,
        data: formdata,
        success: function(data2) {
        ...
        }
        });


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        A Offline
        A Offline
        Alex Dunlop
        wrote on last edited by
        #3

        I applied those changes:

        $(document).ready(function() {
            $('#uploadstatus1').hide();
            $('#uploadstatus2').hide();
        
            $('#btnupload').click(function() {
                const file = document.getElementById("formFile").files\[0\];
                const formdata = new FormData();
                formdata.append("file", file);
        
                $.ajax({
                    url: "../app/model/saveimage.php",
                    type: "POST",
                    processData: false,
                    contentType: false,
                    data: formdata,
        
                    success: function(data2) {
                        if (data2 == 1) {
                            location.reload();
                        } else {
                            alert(data2);
                            $('#uploadstatus1').show();
                        }
                    }
                });
            });
        });
        

        it still returns false for if (isset($_POST['file']))

        Richard DeemingR 1 Reply Last reply
        0
        • A Alex Dunlop

          I applied those changes:

          $(document).ready(function() {
              $('#uploadstatus1').hide();
              $('#uploadstatus2').hide();
          
              $('#btnupload').click(function() {
                  const file = document.getElementById("formFile").files\[0\];
                  const formdata = new FormData();
                  formdata.append("file", file);
          
                  $.ajax({
                      url: "../app/model/saveimage.php",
                      type: "POST",
                      processData: false,
                      contentType: false,
                      data: formdata,
          
                      success: function(data2) {
                          if (data2 == 1) {
                              location.reload();
                          } else {
                              alert(data2);
                              $('#uploadstatus1').show();
                          }
                      }
                  });
              });
          });
          

          it still returns false for if (isset($_POST['file']))

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #4

          Try replacing:

          if (isset($_POST['file'])) {

          with:

          if (isset($_FILES['file'])) {


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          A 1 Reply Last reply
          0
          • Richard DeemingR Richard Deeming

            Try replacing:

            if (isset($_POST['file'])) {

            with:

            if (isset($_FILES['file'])) {


            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

            A Offline
            A Offline
            Alex Dunlop
            wrote on last edited by
            #5

            Thank you. I have an another problem. When I access a php file through javascript, paths cause error. For example require "../app/core/database.php"; gives error and says: No such file or directory. How can I fix this issue?

            1 Reply Last reply
            0
            • A Alex Dunlop

              Hi, I want to upload an image file using JQuery AJAX and send it to php code for further processing including image cropping. I tried this code for Js:

              $(document).ready(function() {
              $('#uploadstatus1').hide();
              $('#uploadstatus2').hide();

                  $('#btnupload').click(function() {
                      var file = $('#formFile')\[0\].files\[0\];
                      var filename = file.name;
                      var filedata = $('#formFile').prop('files')\[0\];
                      var formdata = new FormData();
                      formdata.append("file", filedata);
                      formdata.append("filename", filename);
                      $.ajax({
                          url: "../app/model/saveimage.php",
                          type: "POST",
                          dataType: 'script',
                          cache: false,
                          processData: false,
                          data: formdata,
              
                          success: function(data2) {
                              if (data2 == 1) {
                                  location.reload();
                              } else {
                                  alert(data2);
                                  $('#uploadstatus1').show();
                              }
                          }
                      });
                  });
              });
              

              Uploading modal:

              Upload image

              Upload file:

                                          Only Jpeg files are supported.
                                          
                                      
              
                                  
              
                                  
              
                                      Upload failed!
              
              J Offline
              J Offline
              jkirkerx
              wrote on last edited by
              #6

              Regardless of whether your using jQuery which was obsoleted back in 2016 or so, or JavaScript, you need to read the file and convert the binary data to a base64 string, and then just HTTP POST that base64 string to the PHP API. The PHP API would convert the base64 string back to binary data, and just write the binary data as a image file. I found using base64 strings more reliable that sending binary data to the web server. As far as cropping goes, that another story for the PHP world and PHP image processing that you would add to the API, in the form of coordinates. On the PHP side, grabbing the HTTP POST payload would be, well I would of used this instead for PHP 7.4+.

              $imagePayload = file_get_contents('php://input');

              You don't need to try the payload, it's either there or not. I forgot how to write jQuery, that was years ago for me. I just use plain vanilla JavaScript now.

              If it ain't broke don't fix it Discover my world at jkirkerx.com

              Richard DeemingR 1 Reply Last reply
              0
              • J jkirkerx

                Regardless of whether your using jQuery which was obsoleted back in 2016 or so, or JavaScript, you need to read the file and convert the binary data to a base64 string, and then just HTTP POST that base64 string to the PHP API. The PHP API would convert the base64 string back to binary data, and just write the binary data as a image file. I found using base64 strings more reliable that sending binary data to the web server. As far as cropping goes, that another story for the PHP world and PHP image processing that you would add to the API, in the form of coordinates. On the PHP side, grabbing the HTTP POST payload would be, well I would of used this instead for PHP 7.4+.

                $imagePayload = file_get_contents('php://input');

                You don't need to try the payload, it's either there or not. I forgot how to write jQuery, that was years ago for me. I just use plain vanilla JavaScript now.

                If it ain't broke don't fix it Discover my world at jkirkerx.com

                Richard DeemingR Offline
                Richard DeemingR Offline
                Richard Deeming
                wrote on last edited by
                #7

                jkirkerx wrote:

                ... you need to read the file and convert the binary data to a base64 string, and then just HTTP POST that base64 string to the PHP API

                Or use FormData, which will let the PHP code handle the file upload in the same way as a normal form submission. Using FormData Objects - Web APIs | MDN[^]


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                J 1 Reply Last reply
                0
                • Richard DeemingR Richard Deeming

                  jkirkerx wrote:

                  ... you need to read the file and convert the binary data to a base64 string, and then just HTTP POST that base64 string to the PHP API

                  Or use FormData, which will let the PHP code handle the file upload in the same way as a normal form submission. Using FormData Objects - Web APIs | MDN[^]


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  J Offline
                  J Offline
                  jkirkerx
                  wrote on last edited by
                  #8

                  I didn't know about FormData. I've been working on this PHP project for quite some time now, writing a bunch of SPA type pages writing JavaScript and PHP APIs. And never before had to use the browser so much to look at my HTTP request and responses to make sure my payloads are correct. Quite interesting how the browser packages all the input elements into a nice payload and sends it off to the server as a POST, and the format that it uses for packaging, pretty much how FormData is constructed. I was thinking the OP on this post could actually just build a JSON payload with his crop coordinates, filename, and a base64 string and post it to his API page. Then his API can just grab the payload, parse it and he would have all the data he needs to finish the image in one tidy package. But he has to start somewhere and just posting binary data to his API is a good start to get him rolling with something successful.

                  If it ain't broke don't fix it Discover my world at jkirkerx.com

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups