0

I've been working on this for hours. I have a basic form that submits the data and feature image for a store i'm building.

I'm sending data from view to controller using ajax, but the $_POST array is always empty in the controller.

view:

<form method="POST" id="newproducts" enctype="multipart/form-data">
<div class="form-group">
    <label class="control-label">Product Name</label>
    <input type="text" name="product" class="form-control" placeholder="Enter product name">                                
</div>
<div class="form-group">
    <label class="control-label">Prodct Category</label>
    <select name="category" class="form-control" id="mycat">
        <option value=""></option>
        <option value="1">Dummy Category 1</option>
        <option value="2">Dummy Category 2</option>
    </select>
</div>
<div class="form-group">
    <label class="control-label">Available Stock</label>
    <input type="number" name="stock" class="form-control" placeholder="Number of Available units">
</div>
<div class="form-group">
    <label class="control-label">Product Price</label>
    <input type="number" class="form-control" name="price" placeholder="Price without the (R)">
</div>
<div class="form-group">
    <label class="control-label">Product Description</label>
    <textarea name="description" placeholder="Enter Prodct Description" class="form-control"></textarea>
</div>
<div class="form-group">
    <label class="control-label">Feature Image</label>
    <input type="file" name="feature" id="feature">
    <div class="error"></div>
    <div class="clearfix"></div>
    <p>&nbsp;</p>
    <div id="preview"></div>
</div>
<div class="form-group">
    <button type="submit" class="btn btn-success" name="add">Add Product</button>
</div>
<div class="form-group">
    <input type="image" src="view/assets/images/ajax-loader.gif" style="display: none;" name="loader">
</div>

product.js

I have left out the validation just to show only the relevant code

var formData = new FormData($('#newproducts')[0]);

            $.ajax({
                type : "POST",
                url  : "controller/products.php",
                // data : {product :product, category:category,stock:stock,price:price,description:description,feature:feature},
                data :  formData,
                cache : false,
                contentType: true,
                processData:false,
                async : false,
                traditional: true,
                beforeSend : function(){

                    $('button[type="submit"][name="add"]').html("Please Wait...");
                    $('input[type="image"][name="loader"]').css('display','block');
                },
                success : function(results){
                    $('button[type="submit"][name="add"]').html("Add Product");
                    $('input[type="image"][name="loader"]').css('display','none');

                    if(results == "ok"){
                        $('#results').removeClass('error');
                        $('#results').addClass('success');
                        $('#results').html('Product added successfully...');
                    }else{

                        $('#results').removeClass('success');
                        $('#results').addClass('error');
                        $('#results').html(results);
                    }
                }
            });
        return false;   
    }

When I sent data like this : data : {product :product, category:category,stock:stock,price:price,description:description,feature:feature}, everything works fine, but the only challenge I have with that is sending the image data for upload.

my controller :

I have just done a simple var_dump to see if does it gets data

var_dump($_POST)

gives :

array(0) { }
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34
user1
  • 262
  • 1
  • 2
  • 13
  • 1
    I don't see `#addnew` anywhere in your page. Try logging `formData`, does it contain what you think it should? – aynber Jun 21 '17 at 14:33
  • What is `$('#addnew')[0]`? When you debug client-side, is anything being sent to the server in the first place? What does `formData` actually contain? – David Jun 21 '17 at 14:33
  • @aynber I made an error whn posting here its `newproducts` – user1 Jun 21 '17 at 14:34
  • @David I get `[object FormData]` – user1 Jun 21 '17 at 14:37
  • @user1: You "get" that from *what*, exactly? When you inspect that variable or log it to the browser's debugging console, *what does it contain*? – David Jun 21 '17 at 14:39
  • When I log the formdata in the console – user1 Jun 21 '17 at 14:42
  • 1
    please don't use `async : false`. It's well known to produce horrible user experience (browser locks up if request takes longer than expected, causing users to think it's crashed) and for that reason some browsers have already deprecated this feature, so you can expect it to stop working entirely in future. – ADyson Jun 21 '17 at 14:42
  • @ADyson Thanks for the info I have removed that and still no luck – user1 Jun 21 '17 at 14:46
  • @user1: Can you expand the object then? Find out what it contains? It's clear that it *is* an object, what you need to find out is what that object actually contains and if it's what you expect. – David Jun 21 '17 at 14:46
  • @ADyson what do u mean by expend? – user1 Jun 21 '17 at 14:50
  • wasn't me who said that. I suspect though that what David means by "expand" is look in detail at the properties within the object, since that is what is pertinent. Just saying "it's an object" doesn't give any information about what's inside it, and it's what's inside that gets sent to the server. Logging it using this command `console.log(JSON.stringify(formData));` is an easy way to see its contents listed neatly. – ADyson Jun 21 '17 at 15:04
  • @ADyson with that added this is what's in the console `{}` empty – user1 Jun 21 '17 at 15:08
  • that's weird. When are you doing the log. Just after `var formData = new FormData($('#newproducts')[0]);` I assume? When does that code get run? Is it after the user clicks on "submit"? Are you preventing the default postback behaviour somewhere? – ADyson Jun 21 '17 at 15:12
  • yes just after that.... default postback is prevented by the validate function, jquery validate, then submitHandler is this function – user1 Jun 21 '17 at 15:18

2 Answers2

2

Try changing this part of you ajax, with these settings, I got it to work. Using this post and one of my own I did a while back for reference, it is where I looked for a "refresher" on FormData.

Here are the parts I changed:

// Pass event, use this instead of false at the end,
// this is just how I stop the default action, it's optional
e.preventDefault();
// Set the form into the formdata
var formData    =   new FormData($("#newproducts")[0]);    
// Append the file to the formdata
formData.append('file',$( '#feature' )[0].files[0]);
// Send normally
$.ajax({
    // Same
    type : "POST",
    url  : "controller/products.php",
    data :  formData,
    processData: false,
    contentType: false,
    // I removed "traditional", but I don't know if it still works with it,
    // I never tried it. Everything after is the same...
Rasclatt
  • 12,498
  • 3
  • 25
  • 33
  • will try this.. atleast now `var_dum` does show the values – user1 Jun 21 '17 at 15:21
  • Everything is working fine, the image is uploaded and database updated. thank you very much... this is what I have been missing – user1 Jun 21 '17 at 15:26
-1

Check the size limit of your php.ini, and try with a higher size than your (like 20MB):

; Maximum allowed size for uploaded files.
upload_max_filesize = 20M

; Must be greater than or equal to upload_max_filesize
post_max_size = 20M

I have got the same problem some years ago. When POST, GET and FILES are empties, the problem is always the size of the input, so if you try to increase the limit, your upload should work fine. You can also try to upload a smaller file than your actual config.

Ryosaku
  • 453
  • 4
  • 14