0
  • 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;

        });
    });
Francesco
  • 69
  • 3
  • 10
  • 1
    See http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery – Musa Dec 24 '14 at 19:37
  • @Musa it's only keep the file,what about the another fields of form data? – Francesco Dec 24 '14 at 19:39
  • When you post a file, you don't access it using $_POST['file'] it gets stored in the server global variable for files : $_FILES['file'] – Colum Dec 24 '14 at 19:40
  • @ARH Did you read this answer http://stackoverflow.com/a/8758614/1353011 – Musa Dec 24 '14 at 19:41
  • @Colum $_FILES['file'] it says it's undefined,but i think that all the form contents,containing file,POSTing with ajax to proccess.php,isn't it? – Francesco Dec 24 '14 at 19:47
  • I did something similar to this recently, I wasn't able to post the file using Ajax, so I just made the form target a hidden iframe, waited till the iframe loaded (ie the php finished) and used Ajax to clear the form – Colum Dec 24 '14 at 19:51
  • Look at this: http://blog.teamtreehouse.com/uploading-files-ajax – Colum Dec 24 '14 at 19:53
  • @Musa i'll implement the way you linked into it, it give me this `error:Uncaught ReferenceError: beforeSendHandler is not defined` – Francesco Dec 24 '14 at 19:58

2 Answers2

0

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;
    });
});
Francesco
  • 69
  • 3
  • 10
0

You can use this AJAX to save your fields values.

 $(document).ready(function (e) {
    $("#YourButtonID").on('submit',(function(e) {
    e.preventDefault();
    var fileValue = $('#file').val();
    if(fileValue !='')
    {
        $.ajax({
            url: "submitFile.php", 
            type: "POST",             
            data: new FormData(this), 
            contentType: false,                  
            processData:false,        
            success: function(data)   
            {
                $("#message").html('Image Uploaded Successfully..!!');
                $('#ShowImage').show();
                //$('#file').val('');
                $('#ShowImage').attr("src",data);
            }
        });
    }
    else
    {
        alert("Please Choose file!");
        return false;
    }
    }));

    });

This is HTML part

<form id="uploadimage" method="post" enctype="multipart/form-data">
   <div id="message"></div><br/>    
   <img src="" id="ShowImage" style="display:none;"><br/><br/>
   <label>File:</label>
   <input type="file" name="file" id="file" /><br/><br/>
   <input type="submit" value="Upload" name="submit" id="submit" />
</form>

And at PHP side write this code

<?php
    if($_FILES["file"] !='')
    {
        $name = strtolower($_FILES['file']['name']);
        $File_Ext = substr($name, strrpos($name, '.')); 
        if($name !='' && $File_Ext !='')
        {       
            $NewFileName = time().$File_Ext;
        }

        $cmpltPath = "uploads/".$NewFileName; 
        move_uploaded_file($_FILES['file']['tmp_name'],$cmpltPath) ;
        echo $cmpltPath;
    }
    else
    {
        echo "Failure!!";
    }
?>
Sunil Pachlangia
  • 2,033
  • 2
  • 15
  • 25