简体   繁体   中英

xmlhttprequest ajax php runs more than once

I have xmlhttprequest file upload. The problem is that the function runs more than once. This is the part where I fire my fileUpload function:

$('.edit-pic').click(function() {
     if ($('#btnSubmit').val() == 'Edit') {
       return false;
                                }
      else if ($(this).prop('id') == 'profilePic') {
         uploadFile('profilePic');
                                }
      else if ($(this).prop('id') == 'content') {
         uploadFile('coverPic');
                                }
                            });

Here's the fileUpload function:

function uploadFile(imageType) {

     $('#the-file').click();
     $('#the-file').change(function() {

          var fileInput = $('#the-file');
          var uri = 'upload.php';
          var formData = new FormData();
          var file = fileInput[0].files[0];
          var xhr = new XMLHttpRequest();

          formData.append("the-file", file);
          xhr.upload.addEventListener('progress', onprogressHandler, false);
          xhr.open('POST', uri, true);
          xhr.setRequestHeader('X-File-Name', file.name + '&' + imageType);

              xhr.onload = function() {

                 if (this.readyState == 4 && this.status == 200) {
                     var response = JSON.parse(this.response);

                          if (response.imageType == 'coverPic') {
                               $('#content').css('background-image', 'url("' + response.tempUrl + '")'); }
                          else if (response.imageType == 'profilePic') {
                               $('#profilePic').prop('src', response.tempUrl);
                                            }
                                        }
                                    };

                 function onprogressHandler(e) {
                    var percent = e.loaded / e.total * 100;
                    console.log('Upload progress: ' + percent + '%');                                        
                                    }

                                    xhr.send(formData);
                                });
                            }
                            ;

This is what I have in my php file:

if (!file_exists($_FILES["the-file"]["name"])) {

            $fileName = $_SERVER['HTTP_X_FILE_NAME'];
            $fileType = $_FILES['the-file']['type'];
            $fileContent = file_get_contents($_FILES['the-file']['tmp_name']);
            $dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);
            $tempUrl = "";
            list($fileName, $imageType) = explode('&', $fileName);

            if ($imageType == 'profilePic') {
                move_uploaded_file($_FILES['the-file']['tmp_name'], "temp/profile/" . $_FILES['the-file']['name']);
                $tempUrl = "temp/profile/" . $_FILES['the-file']['name'];
            } else if ($imageType == 'coverPic') {
                move_uploaded_file($_FILES['the-file']['tmp_name'], "temp/cover/" . $_FILES['the-file']['name']);
                $tempUrl = "temp/cover/" . $_FILES['the-file']['name'];
            }

            $json = json_encode(array(
                'name' => $fileName,
                'type' => $fileType,
                'dataUrl' => $dataUrl,
                'tempUrl' => $tempUrl,
                'imageType' => $imageType
            ));

            echo $json;

My problem is that every time I upload a new picture, the function runs as many times as I clicked the file upload. If I clicked it 4 times to test, it runs 4 times and changes the img src of both profile and cover pics to the last picture I selected. I tried returning false, event.PreventDefault etc. I am open to any suggestions at this point. Sorry about the format, there's a lot of code here.

Have you tried passing the event as an argument to click()?

$('.edit-pic').click(function( e ) {

    e.preventDefault();

     if ($('#btnSubmit').val() == 'Edit') {
       return false;
                                }
      else if ($(this).prop('id') == 'profilePic') {
         uploadFile('profilePic');
                                }
      else if ($(this).prop('id') == 'content') {
         uploadFile('coverPic');
                                }
                            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM