skip to Main Content

i have problem pass data from selected file (image)

i will move the image to localhost directory

here my simple code



function uploadFile(){
  event.preventDefault();
  var input = document.getElementById("uploadImage");
  file = input.files[0];
  if(file != undefined){
    formData= new FormData();
    if(!!file.type.match(/image.*/)){
      formData.append("image", file);
     
      $.ajax({
        url: "service.php?aksi=A",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function(data){
            alert('data);
        }
      });
    }else{
      alert('Not a valid image!');
    }
  }else{
    alert('Input something!');
  }
}

here my simple html code

 <input type="file" required="" id="uploadImage" name="gambar" >
                       
<button id="gantiphoto"  name="submit" onclick="uploadFile()" class="btn btn-default">Upload </button>
                     

and call it to specific php function

if ($_POST["aksi"]=="A"){
    
$dir = "asset/";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_FILES["image"]["name"]);

}
elseif ($_POST["aksi"]=="B"){
    
}


i try

 $.ajax({
        url: "service.php?aksi=A",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function(data){
            alert('data);
        }
      });


and

 $.ajax({
        url: "service.php",
        type: "POST",
        data: "aksi=A"+formData,
        processData: false,
        contentType: false,
        success: function(data){
            alert('data);
        }
      });

but the response still
Notice: Undefined index: image in C:xampphtdocsrutelaservice.php on line 166
or

Notice: Undefined index: aksi in C:xampphtdocsrutelaservice.php on line 7

i still dont understand how to pass this image file,. im success with text but cant solve this image pass data

im appreciate ur answer, im just newbie in ajax

2

Answers


  1. You Can Add One More formData Filed

    formData.append("aksi", "A");
    

    Also Change Url to This

    service.php
    After This You Can Check Like

    if($_POST['aksi'] == "A"){
    $dir = "asset/";
    move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_FILES["image"]["name"]);
    }
    else if($_POST['aksi'] == "B")
    {
    }
    
    Login or Signup to reply.
  2. There are a couple things I might change to make this work:

    <script>
    function submitForm()
    {
        // Set error state a true
        var valid   =   false;
        // Init
        var data1 = new FormData();
        // Loop files
        $.each($('input[type="file"]')[0].files, function(i, file) {
            // If the file is good
            if(!!file.type.match(/image.*/)) {
                // Update status to valid
                valid   =   true;
                // Add file
                data1.append(i, file);
            }
        });
        // Do the ajax
        if(!valid) {
            $.ajax({
                url: "service.php?aksi=A",
                type: "POST",
                data: data1,
                enctype: 'multipart/form-data',
                processData: false,
                contentType: false,
                success: function(response) {
                    $('#response').html(response);
                }
            });
        }
        else {
            alert('Incorrect file type');
        }
    }
    </script>
    
    <div id="response"></div>
    <input type="file" required="" id="uploadImage" name="gambar" >                   
    <button id="gantiphoto"  name="submit" onclick="submitForm()" class="btn btn-default">Upload</button>
    

    In your PHP you should first try a test to make sure but I would switch to $_GET here not $_POST:

    // ****** START TEST ******//
    
    // If you do a test, you can see what is being sent so it will help you
    // narrow down where it's going wrong
    echo '<pre>'.print_r([
        $_POST,
        $_GET,
        $_FILES
    ], 1).'</pre>';
    
    // ****** START ACTUAL CODE ******//
    
    // Stop if this is not set
    if(empty($_GET["aksi"]))
        die('aksi is a required parameter.');
    // Switch to GET here
    switch($_GET["aksi"]) {
        case('A'):
            if(empty($_FILES))
                die('Invalid image.');
            $dir = "asset/";
            // I haven't checked, but I think these keys are numeric now
            // The test above should tell you what they are exactly
            move_uploaded_file($_FILES[0]["tmp_name"], $dir. $_FILES[0]["name"]);
            break;
        case('B'):
            // do stuff
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search