0

I'm trying to provide data to my MYSQL Database using Ajax, however, for some reason my PHP file is not reading the JSON array that I post to the file. Within the array I also have a file to store an image on my server as well as my database.

Javascript file

    $(document).ready(function(){

// Give Data to PHP

       // process the form
               $('form').submit(function(event) {

    // get the form data
    // there are many ways to get this data using jQuery (you can use the class or id also)

    //formData.append('tax_file', $('input[type=file]')[0].files[0]



    var img = $('input[name=img]').prop('files')[0];
    var name = img.name,
        tmp = img.tmp_name,
        size = img.size,
        form = $('input[name=form-submit]').val(),
        myName = $('input[name=my-name]').val(),
        desc = $('input[name=description]').val();

        // document.write(name + tmp + size);



    var formData = {
        'form-submit' :  form,
        'my-name'     :  myName,
        'description' :  desc,
        'img'         :  name,
        'tmp_name'    :  tmp,
        'size'        :  size
    };

    // document.write(JSON.stringify(formData));

    console.log(formData);

    // process the form
    $.ajax({
        url         : 'insert-bio.php', // the url where we want to POST
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        data        : formData, // our data object
        processData : false,
        contentType : false,
        dataType    : 'json', // what type of data do we expect back from the server
        encode      : true
    })

        // using the done promise callback
        .done(function(data) {

            // log data to the console so we can see
            console.log(data); 

            // here we will handle errors and validation messages
        });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});

});

My PHP file

      include('../db.php');

$conn = new Database();

echo explode(",", $_POST['data']);

if(isset($_POST['form-submit'])){
 // text data


 $name = strip_tags($_POST['my-name']);
 $desc = strip_tags($_POST['description']);


 // picture stuff
 $file = rand(1000,100000)."-".$_FILES['img']['name'];
 $file_loc = $_FILES['img']['tmp_name'];
 $file_size = $_FILES['img']['size'];
 $file_type = $_FILES['img']['type'];

 // folder for profile pic
 $folder = "bio-pic/";

 // new file size in KB
 $new_size = $file_size/1024;  

 // make file name in lower case
 $new_file_name = strtolower($file);

 // final pic file
 $final_file=str_replace(' ','-',$new_file_name);

 // mysql query for form data
    if(move_uploaded_file($file_loc,$folder.$final_file)){
        $sql="INSERT INTO bio(img, name, description) VALUES('$final_file', '$name', '$desc')";
        $conn->query($sql);
    }   
} else  {
    echo "Need data";
}

$query = $conn->query("SELECT * FROM bio");
    $results=$query->fetchAll(PDO::FETCH_ASSOC);
    $parse_bio_json = json_encode($results);

    file_put_contents('bio-DATA.json', $parse_bio_json);
    echo $parse_bio_json;

The console shows that I have made contact with my PHP file, but it simply has not read any data.

The error on the PHP file:

Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8
Notice: Array to string conversion in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8 ArrayNeed data[]
Shafizadeh
  • 9,960
  • 12
  • 52
  • 89
  • what is the error ? –  Jun 20 '16 at 00:37
  • *The Error* Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8 The Error: Notice: Array to string conversion in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8 ArrayNeed data[] –  Jun 20 '16 at 00:39
  • @awl1991 you know that JSON cannot have a property that holds a file value right? – HenryDev Jun 20 '16 at 01:02
  • @HenryDev ugh that would be my problem. Would you mind pointing me in the right direction to passing the file as well as my data simultaneously to the PHP file? I really could not find any helpful posts on this. –  Jun 20 '16 at 01:07
  • @awl1991 I just posted an example you can look at. Hope it helps :) – HenryDev Jun 20 '16 at 01:10
  • @HenryDev thank you so much! –  Jun 20 '16 at 01:12
  • @awl1991 You're welcome!. If it helps you please don't forget to mark my answer as the correct one :) Thanks! – HenryDev Jun 20 '16 at 01:13

1 Answers1

0

I had the same issue back in the day. After doing lots of research I found out that JSON cannot have a property that holds a file value. However, you can follow this example. It worked great for me. Hope it helps :)

$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];   
var form_data = new FormData();                  
form_data.append('file', file_data);
alert(form_data);                             
$.ajax({
            url: 'upload.php', // point to server-side PHP script 
            dataType: 'text',  // what to expect back from the PHP script, if anything
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         
            type: 'post',
            success: function(php_script_response){
                alert(php_script_response); // display response from the PHP script, if any
            }
 });
});

PHP

<?php

if ( 0 < $_FILES['file']['error'] ) {
    echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}

?>

Credit goes to -> jQuery AJAX file upload PHP

Community
  • 1
  • 1
HenryDev
  • 4,685
  • 5
  • 27
  • 64