0

I am uploading image with jQuery Ajax and I also want to pass user id with Ajax data but when Ajax run I am getting bellow error. I am using MVC structure.

Notice: Undefined index: userImage in/var/www/propio/application/models/user_model.php on line 544

I don't understand why I am getting error. Here is my Ajax code:

$.ajax({
    url: BASE_URL+"user/updateUserImage",
    type : "POST",
    data : new FormData(this) + '&id=' + <?php echo $user_id; ?>,
    contentType : false,
    cache : false,
    processData : false,
    success : function(data) {                  
        $('#loading-div').hide(); // Hide ajax loader
        if(data == "Error: Please upload your image."){
            $('#errorBox').html(data);
        }else if(data == "Error: File is too large. File must be less than 2MB."){
            $('#errorBox').html(data);
        }else if(data == "Error: Image must be in JPEG, JPG or PNG format."){
            $('#errorBox').html(data);
        }else{
            $("#change_photo").html(data);
            $('.featherlight-close').click();
        }
    },
    error : function() {

    }
});

Controller: user.php

public function updateUserImage(){

    // Load model, perform an action on the model
    $loadOffice = $this->loadModel('user_model');
    return $postData = $loadOffice->updateUserImage();

}

Model: user_model.php

public function updateUserImage(){

    if($_FILES['userImage']['type'] =='image/jpeg' || $_FILES['userImage']['type'] =='image/jpg' || $_FILES['userImage']['type'] =='image/png' && $_FILES['userImage']['size'] < 20000){
        if(is_array($_FILES)) {
            if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {

                define('DESIRED_IMAGE_WIDTH', 130);
                define('DESIRED_IMAGE_HEIGHT', 130);

                $timestamp = time();
                $source_path = $_FILES['userImage']['tmp_name'];
                $final_location = USER_PROFILE_UPLOAD_PATH.$timestamp.$_FILES['userImage']['name'];
                $final_location = strtolower($final_location); //Create image name with lower case

                $db_file_name = $timestamp.$_FILES['userImage']['name'];
                $db_file_name = strtolower($db_file_name); //Create image name with lower case

                /*
                * Add file validation code here
                */
                list($source_width, $source_height, $source_type) = getimagesize($source_path);

                switch ($source_type) {
                    case IMAGETYPE_GIF:
                        $source_gdim = imagecreatefromgif($source_path);
                    break;
                case IMAGETYPE_JPEG:
                        $source_gdim = imagecreatefromjpeg($source_path);
                    break;
                case IMAGETYPE_PNG:
                        $source_gdim = imagecreatefrompng($source_path);
                    break;
                }

                $source_aspect_ratio = $source_width / $source_height;
                $desired_aspect_ratio = DESIRED_IMAGE_WIDTH / DESIRED_IMAGE_HEIGHT;

                if ($source_aspect_ratio > $desired_aspect_ratio) {

                   /*
                    * Triggered when source image is wider
                    */
                    $temp_height = DESIRED_IMAGE_HEIGHT;
                    $temp_width = ( int ) (DESIRED_IMAGE_HEIGHT * $source_aspect_ratio);

                } else {

                   /*
                    * Triggered otherwise (i.e. source image is similar or taller)
                    */
                    $temp_width = DESIRED_IMAGE_WIDTH;
                    $temp_height = ( int ) (DESIRED_IMAGE_WIDTH / $source_aspect_ratio);

               }

               /*
                * Resize the image into a temporary GD image
                */
                $temp_gdim = imagecreatetruecolor($temp_width, $temp_height);
                imagecopyresampled(
                    $temp_gdim,
                    $source_gdim,
                    0, 0,
                    0, 0,
                    $temp_width, $temp_height,
                    $source_width, $source_height
                );

               /*
                * Copy cropped region from temporary image into the desired GD image
                */

                $x0 = ($temp_width - DESIRED_IMAGE_WIDTH) / 2;
                $y0 = ($temp_height - DESIRED_IMAGE_HEIGHT) / 2;
                $desired_gdim = imagecreatetruecolor(DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT);
                imagecopy(
                    $desired_gdim,
                    $temp_gdim,
                    0, 0,
                    $x0, $y0,
                    DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT
                );

               /*
                * Render the image
                * Alternatively, you can save the image in file-system or database
                */
                header('Content-type: image/jpeg');
                imagejpeg($desired_gdim, $final_location, 100);

                // Retrieve current user profile image
                $sql = "SELECT profile_picture FROM ".TABLE_USER_DETAIL." WHERE user_id=84";    
                $query = $this->db->prepare($sql);
                $query->execute();
                $result = $query->fetchAll();
                $current_picture = $result[0]->profile_picture; // Get admin current profile image

                $sql = "UPDATE ".TABLE_USER_DETAIL." SET profile_picture = :profile_picture WHERE user_id=84";
                $query = $this->db->prepare($sql);
                $updateProfile = $query->execute(array(':profile_picture' => $db_file_name));

                if($updateProfile && !empty($current_picture)) {
                    unlink(USER_PROFILE_UPLOAD_PATH.$current_picture); // Unlink old profile picture
                }

                ?>
                    <img src="<?php echo URL.$final_location; ?>" />
                <?php

            }
        }
    }else if($_FILES['userImage']['name'] == ""){
        echo "Error: Please upload your image.";
    }else if($_FILES['userImage']['type'] =='image/jpeg' || $_FILES['userImage']['type'] =='image/jpg' || $_FILES['userImage']['type'] =='image/png' && $_FILES['userImage']['size'] > 20000){
        echo "Error: File is too large. File must be less than 2MB.";
    }else{
        echo "Error: Image must be in JPEG, JPG or PNG format.";
    }

}
Mr.Happy
  • 2,639
  • 9
  • 40
  • 73
  • 1
    Your issue comes from user_model.php on line 544, not from your Ajax call.. You seem to be accessing an array's index that doesn't exist. – fkoessler Oct 10 '14 at 06:36
  • It is better if you can share code on user_model.php – Jithin Jose Oct 10 '14 at 06:37
  • @JithinJose I have update `user_model.php` in my question. – Mr.Happy Oct 10 '14 at 06:41
  • I want user_id in this function `updateUserImage()` – Mr.Happy Oct 10 '14 at 06:43
  • Check if `$_FILES['userImage']` exists or has a length before continuing with the function. That is not an error. You can also turn these notices off from your server configuration http://stackoverflow.com/questions/2867057/how-do-i-turn-off-php-notices – Spokey Oct 10 '14 at 06:52

