POST to PHP from different HTML files using AJAX?

I have 3 HTML file that I am using to upload the pictures to a specific folder and sub folder. The problem that I am facing is when I POST from 1st and 2nd HTML page I can move the image to the specific folder and sub-folder but as soon as I POST the FILE from the 3rd HTML, it gives me a success alert but the image is not uploaded. Below are the codes.

PHP:

 if(isset($_POST))
{
    session_start();
    //The target location for the image to be stored.
    $_SESSION['str'];
    $_SESSION['str1'];
    $_SESSION['str2'];
    //To rename the file
    $_SESSION['img'];
    $_SESSION['img1'];
    $_SESSION['img2'];


     if(!empty($_FILES["info_file"]["name"])){

     move_uploaded_file($_FILES['info_file']['tmp_name'], $_SESSION['str'].$_SESSION['img']);
         echo 'Upload Successful';

    }
    else 
        {
        if(!empty($_FILES["info_file1"]["name"])){
            move_uploaded_file($_FILES['info_file1']['tmp_name'], $_SESSION['str1'].$_SESSION['img1']);
        }
        else
        {
            if(!empty($_FILES["info_file2"]["name"]))
            {
            move_uploaded_file($_FILES['info_file2']['tmp_name'], $_SESSION['str2'].$_SESSION['img2']);
            }
        }
        }
}

HTMLs:

1st.

<script>

function readURL(input) {

        if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah')
                .attr('src', e.target.result)
                .width(300)
                .height(340);
        };

        reader.readAsDataURL(input.files[0]);
    }
   uploadfunc();

  }
</script>
<script> 
function uploadfunc(){  
     if(!navigator.onLine){ 
        alert("你已離線,請再試一次");
        return false;   
    }else{
     var formData = new FormData();
     var info_file_data = $('#imageid').prop('files')[0];
     console.log(info_file_data);
      formData.append('info_file', info_file_data);
      // for 2nd and 3rd HTML onlt this 'info_file' changed to 'info_file1' and 'info_file2' respectively.
     $.ajax({
          url: 'login.php', // point to server-side PHP script 
          dataType: 'text',  // what to expect back from the PHP script, if anything
          cache: false,
          contentType: false,
          processData: false,
          data: formData,                         
          type: 'post',
          success: function(php_script_response){
            alert ("上載成功");
          }
        });
    }
}
</script>

</head>
<body style="text-align:center">


<h1 style="color:#F00">SMArt-InterAct</h1><br/>

<h2 style="color:#03F">相片上載</h2>
  <form enctype="multipart/form-data" id="form" method="POST">
     <input type="file" required id="imageid" name="image" onChange="readURL(this);" />
    <img id="blah" src="#" alt="你的相片" /><br/><br/>
     <input type="button" class="test" value="上傳"/>
  </form>

</body>


Source: ajax

Leave a Reply