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!

2

2 Answers 2

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.

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

3 Comments

sry I have updated it, please check updated one, I have changed your name attribute in form tag.
I got that error TypeError: $(...)[0] is undefined
alert(form); and see are u giving current form id or not
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.

3 Comments

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,
Worked but i get that error TypeError: 'append' called on an object that does not implement interface FormData
Sorry, My bad You only had to remove dataType and cache attributes to get this to work. Please try and let me know.

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.