2 Answers2

0

Try this:

$.ajax({
    url: BASE_URL+"user/updateUserImage",
    type : "POST",
    data : {new FormData(this) + 'id:'<?php echo $user_id; ?>},
    contentType : false,
    cache : false,
    processData : false,
    success : function(data) {                  
        $('#loading-div').hide(); // Hide ajax loader
        if(data == "Error: Please upload your image."){
            $('#errorBox').html(data);
        }else if(data == "Error: File is too large. File must be less than 2MB."){
            $('#errorBox').html(data);
        }else if(data == "Error: Image must be in JPEG, JPG or PNG format."){
            $('#errorBox').html(data);
        }else{
            $("#change_photo").html(data);
            $('.featherlight-close').click();
        }
    },
    error : function() {

    }
});
Pang
  • 9,564
  • 146
  • 81
  • 122
DeeSK
  • 13
  • 7
  • Getting this error in your code: `SyntaxError: missing : after property id Source File: http://localhost/sitename/user/84/pt Line: 922, Column: 16 Source Code: data : {new FormData(this) + '&id:'84}, ` – Mr.Happy Oct 10 '14 at 08:09
0

as this is file field in ajax so you can not send it directly instead you should use ajaxform jquery plugin which can do the trick of sending data including files

http://malsup.com/jquery/form/

Sagar Rabadiya
  • 4,126
  • 1
  • 21
  • 27