skip to Main Content

im using ajax to post file and text in a form, When I use the file and the text input simultaneously, I get into trouble , this is my form:

    <form action="insertbook.php" method="post" id="addBookForm" enctype="multipart/form-data">
        <table >
        <!-- 1- IMAGE -->
        <tr>
            <td>Image:</td>
            <td>
                <input accept="image/gif, image/png, image/jpeg, image/jpg"
                    type="file" name="img_data" id="img_data">
            </td>
        </tr>

        <!-- 2- NAME-->
        <tr>
            <td>Book Name: </td>
            <td >
                <input type="text" name="title" id="title">
            </td>
        </tr>
        <!-- 3- CATEGORY -->
        <tr>
            <td>Book Cat: </td>
            <td>
                <select id="cat_dropdown" onchange="selectionCatchange()">
                        <?php for ($i=0; $i< sizeof($cats); $i++ ) { 
                        echo '<option  value="'.$cats[$i]['id'].'" >'. $cats[$i]['cat_name'] .'</option>';
                         } ?>
                </select>
                <?php echo 
                '<input  id="cat_id" name="cat_id" value="'. $cats[0]['id'] .'"  type="hidden">' ;
                ?>
            </td>
        </tr> 

        <!-- SUBMIT -->
        <tr>
            <th colspan="2" >
                <input id="insertbook" type="submit" name="submit" >
            </th>
        </tr>
    </table>
</form>

In Javascript codes, We have:

$("#addBookForm").submit(function(e) {
    /* Stop form from submitting normally */
    e.preventDefault();
    /* Get some values from elements on the page: */
    var title = document.getElementById('title').value;
    var img_data = $('#img_data').prop('files')[0];
    var cat_id = document.getElementById('cat_id').value;
    var submit = "submit";
    $.ajax({
        url: "insertbook.php",
        type: "POST",
        data: {'title':title,
                 'img_data':img_data,
                'cat_id':cat_id,
                'submit':submit
                },
        dataType:'html',
        success: function(data){
          console.log(data);
        },
        error:function(data){
            alert(data);
        }
    }); 
});

But in PHP Code, following this:

<?php 
     $conn = mysqli_connect(****);
     mysqli_set_charset($conn,"utf8");
    if( 
        isset($_POST['title']) && 
        isset($_POST['cat_id']) && 
        isset($_POST['submit']) 
        && 
        isset($_FILES['img_data'])
     ){

    $title = $_POST['title'];
    $cat_id = $_POST['cat_id'];

    // THIS SECTION RELATE TO IMAGE UPLOAD
    $name_img = basename($_FILES['img_data']['name']);
    $type_img = strtolower($_FILES['img_data']['type']);
    $data_img = file_get_contents($_FILES['img_data']['tmp_name']);

    $uploadOk = 1;
    // Check file size
    if ($_FILES["img_data"]["size"] > 2097152) {
        echo "Sorry, your file is too large > 2 Mb!";
        $uploadOk = 0;
    }
    if ($uploadOk == 0) {
    echo "Sorry, your image file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (mysqli_query( $conn,"INSERT INTO `books`( `title`, `img`, `cat_id`, `created_at`) VALUES ('$title','".addslashes($data_img)."', '$cat_id', NOW())" )) {
        echo "New record created successfully";
        } else {
            echo "Error: " . "<br>" . mysqli_error($conn);
        }
    }}else{echo "Please set all information...!!! ";}
?>

But in the end I get the following error every time:

Notice: Undefined index: img_data in insertbook.php on line 6

Notice: Undefined index: img_data in insertbook.php on line 22

Notice: Undefined index: img_data in *insertbook.php on line 23

Notice: Undefined index: img_data in ***insertbook.php on line 24

Warning: file_get_contents(): Filename cannot be empty in *insertbook.php on line 24

Notice: Undefined index: img_data in ***insertbook.php on line 34
New record created successfully

But in the end there is no file stored in the database and only one empty record is created, hopefully you can help guide me through the problem.
Thanks

2

Answers


  1. To check a file input if it is set or not is this.

    Change this art in your if condition

    isset($_FILES['img_data'])
    

    To this

    isset($_FILES['img_data']['name'])
    
    Login or Signup to reply.
  2. You should try this

    Remove action method and enctype attributes from from tag element.

    Try with sending data using new FormData() in ajax.

    $("#addBookForm").on('submit', function (e) {
        e.preventDefault();
        var formData = new FormData(this);
        formData.append('submit', 'submit');
        $.ajax({
            type: 'POST',
            url: 'insertbook.php',
            data: formData,
            contentType: false,
            cache: false,
            processData: false,
            success: function (data) {
                console.log(data);
            },          
            error: function (jqXHR, textStatus, errorThrown) {
                alert("Some problem occurred, please try again.");
            }
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search