1

I have fair knowledge of JS, PHP and Ajax but this simple problem has driven me nuts.

I am trying to upload an image silently, without using a form. I am not using a form because that will lead to nested forms in my HTML, which I read, can cause additional issues.

I have been able to use oFReader, to preview the images.
To upload the image, I am attempting an AJAX call as given below:

HTML

<div id="loginButton2">
  <div id="personalimg"  >
    <img src="photos/seller_photos/<?php echo $profile_pic; ?>" width="70" hight="70" />
  </div>
</div>
<div id="loginBox2" style="display:none">
  <div id="loginForm2" class="floatLeft" >
    <fieldset>
      <input id="file" type="file" name="profile_img" value="photos/seller_photos/<?php echo $profile_pic;?>"/>
      <input id="file_submit" type="hidden" name="submit4" value="1" >
    </fieldset>
  </div>
</div>

JS

$('#file').change(function(){
  var oFReader = new FileReader();
  oFReader.readAsDataURL(this.files[0]);
  var fd = new FormData();
  var file = $("#file").prop("files")[0];
  fd.append('profile_img', file);
  fd.append('submit4', 1);
  fd.append('filename', 1);
  oFReader.onload = function (oFREvent) {
    $.ajax({
      url: "upload.php",
      dataType: 'image',
      cache: false,
      contentType: false,
      processData: false,
      type: "POST",
      data:  fd,
      success: function(data){
        console.log(data);
      },
      error: function(){
       console.log("image upload failed");
      }
    });
    $('#loginForm2').toggle();
    $('#personalimg').html('<img src="'+oFREvent.target.result+'" width="70" height="70">');
  };
});

PHP

if(isset($_POST['submit4'])) {
  $check_sql =  "select profile_pic from profile where user_id=$user_id";
  $check_rs  =  mysql_query($check_sql);
  $check_num = mysql_num_rows($check_rs);
  if($check_num==0) {
    $sql =  "insert into profile(user_id) values($user_id)";
    $rs  =  mysql_query($sql); 
  }    
  $fName = $_FILES["profile_img"]["name"] ;
  $data  = explode(".", $fName);
  $fileName = $user_id.'.'.$data[1];
  if($fName!='')$user->update('profile_pic',$fileName);
  $fileTmpLoc= $_FILES["profile_img"]["tmp_name"];
  //image store path
  $pathAndName = "photos/seller_photos/".$fileName; 
  $moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
  if(move_uploaded_file) {
    $response['status'] = '1';
    header('Location: edit_profile_new.php');
  } else {
    $response['status'] = '0';
  }
  return $response;

}

But somehow, I have not been able to get this to work. I am using chrome. I get 302 Found status code and "image upload failed" in console.

Can someone please help me out?

ps: I know, mysql is deprecated and will migrate to pdo. This code is inherited and hence has old standards.

rednivlat
  • 135
  • 2
  • 2
  • 11

0 Answers0