1

I'm trying to create AJAX form handler. The problem is I'm having troubles with uploading an image file along with other data in form.

Uploaded file will cause:

Uncaught TypeError: Illegal invocation

I guess it's because my AJAX formhandler has processData set to default and therefore cannot convert file into a string. However, if I set processData to false the data send won't be recognised by my php file.

How could i make this form send both files and strings well and then read them in php?

Here's my ajax/jquery:

$('#createcompany').click(function() {

            var formData = {

                'ownerid'                : $('#id').text(),
                'companyname'            : $('#companyname').val(),
                'logo'                   : $('#logo')[0].files[0],
                'investment'             : $('#investment').val(),
                'payment'                : $('#payment').val(),
                'companytype'            : $('#companytype').val(),
                'companyresource'        : $('#companyresource').val()
            };

            $.ajax({
                type        : 'POST',
                url         : 'processcreatecompany.php',
                data        : formData,
                dataType    : 'json',
                encode      : true
            }).done(function(data) {

                console.log(data); 

            }).fail(function(data) {

                console.log(data); 

        })
    });

And my PHP data recipient lines:

    $ownerid = filter_input(INPUT_POST, 'ownerid', FILTER_SANITIZE_STRING);
    $companyname = filter_input(INPUT_POST, 'companyname', FILTER_SANITIZE_STRING);
    $investment = filter_input(INPUT_POST, 'investment', FILTER_DEFAULT);
    $payment = filter_input(INPUT_POST, 'payment', FILTER_DEFAULT);
    $companytype = filter_input(INPUT_POST, 'companytype', FILTER_SANITIZE_STRING);
    $companyresource = filter_input(INPUT_POST, 'companyresource', FILTER_SANITIZE_STRING); 

for file request I'd use this:

$_FILES['logo']

EDIT:

HTML markup of form (little bit messy since i just added the form to be able to call for it):

    <form id="formcompany">
        <div class="new-company-informations">
            <h1>BASIC INFORMATION</h1>
            <div id="company-name" class="company-info"><h1>Company name:</h1><input type="text" name="companyname" id="companyname" maxlength="50"></div>
            <div id="company-logo" class="company-info"><h1>Company logo:</h1><input type="file" name="logo" id="logo"></div>
            <div id="company-investment" class="company-info"><h1>First investment amount:</h1><input type="text" name="investment" id="investment"></div>
            <div id="company-payment" class="company-info"><h1>Basic wage per EP:</h1><input type="text" name="payment" id="payment" maxlength="20"></div>
        </div>

        <div class="new-company-separator"></div>

        <div class="new-company-area">
            <h1>AREA OF ECONOMY</h1>
            <div id="company-type" class="company-area">
                <h1>Company type:</h1>
                <select name="companytype" id="companytype">
                    <option value="" selected="selected">Choose company type</option>
                    <option value="1">Resource gathering (5.000 eDollars)</option>
                    <option value="2">Processing/manufacturing (15.000 eDollars)</option>
                    <option value="3">Production (30.000 eDollars)</option>
                    <option value="4">Labolatory (100.000 eDollars)</option>
                    <option value="5">Architecture development (500.000 eDollars)</option>
                    <option value="6">Innovations (1.000.000 eDollars)</option>
                </select>
            </div>
            <div id="company-resource" class="company-area">
                <h1>Resource:</h1>
                <select name="companyresource" id="companyresource">
                    <option value="" selected="selected">Choose resource</option>
                    <option value="1">Lumbermill (Wood)</option>
                    <option value="2">Quarry (Stone)</option>
                    <option value="3">Mine (Ore)</option>
                    <option value="4">Mine (Coal)</option>
                    <option value="5">Farm (Food)</option>
                    <option value="6">Farm (Leather and cloth)</option>
                </select>
            </div>

           <input type="hidden" value="<?=$_SESSION['user']['id']?>">
            <div id="company-button" class="company-area">
                <button id="createcompany">Create</button>
            </div>
        </div>
    </form>
Damian Doman
  • 522
  • 8
  • 19
  • To upload binary data you need to use a `FormData` object, not a plain object. You'll also need to set `contentType` and `processData` to `false` in the `$.ajax` call. See the duplicate for more information – Rory McCrossan Apr 26 '17 at 13:18

1 Answers1

1

Use a FormData and parse the id of your form. Doing this, all the contents of your form, including the files will be parsed via AJAX of course to your server-side(PHP)

 var formData = new FormData(this);

 $.ajax({
                    type        : 'POST',
                    url         : 'processcreatecompany.php',
                    data        : formData,
                    dataType    : 'json',
                   contentType: false,
                   processData: false,                        
                }).done(function(data) {

                    console.log(data); 

                }).fail(function(data) {

                    console.log(data); 

            })
        });

in your php, do this,

var_dump('Posted fields are '.$_POST);
var_dump('Files are '. $__FILES);
Rotimi
  • 4,783
  • 4
  • 18
  • 27
  • 1
    Just added that. Thanks @RoryMcCrossan – Rotimi Apr 26 '17 at 13:20
  • now it strangely refreshes my website. I have tried setting `var formData = new FormData($('#formcompany'));` in dev console and when i call for `formData;` all i get is `FormData {}` - isn't it empty now? – Damian Doman Apr 26 '17 at 13:44
  • remove `encode: true,` Also copy what i wrote. – Rotimi Apr 26 '17 at 13:47
  • still same story. i also get this address query `?companyname=&logo=&investment=&payment=&companytype=&companyresource=` (with good values if i set them in inputs) - isn't such address query meant for GET method? i'm pretty sure it's set to POST now – Damian Doman Apr 26 '17 at 13:52
  • post your html form – Rotimi Apr 26 '17 at 13:58
  • posted in edit @Atkin – Damian Doman Apr 26 '17 at 14:04
  • Hey, i've managed to stop the weird refresh thing by setting there an `` instead of previous button and using `prevent.default`. Now i get "Posted fields are array" and Files are array" - is that good? – Damian Doman Apr 26 '17 at 14:11
  • yeah the issue was with your html form. Lets discuss in chat. Send your html form there. – Rotimi Apr 26 '17 at 14:13
  • 1
    Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/142742/discussion-between-akin-and-damian-doman). – Rotimi Apr 26 '17 at 14:15