tabia
tabia

Reputation: 635

Uploaded File name send through Ajax

I have a form with some fields and file upload option. I want to send uploaded file through Ajax to upload.php. Here is a code which i have tried and it does not work. Where am i doing wrong? Any suggestions please.

Form.php

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" </script>
<script type="text/javascript">
$(document).ready(function() {
$("#submit_custom").click(function() {
 e.preventDefault();
 var postData = new FormData();

                postData.append('file[]', $('input[type=file]')[0].files[0]);
                postData.append('trxid', $('input[name=trxid]'));
                postData.append('orderid', $('input[name=orderid]'));
                postData.append('custid', $('input[name=custid]'));// Uncaught TypeError: Illegal invocation
  if(proceed)

 $.post('upload.php', post_data, function(response){
 if(response.type == 'error'){ //load json data from server and output message
  output = '<div class="error">'+response.text+'</div>';
  }else{
  output = '<div class="success">'+response.text+'</div>';
  $("#upload_form").slideUp(); //hide form after success
                    }
  $("#upload_form").hide().html(output).slideDown();
  }, 'json');
  });
 });
    </script>
</head>
<body>
<h2>Hello <?php echo $user ?> </h2> <p> "You have successfully done purchasing process.</p>
<div id="upload_form">
<p>To send your size details for your order please upload the following file:</p>
<p>Download custom size form Provide us your custom size: <a  href="download.php?download_file=custom-measurement-form.pdf">File.pdf</a></p>
<form enctype="multipart/form-data" action="" method="post">
    <input type="text" name="trxid" value="<?=$trx?>">
    <input type="text" name="orderid" value="<?=$orderid?>">
    <input type="text" name="custid" value="<?=$customerid?>">
    <input type="file" name="file">
    <input type="submit" id="submit_custom">
</form>
</div>
</body>
</html>

upload.php

<?php
if(isset($_POST['file'])){
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
  $output = json_encode(array( //create JSON data
            'type'=>'error',
            'text' => 'Sorry Request must be Ajax POST'
   ));
   die($output);
    }
    $file=$_FILES['file']['name'];
    $trx=$_POST['trxid'];
    $oid=$_POST['orderid'];
    $cid=$_POST['custid'];
    echo $file;

    $query=mysqli_query($con,"insert into payments(custom_file) value ('$file') where orderid='$oid',trx_id='$trx' and cust_id='$cid' ");
    if($query){
        $m=move_uploaded_file($_FILES['file']['name'],'./ServerUploadedFiles/'.$trx.$file);
        $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your email'));
        die($output);
    }
    else
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Problem uploading file! .'));
        die($output);
    }
}

?>

Upvotes: 2

Views: 4718

Answers (2)

Michael
Michael

Reputation: 1089

This code send data and get result, your code don't make something

Test file a.php

 <html>
 <head>

 <!-- change jquery version, your give me some warnings -->
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 

 <script type="text/javascript">

 $(document).ready(function() {

 var proceed=true; /* ** declare proceed */

 $("#submit_custom").click(function() {
 /*e.preventDefault();*/

 var postData = new FormData();

 alert('Found file '+$('[type=file]').val());
 postData.append('file', $('[type=file]')[0].files[0]);

 if(proceed) {

 $.ajax({
 processData: false, /* important */
 contentType: false, /* important */
 type: "POST",
 url: 'b.php',
 data: postData, /* ** here not post_Data but postData like declared in var*/
 error: function(jqXHR, textStatus, errorThrown){ alert(textStatus); },
 success:function(data, textStatus, jqXHR) { 
 alert(data);
 var response;
 /* added */
 try { response = JSON.parse(data); } catch (err) { alert('Error parsing response.'); return; }

 alert('result after parsing json of a is     '+response.a);
 /* */
 }, 
 dataType: 'html'  /* I change it ot html for this example*/
 });

 }

 });

 });

 </script>

 </head>
 <body>
 <form  name="upload" enctypex="multipart/form-data" action="b.php" method="post">
 <input type="file" name="file">

 <input type="button" id="submit_custom" value="ajax">

 <input type="submit"  value="post">
 </form>
 </div>
 </body>
 </html>

Test file b.php contain response like a json {"a":"2"}

{"a":"2"}

After you will be able to send and get response, you add others pribambasi

Upvotes: 2

Michael
Michael

Reputation: 1089

Try

var postData = new FormData();

$('input[type=file]').each(function() {
    postData.append('file[]', $('input[type=file]')[0].files[0]);
}

not

post_data = {
    'file': $('input[name=file]').val(),

Upvotes: 2

Related Questions