-2

I am trying to upload the file with the help of ajax, but some reason its not working properly I do not know what is the reason for that. this is my html and jquery and ajax code:

<!DOCTYPE html>
<html>
<title>insert data and upload image with ajax</title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script>
$(document).ready(function() {
    $('#d').click(function() {
        var name = $('#a').val();
        var designation = $('#b').val();
        var fdata = new FormData();
        var files = $ ('#c' )[0].files[0];
        fdata.append( 'file', files );
        $.ajax({
            type: "POST", 
            url: "c3.php",
            data: {name: name, des: designation, file1: fdata},
            contentType: false,
            cache: false,
            processData: false,
            success: function(result) {
                alert(result);
            }
        });
    });
});
</script>
</head>
<body>
<form  method = "POST" enctype = "multipart/form-data">
    <label for = "a"> name </label><br>
    <input type = "name" id = "a"><br>
    <label for = "b"> designation </label><br>
    <input type = "text" id = "b"><br>
    <label for = "c"> profile photo </label><br>
    <input type = "file" id = "c"><br>
    <input type = "button" id="d" value = "submit"><br>
</form>
</body>
</html>

and this is my php code:

<?php
    
$a = $_POST["name"];
$b= $_POST["des"];
    
$target_folder = "image/";
$target_path = $target_folder.basename($_FILES['file1']['name']);
if(move_uploaded_file($_FILES['file1']['tmp_name'], $target_path)){
    $c = $target_path;
} else {
    exit("upload failed");
}
    
$connect = mysqli_connect("localhost:3307", "root", "", "hello");
$sql = "insert into test(name, work, path) values ('$a', '$b', '$c');";
$result = mysqli_query($connect, $sql);
if($result) {
    echo "uploaded the file and inserted the data successfully."; 
} else {
    echo "failed"; 
}
?>

please check my jquery and ajax code and php code and tell me that, what are the mistakes I did and what is the solution for that. thank you

RiggsFolly
  • 89,708
  • 20
  • 100
  • 143
joy
  • 1
  • Good code indentation would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](https://www.php-fig.org/psr/psr-12/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly May 09 '22 at 10:20
  • `file1: fdata` inside your AJAX options makes no sense. You can not just invent arbitrary options yourself, and expect that to have the desired effect. The data you want to send, needs to be passed under the key `data`. And then you want to access `$_FILES['file']`, because `file` is the name of the entry you appended to your FormData object, and not `file1`. – CBroe May 09 '22 at 10:24

0 Answers0