Home > Software design >  Problem Sending FormData to PHP together with string data
Problem Sending FormData to PHP together with string data

Time:05-20

I want to send the file data together with string data. I am able to send it from ajax to PHP. But in PHP I can not get correct string data from $_POST[] This doesn´t work. I don´t know how to get the correct string.

I got only initial alphabet from a string. No specific product that I want.

Here is ajax

var action = "product1=" myProduct1 "&product2=" product2;
    var file_data = $('#myfile').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        form_data.append('action', action);

$.ajax({
 type: "POST",
 url: "URL TO PHP",

data:form_data,

dataType: 'json',
contentType: false,
processData: false,
success: function(response){
//Do something
},
});

PHP

$data=$_POST['data'];
$action=$_POST['action'];

    $mydata = array("myStatus"=>"ok", "myMsg"=>$action['product1']);
     echo json_encode($mydata);

UPDATE

I found one solution : javascript script:

var file_data = $('#myfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('product1',my_product1);
form_data.append('product2',my_product2);

PHP code :

$data=$_POST['data'];
    $mydata = array("myStatus"=>"ok", "myMsg"=>$_POST['product2']);
     echo json_encode($mydata);

I am a bit satisfy with this. If someone has another solution would be nice. Because I have lots of string data in this code. If I do manual like this....will look stupid. Unless this is the only solution I can do.

CodePudding user response:

you may try like this,

var action = [
{
    product : "product1",           
},
{
    product : "product2"
}];

var file_data = $('#myfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('action',  JSON.stringify(action));

$.ajax({
 type: "POST",
 url: "URL TO PHP",

data:form_data,

dataType: 'json',
contentType: false,
processData: false,
success: function(response){
//Do something
},
});

and in php side,

$data = json_decode($post,true);
//print_r($data);
foreach ($data as $key => $value) {
     echo $value['product'];echo "<br>";
}

CodePudding user response:

So I think this is the only solution for this case. Let me mark this as correct solution. So that will be useful for other people who have the same issue. The answer is below my question in UPDATE

  • Related