0

I have a modal that submit some information and an image through form to database. I am working with php and javascript...well i am not so good with js so i need some help.

Work i have done so far is that i can insert data from form to db without no errors but i don't know how to start and what to do with image upload. I am working now on localhost.

I want to upload image to local folder and to automatically rename it with title that someone entered through form. So the name of image saves into table and the image in folder.

I will past the code here so if anyone can help me with code i will appreciate it.

ajax:

    $(document).ready(function(){

    $('form.insert-movie').on('submit', function(e) {
        e.preventDefault();

        var that = $(this),
            url = that.attr('action'),
            method = that.attr('method'),
            data = {};

        that.find('[name]').each(function(index, value) {
            var that = $(this),
                name = that.attr('name'),
                value = that.val();

            data[name] = value;
        }); 

        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            success: function (msg) {                    
               alert("YOUR SUCCESS MESSAGE HERE");
            },
            error: function (msg) {
                alert("Error " + msg.d.toString());
            }
        });
        return false;
    });

});

queries:

    <?php

include 'config.php';

$pdo = connect();

if(isset($_POST['InputTitle'], $_POST['InputYear'], $_POST['InputDuration'], $_POST['InputDescription'], $_POST['InputGender'])) {

    $InputTitle       = $_POST['InputTitle'];
    $InputYear        = $_POST['InputYear'];
    $InputDuration    = $_POST['InputDuration'];
    $InputDescription = $_POST['InputDescription'];
    $InputGender      = $_POST['InputGender'];
    $InputImage       = $_POST['InputImage'];

    $sql = $pdo->prepare("INSERT INTO filmovi(naslov,godina,trajanje,opis,id_zanr,slika) 
                          VALUES(:field1,:field2,:field3,:field4,:field5,:field6)");
    $sql->execute(array(':field1' => $InputTitle,
                        ':field2' => $InputYear, 
                        ':field3' => $InputDuration, 
                        ':field4' => $InputDescription, 
                        ':field5' => $InputGender,
                        ':field6' => $InputImage));
    $affected_rows = $sql->rowCount();  

}

modal:

    <form action="inc/queries.php" method="post" class="insert-movie" enctype="multipart/form-data">

  <div class="form-group"> <!-- TITLE -->
    <label for="title">Title</label>
    <input type="text" class="form-control" name="InputTitle" id="InputTitle" placeholder="Enter title" required>
  </div>

  <div class="form-group"> <!-- YEAR -->
    <label for="year">Year</label>
    <input type="date" class="form-control" name="InputYear" id="InputYear" placeholder="Year" required>
  </div>

  <div class="form-group"> <!-- DURATION -->
    <label for="year">Duration</label>
    <input type="time" class="form-control" name="InputDuration" id="InputDuration" placeholder="Duration" required>
  </div>

  <div class="form-group"> <!-- GENDER -->
    <label for="year">Gender</label></br>
    <select name="InputGender">
        <option>select a genre</option>
        <?php
        $pdo = connect();
        // display the list of all members in table view
        $sql = "SELECT * FROM zanr";
        $query = $pdo->prepare($sql);
        $query->execute();
        $list = $query->fetchAll();      

        foreach ($list as $rs) {
        ?>  
        echo'   
        <option name="InputGender" value="<?php echo $rs['id'] ?>"><?php echo $rs['naziv'] ?> </option>'

        <?php } ?>
    echo'   
    </select>
  </div>

  <div class="form-group"> <!-- DESCRIPTION -->
    <label for="year">Description</label>
    <textarea class="form-control" name="InputDescription" placeholder="Description" rows="3" required></textarea>
  </div>

  <div class="form-group"> <!-- IMAGE -->
    <label for="image">Image upload</label>
    <input type="file" name="InputImage" id="InputImage">
    <p class="help-block">Select image of movie.</p>
  </div>

Close

Davor Miljkovic
  • 61
  • 3
  • 14

1 Answers1

0

First, you must handle the file upload. Examples here: http://php.net/manual/en/features.file-upload.post-method.php Second you need to figure out what you want to store in your Database.

<?php
include 'config.php';

$pdo = connect();

if(isset($_POST['InputTitle'], $_POST['InputYear'], $_POST['InputDuration'], $_POST['InputDescription'], $_POST['InputGender'])) {

    $InputTitle       = $_POST['InputTitle'];
    $InputYear        = $_POST['InputYear'];
    $InputDuration    = $_POST['InputDuration'];
    $InputDescription = $_POST['InputDescription'];
    $InputGender      = $_POST['InputGender'];

    $uploaddir = '/var/www/uploads/'; // Change this to be a path on your server
    $uploadfile = $uploaddir . basename($_FILES['InputImage']['name']);
    if (move_uploaded_file($_FILES['InputImage']['tmp_name'], $uploadfile)) {
         $InputImageStorePath = $uploadfile;
         $InputImage = $_FILES['InputImage']['name'];
    } else {
         $InputImage = "";
    }

    $sql = $pdo->prepare("INSERT INTO filmovi(naslov,godina,trajanje,opis,id_zanr,slika) 
                          VALUES(:field1,:field2,:field3,:field4,:field5,:field6)");
    $sql->execute(array(':field1' => $InputTitle,
                        ':field2' => $InputYear, 
                        ':field3' => $InputDuration, 
                        ':field4' => $InputDescription, 
                        ':field5' => $InputGender,
                        ':field6' => $InputImage));
    $affected_rows = $sql->rowCount();  

}
?>

I would advise using FormData for your AJAX:

$('form.insert-movie').on('submit', function(e) {
     e.preventDefault();
     var formData = new FormData($('form.insert-movie')),
         url = $(this).attr('action'),
         method = $(this).attr('method');

     $.ajax({
         url: url,
         type: 'POST',
         data: formData,
         success: function (msg) {                    
              alert("YOUR SUCCESS MESSAGE HERE");
              // Close Modal here with .hide() ?
         },
         error: function (msg) {
              alert("Error " + msg.d.toString());
         }
     });
 });
Twisty
  • 30,304
  • 2
  • 26
  • 45
  • i edit this part of my code, i want to store name of image in database. What do i need to do with ajax code? – Davor Miljkovic May 14 '15 at 17:06
  • it is working now, image is saved in folder and in db. only problem is when is press submit in modal, modal stays open and when i close it i need to refresh to see changes – Davor Miljkovic May 14 '15 at 17:21
  • See update to answer. If this answers your question, please check it as the answer. – Twisty May 14 '15 at 17:31
  • ajax code that you updated does not work, nothing happens. Image upload worked and now it does not ?! i get this error in response: Undefined index: InputImage in C:\xampp\htdocs\WeCollect\inc\queries.php on line 15
    – Davor Miljkovic May 14 '15 at 18:02
  • Don't have to use my code. Was just a suggestions. Can revert back to your code or review the HTTP Headers to see what is in Post header. I use tools like FireBug or HttpFox in FireFox for this. – Twisty May 14 '15 at 18:12
  • the code you posted before your last update was working fine, it uploaded image in folder and in db, it work for 5min and stop working, it does not insert image name in db and does not copy img in folder. here is what it say when is click submit: response:
    Notice: Undefined index: InputImage in C:\xampp\htdocs\WeCollect\inc\queries.php on line 15

    Notice: Undefined index: InputImage in C:\xampp\htdocs\WeCollect\inc\queries.php on line 16
    – Davor Miljkovic May 14 '15 at 18:17
  • Is `InputImage` one of the elements that is Posted? – Twisty May 14 '15 at 18:23
  • yes, this is in post: Source InputTitle=Some+Movie+Name&InputYear=2000&InputDuration=123&InputGender=7&InputDescription=some+description &InputImage=Desert+rose.jpg – Davor Miljkovic May 14 '15 at 18:25
  • I do not see why FormData does not work for you, yet you said your code worked. So just use your code so that the file is uploaded properly. – Twisty May 15 '15 at 16:22