Search code examples
phpjquerymysqlajaxasyncfileupload

how to passing file and other data form by ajax as a POST object to a php page and save it to database?


  • I've a form with text data and i want to send a form content and file via ajax POST method to a Proccess.php handler and i want to get the binary file as an object to insert it into database(mysql).
  • i know that saving file into database is wierd,but it's necessary in that case.
  • and another question:why the POST data sends in $_POST array and the $_POST['file'] which coming from <input type="file" name="file"> from same page is undefined?

here is my code: PHP handler:(proccess.php which ajax sends data to this page):

<?php
    $mysqli = new mysqli('localhost', 'root', '', 'msgsys');
    if(mysqli_connect_errno()) {
        print_r("<h4 id='senterror'>Connection Failed: " . mysqli_connect_errno()."</h4>");
        exit();
    }
    $email = $_POST['email'];
    $file = $_FILES['file']['name']; //i'll try to give an object property to sure that the object exists;
    $file2 = $_POST['file']; //the same attemp;
    print_r($file);
    if($stmt = $mysqli -> prepare("SELECT uid FROM user WHERE eaddress=?")) {
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = mysqli_fetch_row($result)) {
            $recUid = $row[0];
        }
        $stmt->close();
        if (!$result || mysqli_num_rows($result) <= 0) {
            print_r("<h4 id='senterror'>You Can not Mailing To Who doesn't exists!</h4>");
            $mysqli->close();
            exit();
        } else {
            date_default_timezone_set('ASIA/Tehran');
            $today = date('m/d/Y-H:i:s');
            $stmt = $mysqli->prepare("INSERT INTO message (sdeltag,rdeltag,rreadtag,timesent,body,subjecttxt,sender,receiver) VALUES ('0','0','0',?,?,?,'1',?)");
            $stmt->bind_param("ssss",$today,$_POST['txt'], $_POST['subject'],$recUid);
            $stmt->execute();
            print_r("<h4 id='mailsent'>Message Sent Successfully!</h4>");
            $stmt->close();
        }
        $mysqli->close();
    }
?>

ajax:

$(document).ready(function () {
        $('#sendmail').submit(function () {
            var that = this;
            $('#response').html("<b>Loading response...</b>");
            $.ajax({
                type: 'POST',
                url: 'proccess.php',
                data: $(that).serialize()
            })
                .done(function (data) {
                    $('#response').html(data);

                })
                .fail(function () {
                    alert("Posting failed.");

                });
            this.reset();
            return false;

        });
    });

Solution

  • i'll rewrite the ajax part as below and works fine for me:

    $(document).ready(function () {
        $('#sendmail').submit(function () {
            var formData = new FormData($('form')[0]);
            $('#response').html("<b>Loading response...</b>");
            $.ajax({
                url: 'proccess.php',  //Server script to process data
                type: 'POST',
                data: formData,
                async: false,
                success: function (msg) {
                    $('#response').html(msg);
                },
                cache: false,
                contentType: false,
                processData: false
            });
            this.reset();
            return false;
        });
    });