0

I am trying to upload an image using Jquery and php but it's not getting uploaded. Anybody who knows how to fix this please help me solve this. I checked the ajax url on console.url and it was working but i don't know why its not getting uploaded.

index.php:

<form enctype="multipart/form-data" name="imageform"  id="imageform" method="post">
    <div class="form-group">
        <label>Please Choose Image: </label>
        <input class='file' type="file" class="form-control" name="images" id="images" placeholder="Please choose your image">
        <span class="help-block"></span>
    </div>
    <div id="loader" style="display: none;">Please wait image uploading to server....
    </div>
    <input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
</form>

script:

$(document).ready(function(){
   $('#imageform').on('click', function() {
       var form = $('imageform')[0]; // You need to use standard javascript object here
       var formData = new FormData(form);
       $.ajax({
           url:         'ajax.php',
           data:        formData,
           cache:       false,
           contentType: false,
           processData: false,
           type:        'POST',
           success:     function (data) {
           //   alert(data);
        }
       });
     });
   });

ajax.php:

<?php
require_once 'dbconnect.php';
$data = array();
if (isset($_POST['image_upload'] ) && !empty($_FILES['images'])) {

    $image = $_FILES['images'];
    $allowedExts = array("gif", "jpeg", "jpg", "png");

    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    // Create directory if not exists.
    if (!file_exists('images')) {    
        mkdir('images', 0777, true);
    }
    $image_name = $image['name'];

    // Get image extension.
    $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));

    // Assign unique name to image.
    $name = time() . '.' . $ext;
    //$name = $image_name;
    //image size calcuation in KB
    $image_size = $image['size'] / 1024;
    $image_flag = true;

    // Max image size.
    $max_size = 512;
    if (in_array($ext, $allowedExts) && $image_size < $max_size) {
        $image_flag = true;
    } else {
        $image_flag = false;
        $data['error'] = "Maybe $image_name exceeds max $max_size KB size or incorrect file extension";
    } 

    if ($image["error"] > 0) {
        $image_flag = false;
        $data['error']  = '';
        $data['error'] .= '<br/> ' . $image_name . ' Image contains error - Error Code : ' . $image['error'];
    }

    if ($image_flag) {
        $files = glob('images/*'); // get all file names
        foreach($files as $file) { // iterate files
            if(is_file($file)) {
                unlink($file); // delete file
            }
        }
        move_uploaded_file($image['tmp_name'], 'images/' . $name);

        $src             = 'images/' . $name;
        $dist            = 'images/thumbnail_' . $name;
        $data['success'] = $thumbnail = 'thumbnail_' . $name;
        thumbnail($src, $dist, 200);
        $sql1 = "TRUNCATE TABLE images";
        if (!mysqli_query($conn,$sql1)) {
            die('Error: ' . mysqli_error($conn));
        } 
        $sql2 = "TRUNCATE TABLE image_tag";
        if (!mysqli_query($conn,$sql2)) {
            die('Error: ' . mysqli_error($conn));
        } 

        $sql = "INSERT INTO images (`id`, `original_image`, `thumbnail_image`, `ip_address`) VALUES (NULL, '$name', '$thumbnail', '$ip');";
        if (!mysqli_query($conn,$sql)) {
            die('Error: ' . mysqli_error($conn));
        }
    }
    mysqli_close($conn);
    echo json_encode($data);
} else {
    $data[] = 'No Image Selected..';
}

function thumbnail ($src, $dist, $dis_width = 100) {
    $img       = '';
    $extension = strtolower(strrchr($src, '.'));
    switch($extension)
    {
        case '.jpg':
        case '.jpeg':
            $img = @imagecreatefromjpeg($src);
            break;
        case '.gif':
            $img = @imagecreatefromgif($src);
            break;
        case '.png':
            $img = @imagecreatefrompng($src);
            break;
    }
    $width  = imagesx($img);
    $height = imagesy($img);

    $dis_height = $dis_width * ($height / $width);

    $new_image = imagecreatetruecolor($dis_width, $dis_height);
    imagecopyresampled($new_image, $img, 0, 0, 0, 0, $dis_width, $dis_height, $width, $height);

    $imageQuality = 100;

    switch($extension)
    {
        case '.jpg':
        case '.jpeg':
            if (imagetypes() & IMG_JPG) {
                imagejpeg($new_image, $dist, $imageQuality);
            }
            break;

        case '.gif':
            if (imagetypes() & IMG_GIF) {
                imagegif($new_image, $dist);
            }
            break;

        case '.png':
            $scaleQuality       = round(($imageQuality/100) * 9);
            $invertScaleQuality = 9 - $scaleQuality;

            if (imagetypes() & IMG_PNG) {
                imagepng($new_image, $dist, $invertScaleQuality);
            }
            break;
    }
    imagedestroy($new_image);
}

1 Answer 1

1

You need to use e.preventDefault() to avoid form to submit and reloading the page

Try this:

$(document).ready(function(){
    $('#imageform').on('submit', function(e) {
        e.preventDefault();//preventing page to reload on submit
       var form = new FormData($('#imageform')[0]); //Form object to post using ajax

       $.ajax({
           url: 'ajax.php',
           data: form,
           cache: false,
           dataType: "JSON",
           contentType: false,
           processData: false,
           type: 'POST',

           success: function (data) {
               alert(data);
           }
       });

    });
});
Sign up to request clarification or add additional context in comments.

8 Comments

i got Array ( [images] => Array ( [name] => ty.jpg [type] => image/jpeg [tmp_name] => C:\xampp\tmp\php64F3.tmp [error] => 0 [size] => 59253 ) ) on print_r. but not getting uploaded
worked. Thanks dear. i want one thing too. on success i want to replace image in a div with this new one
Cool, use dataType:"JSON" in order to access json response in success function callback, updated my answer
i used this how get new values on success?
pass new image name i.e. $name like $data['img_name'] = $name so that you can get updated image name inside success function as data.img_name, then you can use $('#divId').html('<img src="images/'+data.img_name+'" />')
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.