View Single Post
Old 02-19-2013, 10:32 PM   PM User | #1
idhist
New to the CF scene

 
Join Date: Feb 2013
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
idhist is an unknown quantity at this point
How do I use ajax to upload a text field and a file?

I'm new at AJAX and am working on an implementation of a form that will upload a name and a file to a php file that processes the data and sends it to a database for insertion using mysqli. I've tested the php file and it does work. My problem is in the AJAX code. I've tried an implementation using XMLHTTP and using jQuery. Both leave the page and open the PHP file in the browser. As a disclamer, I posted this question to another coding site, a fight ensued between two posters, and so I'm trying here to hopefully get a reasoned and calm response with productive suggestions.

I realize that currently "get" is being sent to the PHP file rather than "post", but PHPStorm tells me that "post" is not available in that form. What's my alternative? Am I on the right track or is there another direction I should go? How do I refresh only the form and keep the PHP page from loading?

Here's the relevant snippet of my code,

Code:
<!DOCTYPE html>
<html>
<head>
    <script src="jquery.min.js"></script>
    <script src="jquery.validate.js"></script>
    <script>
        $(document).ready(function() {
            $('#addForm').validate({
                
                submitHandler: function (form) {
                    $('input[name="usingAJAX"]', this).val('true');
                    var url = $(form).prop('action');
                    var dataToSend = $(form).serialize();
                    var callback = function(dataReceived) {
                        $(form).hide();
                        //result message
                        $('body').append(dataReceived)
                    };
                    var typeOfDataToReceive = 'html';
                    
                    $.get(url, dataToSend, callback, typeOfDataToReceive),
                    return false;
                }
            });
        });

    </script>
</head>
<body>
<form id="addForm" action="addInfo.php" enctype="multipart/form-data">
    <input type="hidden" name="usingAJAX" value="false"/>
    <label for="aname">Name: </label>
    <input type="text" name="aname" id="aname" class=required/>
    <label for="aimage">Photo: </label>
    <input id="aimage" type="file" name="aimage" class="required">
    <input type="submit" value="ADD"/>
</form>
</body>
</html>
idhist is offline   Reply With Quote