How to get a PHP file past $.ajax?

Asked

Viewed 290 times

4

I’m having a problem I don’t know if it’s sending in $.ajax or picking up with PHP.

Is not coming the $_FILES normal on the other side, arrives as 'caminhofoto' => string 'C:\fakepath\1.jpg' (length=17), gave var_dump($_POST), but when trying to take the path and move to the directory it only mounts the path no longer takes the file.

My JS:

var caminhofoto = $("input[name='caminhofoto']").val();

        $.ajax({
                url: '/add-data.php',
                type: 'POST',
                data: {
                    caminhofoto: caminhofoto
                }
            }).done(function (data) {
            
                console.log("Sucesso: " + data);
           
            });

And in PHP:

$img = "imgs/";
$caminhofoto = $img . basename($_FILES['caminhofoto']['name']);
$imgFileType = strtolower(pathinfo($caminhofoto, PATHINFO_EXTENSION));

$uploaddir = '/fotos/';
$obj->setPath($uploaddir . $caminhofoto );

Only that it is recording in the bank only the way without the file, it seems that as it is going as fakepath it is not getting to take.

  • The upload via ajax is incorrect, you should do as explained in this reply https://answall.com/a/9712/3774

  • In case I cannot use Submit to submit the form, because I need to get the manual data of each input, , in this case the var formData = new FormData(this); won’t work.

  • Why won’t it work?

  • Because my function and if the user click the button type button, it takes the data one by one and sends it to PHP. Instead of giving Submit in the form.

  • 3

    You can wear something like var formData = new FormData();, formData.append('foto', $("input[name='caminhofoto']").prop('files')[0] ); instead of var formData = new FormData(this);

  • Bacana worked. Thanks, Put as answer I mark as solved @Icaromartins

Show 1 more comment

1 answer

3


We talked through the comments of the question and it was found that the problem was occurring because of the way the value was being sent by ajax.

Using the FormData to upload the file it would achieve reach the goal as shown in the example below.

var formData = new FormData(),
    $inputFoto = $("input[name='caminhofoto']");

 formData.append('foto', $inputFoto.prop('files')[0] );

 $.ajax({
     url: '/add-data.php',
     type: 'POST',
     data: formData,
     success: function(data) {
         alert(data)
     },
     cache: false,
     contentType: false,
     processData: false,
});

Another answer worth looking for Gabriel Gartz

Browser other questions tagged

You are not signed in. Login or sign up in order to post.