1

Hi am trying to upload an image and insert data into items table ( phpmyadmin ) It works if i don't user ajax but when i tried to upload using ajax it didn't work

This is my html5 script

<form id="InsertItemTodatabase" enctype="multipart/form-data" action="requests/newItem.php" method="post" class="add-new-item-form-form">

                    <div class="form-group">
                        <input type="text" name="itemName" placeholder="Item name" class="form-control" id="itemNameJs">
                    </div>

                    <div class="form-group">
                        <input type="text" name="itemDesc" placeholder="Item Description" class="form-control" id="itemDescJs">
                    </div>

                    <div class="form-group">
                        <input type="text" name="itemPrice" placeholder="Item Price" class="form-control" id="itemPriceJs">
                    </div>


                    <div class="form-group">
                        <?php $fetch = fetchData( '*', 'category', '' , '', '', $fetch="fetchAll" ); ?>

                        <select class="form-control" name="category" id="itemCatJs">
                            <option value="0">Select Category</option>
                            <?php 

                                foreach ($fetch as $data) {
                                    echo '<option value="' . $data[ 'cat_id' ] . '">' . $data[ 'cat_name' ] . '</option>';
                                }

                            ?>

                        </select>

                    </div>


                    <div class="form-group">
                        <input type="text" name="itemAmount" placeholder="Amount" class="form-control" id="itemAmountJs">
                    </div>

                    <div class="form-group">
                        <label for="uploadItemPic" class="btn btn-primary">Upload Item Picture</label>
                        <input type="file" id="uploadItemPic" name="itemPic" class="form-control">
                    </div>

                    <div class="form-group">
                        <button type="submit" name="submitAddItemForm" id="submitNow">
                            <i class="ti-plus"></i>
                            Add Item
                        </button>
                    </div>

                </form><!-- /.add-new-item-form-form -->

And this is my jQuery/Ajax script for uplaoding data.

$(document).on( 'submit', '#InsertItemTodatabase', function(e){
    e.preventDefault();

    var file_data = $('#uploadItemPic').prop('files')[0],
        name      = $( '#itemNameJs' ).val(),
        desc      = $( '#itemDescJs' ).val(),
        price     = $( '#itemPriceJs' ).val(),
        cat       = $( '#itemCatJs option:selected' ).val(),
        amount    = $( '#itemAmountJs' ).val(),
        image     = $( '#uploadItemPic' ).val();

        var file = new FormData();
        file.append('file',$('#uploadItemPic')[0].files[0]);

    var ajaxUrl = $(this).attr('action');
    alert(file);                             
    $.ajax({
        url: ajaxUrl, // point to server-side PHP script 
        type: 'POST',
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: {
                name   : name,
                desc   : desc,
                price  : price,
                cat    : cat,
                amount : amount,
                image  : image,
                file

             },                         

        success: function(php_script_response){
            alert(php_script_response); // display response from the PHP script, if any
        }
     });

});

And this is my newItem.php

<?php


if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ){

    include "../database\connect.php";

    $item_name     = $_POST[ 'itemName' ];
    $item_desc     = $_POST[ 'itemDesc' ];
    $item_price    = $_POST[ 'itemPrice' ];
    $item_amount   = $_POST[ 'itemAmount' ];
    $item_category = $_POST[ 'category' ];


    $formErrors = array();

    if( empty( $item_name ) ){
        $formErrors[] = 'You should type the item name'; 
    }
    if( empty( $item_desc ) ){
        $formErrors[] = 'You should add item description';
    }
    if( empty( $item_price ) ){
        $formErrors[] = 'You should add item price';
    }
    if( empty( $item_amount ) ){
        $formErrors[] = 'You should type item amount';
    }
    if( $item_category == 0 ){
        $formErrors[] = 'You should select item category';
    }


    $item_picture = $_FILES[ 'itemPic' ];
    $picture_name = $item_picture[ 'name' ];
    $picture_temp = $item_picture[ 'tmp_name' ];
    $picture_size = $item_picture[ 'size' ];
    $picture_type = $item_picture[ 'type' ];

    if( empty( $picture_name ) ){
        $formErrors[] = 'You should select item picture';
    }



    /*

        Picture Extension
        -------------------

    */


        $extensions = array( "png", "jpg", "jpeg", "gif" );

        $picture_name_explosion = explode('.', $picture_name);
        $extension_name = end( $picture_name_explosion );
        $extension = strtolower( $extension_name );


        if( !in_array($extension, $extensions) && !empty( $picture_name ) ){
            $formErrors[] = 'This extension is not allowed';
        }
        if($picture_size > 4194304){
            $formErrors[] = 'Image Can\'t Be Larger Than 4MB';
        }

        if( empty( $formErrors ) ){

            $item_image = rand( 0, 1000000 ) . '_' . $picture_name;
            move_uploaded_file($picture_temp, '../layouts/images/items' . $item_image);

            $stmt = $db->prepare( "INSERT INTO Items( item_name, item_description, item_pic, item_price, amount,    added_date, cat_id ) VALUES( :zname, :zdesc, :zpic, :zprice, :zamount, :zdate, :zcat ) " );

            $stmt->execute( array(

                'zname'   => $item_name,
                'zdesc'   => $item_desc,
                'zpic'    => $item_image,
                'zprice'  => '$' . $item_price,
                'zamount' => $item_amount,
                'zdate'   => date( 'Y-m-d h:i:s' ),
                'zcat'    => $item_category

            ) );
            echo date( 'Y-m-d h:i:s' );
        }

        foreach ($formErrors as $error) {
            var_dump( $error );
        }
}

When i tried to upload i get an error that $_POST data is not defined in newItem.php

Please help me in that, And thanks in advance!

  • The `$_POST` keys that you are using in PHP do not match the keys that you are passing in the ajax data object. `itemName` vs `name` etc – Patrick Q May 10 '18 at 13:26
  • Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – Patrick Q May 10 '18 at 13:27

2 Answers2

1

You don't need to write so much of code, instead try to give name attribute to your form tab.

<form id="jqdata" enctype="multipart/form-data" method="post" class="add-new-item-form-form" name="jqdata" action="requests/newItem.php">

Now your ajax call:

var ajaxUrl = $(this).attr('action');
$(document).ready(function(){
    $('#submitNow').click(function(e){
        e.preventDefault();
        var form = $("#jqdata");
        var formdata = new FormData(form[0]);
         $.ajax({
                url: ajaxUrl,
                data: formdata,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (output) {
                    alert(output);
                    $("#jqdata")[0].reset(); //reset all data from form.
                }
            });
    });
});

Try this and do let me know if it works.

Bits Please
  • 877
  • 6
  • 23
0

Change your variable assignments as mentioned below:

$item_name     = $_POST[ 'name' ];
$item_desc     = $_POST[ 'desc' ];
$item_price    = $_POST[ 'price' ];
$item_amount   = $_POST[ 'amount' ];
$item_category = $_POST[ 'cat' ];

The Data posted to newitems file is the one that you have set in your ajax request. So the field names that you are using should be changed to match the ones set in your ajax data.

Faham Shaikh
  • 983
  • 2
  • 6
  • 15
  • remove the following attributes from your ajax `dataType: 'text', // what to expect back from the PHP script, if anything cache: false, contentType: false, processData: false,` – Faham Shaikh May 10 '18 at 13:51
  • Worked but i get that error `TypeError: 'append' called on an object that does not implement interface FormData` – alaa nabawy May 10 '18 at 14:06
  • Sorry, My bad You only had to remove dataType and cache attributes to get this to work. Please try and let me know. – Faham Shaikh May 10 '18 at 14:23