Tom Odell
Tom Odell

Reputation: 41

Working with input type file AJAX/PHP

I have got this html/php in my index.php

if (isset($_POST['UploadMSub'])) {
    $fileP=$_FILES['Upload_f'];
    $fileP_name=$fileP['name'];
    $fileP_tmp=$fileP['tmp_name'];
    $fileP_size=$fileP['size'];
    $fileP_error=$fileP['error'];
    $fileP_extension=explode('.', $fileP_name);
    $fileP_extension=strtolower(end($fileP_extension));
    $allowed=array('jpg','png');
          if (in_array($fileP_extension, $allowed)) {
            if ($fileP_error===0) {
              if ($fileP_size<=2097152) {
                $fileP_new_name=uniqid().'.'.$fileP_extension;  
        }
      }
    }
    $_SESSION['fileP']=$fileP;
    $_SESSION['fileP_name']=$fileP_name;
    $_SESSION['fileP_tmp']=$fileP_tmp;
    $_SESSION['fileP_size']=$fileP_size;
    $_SESSION['fileP_error']=$fileP_error;
    $_SESSION['fileP_extension']=$fileP_extension;
    $_SESSION['fileP_new_name']=$fileP_new_name;
}

<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
                  <textarea maxlength="400" type="text" class='Text' placeholder="New post"></textarea>
                  <input type="file" name="Upload_f" style="display:none;" id="Nameupload">
                  <label for="Nameupload" class='LabelCamerUp'>
                    <img src="../img/camera.png" class='CamerUp'>
                  </label>
                  <input type="submit" class="UploadMSub">
   </form>

And this ajax

$(".UploadMSub").click(function() {
        var text=$(".Text").val();
        var file=$("#Nameupload").val();            
            $.ajax({
                type: "GET",
                url: '../connect.php',
                data: "Text=" + text+"&&file="+file,
                success: function(data)
                {
                        alert(data);
                }
            });
                return false;
    });

connect.php

    if (isset($_GET['Text'])) {
        $Text=htmlspecialchars($_GET['Text'],ENT_QUOTES);
        $file=htmlspecialchars($_GET['file'],ENT_QUOTES);
        echo $Text." ".$_SESSION['fileP_new_name'];
}

But when i submit form it returns(alerts) "Undefine index ''fileP_new_name'" Is there any other way of getting all information about file in my connect.php?

Upvotes: 1

Views: 78

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

The problem is,

When you hit the submit button, the form doesn't get submitted, which means none of your session variables are set when you hit the submit button. Instead jQuery script runs straight away when you hit the submit button, and that's why you're getting this error,

Undefine index: fileP_new_name

From your question,

Is there any other way of getting all information about file in my connect.php?

So the solution is as follows. You have to change few things in your code, such as:

  • Add a name attribute in your <textarea> element, like this:

    <textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
    
  • Instead of returning false from your jQuery script, use preventDefault() method to prevent your form from being submitted in the first place, like this:

    $(".UploadMSub").click(function(event){
        event.preventDefault();
    
        // your code
    });
    
  • If you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.

  • Set the following options, processData: false and contentType: false in your AJAX request. Refer the documentation to know what these do.

So your code should be like this:

HTML:

<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
    <textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
    <input type="file" name="Upload_f" style="display:none;" id="Nameupload">
    <label for="Nameupload" class='LabelCamerUp'>
        <img src="../img/camera.png" class='CamerUp'>
    </label>
    <input type="submit" class="UploadMSub">
</form>

jQuery/AJAX:

$(".UploadMSub").click(function(event){
    event.preventDefault();
    var form_data = new FormData($('form')[0]);

    $.ajax({
        url: '../connect.php',
        type: 'post',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        success: function(data){
            alert(data);
        }
    });
});

And on connect.php, process your form data like this:

<?php

    if(is_uploaded_file($_FILES['Upload_f']['tmp_name']) && isset($_POST['new_post'])){
        // both file and text input is submitted

        $new_post = $_POST['new_post'];

        $fileP=$_FILES['Upload_f'];
        $fileP_name=$fileP['name'];
        $fileP_tmp=$fileP['tmp_name'];
        $fileP_size=$fileP['size'];
        $fileP_error=$fileP['error'];
        $fileP_extension=explode('.', $fileP_name);
        $fileP_extension=strtolower(end($fileP_extension));
        $allowed=array('jpg','png');
        if (in_array($fileP_extension, $allowed)){
            if ($fileP_error===0) {
                if ($fileP_size<=2097152){
                    $fileP_new_name=uniqid().'.'.$fileP_extension;  
                }
            }
        }

        // your code
        //echo $fileP_new_name;

    }   

?>

Upvotes: 1

Related Questions