2
votes

I'm trying to use posted FormData form an AJAX call in PHP, but I cannot retrieve the variables. What I'm doing wrong?

here is my Javascript

var sendData = new FormData();
sendData.append('itemid',$('select#selectItems').val());
sendData.append('itemtitle',$('#item-title').val());
sendData.append('itemtext',$('#item-text').val());

$.ajax({
    url: 'ajax.file.php',
    type: 'POST',
    dataType: 'text',
    data: sendData,
    cache: false,
    contentType: false,
    processData: false
});

and my PHP

$itemid = $_POST['itemid'];
echo $itemid;

is always undefined in PHP!

and if I print_r ($_POST);

If I use Firefox the PHP text is:

Array ( [-----------------------------12850217581176488271638880149 Content-Disposition:_form-data;_name] => "itemid" 99 -----------------------------12850217581176488271638880149 Content-Disposition: form-data; name="itemtitle" The Title -----------------------------12850217581176488271638880149 Content-Disposition: form-data; name="itemtext" The Text -----------------------------12850217581176488271638880149-- )

...and using Chrome the PHP response is:

Array ( [------WebKitFormBoundarypyFlwBB31gVYXxRP Content-Disposition:_form-data;_name] => "itemid" 99 ------WebKitFormBoundarypyFlwBB31gVYXxRP Content-Disposition: form-data; name="itemtitle" The Title ------WebKitFormBoundarypyFlwBB31gVYXxRP Content-Disposition: form-data; name="itemtext" The Text ------WebKitFormBoundarypyFlwBB31gVYXxRP-- )

thanks

4
Could you try plugging in hardcode for select#selectItems and see what happens? IE, put "sendData.append('itemid',('testValue').val());"?djbhindi
Are you posting any file input through ajax?Rahil Wazir
no, I'm not posting anything elsedenoise
@djbhindi yes, but no successdenoise
Try commenting dataType: 'text' ! And let me know if that works !Rahul Gupta

4 Answers

0
votes

Try this:

$.ajax({
.
.
beforeSend: function(xhr) {
        xhr.setRequestHeader('Content-Type","application/json');
    }
.
.
});

OR :

$.ajax({
    .
    .
    .
    headers: {"Content-Type","application/json"}
});
0
votes

It seems you have outdated jQuery. Check your jQuery version because an important parameter processData that you use in ajax request constructor is available from version 1.6.

As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header.

In order to do it open your browser console and enter:

jQuery.fn.jquery

I have jQuery 1.4 and this code works for me:

var file = $('.rm-action-popup-input[name=file]').attr('files')[0];
var formData = new FormData();
formData.append('file', file);
formData.append('title', params.title);
var xhrForm = new XMLHttpRequest();
xhrForm.open("POST", "/upload.php");
xhrForm.send(formData);

Check how your Content-Type header should look like: right version

0
votes

I had the same problem. When I did not set the Content-Type property(I used javascript), it worked.

The browser then showed(in the Request Header using Chrome debugging):
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarygfXi4NfQAXa8g7PU

and a var_dump($_POST) showed me what I wanted:
array(2) { ["user"]=> string(4) "test" ["pwd"]=> string(7) "testpwd" }

0
votes

i use fetch to solve it

const options = {
  method: 'POST',
  body: formData,
};
fetch('/API', options).then(function(resp) {
    console.log(resp);
    if(resp.ok) {

        resp.json().then((data) => {
            console.log(data);
            if (data.error) {

            }else{
               console.log(data);
            } // ok
        });
    } else {
        console.log('Respuesta de red OK pero respuesta HTTP no OK');
    }
}).catch(function(error) {
  console.log('Hubo un problema con la petición Fetch:' + error.message);
});