Home jquery Send via ajax form data file

Send via ajax form data file

Author

Date

Category

Good day!

I’ve got a poser – going to the upload of images to a website without reloading the page via ajax

.

There is a form of:

& lt; form name = "uploadimages" method = "post" enctype = "multipart / form-data" & gt;
& Lt; input id = "uploadimage" type = "FILE" name = "uploadimage" id = "uploadfile" & gt;
& lt; / form & gt;

and that’s a function that needs to be sent from the field Ajax file upload handler like this:

& lt; script type = "text / javascript" & gt;
    function setimage () {
    var uploadfile = $ ( "# uploadimage") val ().;
    $.ajax ({
        Type: "POST",
        url: "uploadimages.php",
        data: "img =" + uploadfile,
    SUCCESS: FUNCTION (HTML) {
          $ ( "# Textar") append (html).;
        }
      });
    }
 & lt; / script & gt;

With this no problems, everything works in the handler, except for one thing – there is a function of resizing, which also works individually
!
Looks like this:

// function declared here
$ Img = $ _POST [ 'img']; // get the data
$ Image = imageResize ($ img, 'litimages', 1000, 1000); // do resize (paremetry - kartnka, directory to save, size)
$ Image = "& lt; br & gt; & lt; br & gt; & lt; img src = '" "; & lt; br & gt; & lt; br & gt; width =' 700 '& gt". $ Image.'; // insert a tag address
echo $ image; // and return

Everything is logical, but in fact an error:

Catchable fatal error: Argument 1
passed to imageResize () must be an
array, string given, called in
Z: \ home \ superli \ www \ uploadimages.php
on line 92 and defined in
Z: \ home \ superli \ www \ uploadimages.php
on line 5

This is for me, due to the fact that here there

var uploadfile = $ ( "# uploadimage") val ().;

sent the name of the image, not the image.

Please help us to understand how to properly send the file itself, thanks in advance!


Answer 1, Authority 100%

The question about jQuery, rather than how to download files with all browsers. It’s simple, look (jsfiddle ):

function setimage () {
  var $ input = $ ( "# uploadimage");
  var fd = new FormData;
  fd.append ( 'img', $ input.prop ( 'files') [0]);
  $.ajax ({
    url: 'http://example.com/script.php',
    data: fd,
    ProcessData: False,
    CONTENTYPE: FALSE,
    Type: 'Post',
    SUCCESS: FUNCTION (DATA) {
      alert (data);
    }
  });
}

Update

Oh-ho, php here at all to do with the dollar at the beginning of a variable name means that probably it contains the jQuery-collection.

Update

Have you changed your script then? And not in the example you have $ _ POST [ 'img'] , but must be $ _ FILES [ 'img'] about what I wrote above. I think you still early in these things to do, start with the basics of php, learn how to load the ajax without Fayolle, and then to a working code, try to tie it.


Answer 2, Authority 23%

Load a lot of photos while maintaining the photo names, which are already loaded (this is useful if they need to be put in the database, because you can immediately download 200 pictures to 5 per round):

HTML code:

& lt; form id = 'loadPhform' action = 'index.php' method = 'POST' enctype = 'multipart / form -data '& gt;
  & Lt; input id = 'thisPh' type = 'file' name = 'insPh' multiple & gt; & lt; br / & gt;
& lt; / form & gt;

Javascript code:

// This Virables Is Globals (Declare variables)
  window.Arr = [];
  window.el = $;
  window.LengthImg = 0;
  window.VirableLoading = 0; 
// Download Pictures (Loading Images)
  $ ('# thisph'). ON ('CHANGE', FUNCTION () {
    // CREATE OBJECT FORMDATA (Creating an Form type object)
    var formdata = new formdata ();
      // If the selected image is more than 5
    if ($ ('# thisph') [0] .Files.Length & GT; 5) Return False;
    // INSERT FILE LISTS IN AN OBJECT FORMDATA (Creating an insertion arrays of $ _files in the FormData object)
    $ .each ($ ('thisph') [0] .Files, Function (Count, This_File) {
      // If Mime Type of Picture Not Match With That Formats (if not matched)
      if (! this_file.type.match (/ (.png) | (.jpeg) | (.jpg) | (.gif) $ / i) || ($ ('# thisph') [0] .Files [Count ] .size / 1024) .tofixed (0) & gt; 1524) Return False;
           //Otherwise
      ELSE {
        // Append Objects (insert image arrays $ _files to the FormData object)
        FormData.APPEND ("Image" + count, this_file);
              // If we already inserted all the images
        if (Count == $ ('# thisph') [0] .Files.Length - 1) {
          var query = 0;
                  // Second Protection (if the name is not unknown)
          If ($ ("# thisph") [0] .Files [0] .name! = undefined) {
            // Query.
            $.ajax ({
              URL: 'ajaxdocs / downloadalbumphotos.php',
              Type: 'Post',
              CONTENTYPE: FALSE,
              ProcessData: False,
              datatype: 'json',
              Data: FormData,
              BEFORESEND: FUNCTION (LOADING) {$ ('. Loading'). CSS ("Display", "Block"); },
              SUCCESS: FUNCTION (DATA) {
                if (data ['state'] == "success") {
                  VirableLoading ++;
                  $ ('. Loading'). CSS ("Display", "None");
                  // Cycle
                  For (var i = 0; I & lt; Data ['LengTharr'] + 1; i ++) {
                    // Loading More PHOTOS
                    ARR [LENGTHIMG + I] = DATA ['srcpart'] [i];
                    // If The Cycle Is Ended
                    If (i == Data ['LengTharr']) {
                      // Length photos.
                      Lengthimg + = Data ['LengTharr'] + 1;
                      // How Much Pictures Downloaded
                      $ ('# DownloadDepics'). Val ("loaded (" + Lengthimg + ")");
                    }
                  }
                }
              }
            });
          }
        }
      }
    });
  });

php code:

& lt;? php
  $ Array = array ();
  $ Count = -1;
  // Upload Files.
  Foreach ($ _ Files AS $ Pictures) {
    $ COUNT ++;
    / *** Here is the loading of images (you can and in the database together) *** /
      // The array is accumulated here with image paths (for example, withdraw these all pictures)
    $ Array [$ Count] = $ Namepic;
  }
  // Here we are through JSON in the [SRCPART] element send an array of image paths, in the element
 // [LengTharr] how many images, in the [state] status
  $ json_data = array ('srcpart' = & gt; $ array, 'lengtharr' = & gt; $ count, 'state' = & gt; "success");
  Echo JSON_ENCODE ($ json_data);
? & gt;

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions