6

I cannot send via ajax to php file upload and data with ajax. This my code just send file upload. data not send to my php code. I create form and the function send on click using ajax to post on php. I'm using codeigniter

This my form:

<form action="<?php echo site_url('home/send_chat');?>" method="post" enctype="multipart/form-data">
  <input name="message" id="message" type="text" class="form-control input-sm" />
  <input type="file" id="file" name="file" />
  <br />
  <span class="input-group btn">
    <button type="submit" class="btn btn-info btn-sm" id="submit">Enkripsi</button>
  </span>
</form>

This javascript to send post on php using ajax:

$('#submit').on('click', function(){
  var message = $('#message').val();

  var fd = new FormData(this);
  fd.append('file',$('#file')[0].files[0]);

  $.ajax({
    method:"POST",
    url:"<?php echo site_url('home/send_chat');?>",    
    data: {fd,message:message},  
    cache: false,
    contentType: false,
    processData: false,   
    success: function(data){                 
      alert(data);
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }  
  });
});

I'm already try using $_POST['message']; and $this->input->post("message"); its not work both This php to proces code:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
  public function send_chat()
  {
    $name    = $_FILES['file']['name'];
    $error   = $_FILES['file']['error'];
    $size    = $_FILES['file']['size'];


    // $message = $_POST['message'];
    $message = $this->input->post("message");

    $user    = $this->session->userdata('username');
    $iduser  = $this->session->userdata('userID');



    $insert="insert into chat (user,message,id_user,fileupload) VALUES ('$user','$message','$userid','$name')";
    $this->db->query($insert);
  }
}

In database i'm just send name file upload.user, message, and iduser its not send.

5
  • 1
    try to avoid send data in hidden fields use Session for that Commented Dec 16, 2017 at 11:21
  • @kunal my message cannot capture to. This message not hidden fields Commented Dec 16, 2017 at 11:24
  • see you are passing userid and message in hidden field either you can use auth componenet or use session you can't directly pass userid in hidden field anyone can change the userid. Hope you understand and it will help in future coding Commented Dec 16, 2017 at 11:26
  • have you print $_FILES in your function ?? Commented Dec 16, 2017 at 11:28
  • @kunal ok userid. it's wrong.. see that message it's type text. $_FILES its work. but message not work Commented Dec 16, 2017 at 11:30

4 Answers 4

4

i think your problem may be in ajax code since you are using formData object . try append the message variable with it

$('#submit').on('click', function(){

  var fd = new FormData(this);
  fd.append('file',$('#file')[0].files[0]);
  fd.append('message ',$('#message').val());

  $.ajax({
    method:"POST",
    url:"<?php echo site_url('home/send_chat');?>",    
    data: fd,  
    cache: false,
    contentType: false,
    processData: false,   
    success: function(data){                 
      alert(data);
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }  
  });
});
Sign up to request clarification or add additional context in comments.

Comments

0

try to make ajax code like this.

  var data = new FormData();
  jQuery.each(jQuery('#file')[0].files, function(i, file) {
    data.append('file', file);
  });
  $.ajax({
    type : "POST",
    url : "<?=base_url()?>home/send_chat",
    data : data,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data) {

    }
  });

and your controller make like this it's working code for me

class Home extends CI_Controller {

  function singleImageUpload($upload_name,$folder,$extension,$bnr,$filename)
  {
      if($folder == '')
      {
          $config['upload_path'] = 'images/agent';
      }
      else
      {
          $config['upload_path'] = 'upload/'.$folder."/";
      }
      $config['allowed_types'] = '*';
      if($bnr == 2)
      {
          $config['max_width'] = '3000';
          $config['max_height'] = '3000';
      }
      elseif ($bnr == 1)
      {}
      // $config['file_name'] = $user_name.date('YmdHis').".".$extension;
      $config['file_name'] = $filename;

      $this->upload->initialize($config);
      $this->load->library('upload', $config);
      if ( ! $this->upload->do_upload($upload_name))
      {
          $arrayRetutn['upload'] = 'False';
          $arrayRetutn['error'] = $this->upload->display_errors();
      }
      else
      {
          $arrayRetutn['upload'] = 'True';
          $arrayRetutn['data'] = $this->upload->data();
      }
       //echo '<pre>';print_r($arrayRetutn);echo '</pre>'; die;
      return $arrayRetutn;
  }

  public function send_chat()
  {
    $user    = $this->input->post("user");
    $message = $this->input->post("message");
    $iduser  = $this->input->post("iduser");

    if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '')
    {
        $image_name = explode(".",$_FILES['file']['name']);
        $imgData = $this->singleImageUpload('file','your folder name',$image_name[1],'2',$_FILES['file']['name']);
        if($imgData['upload']=='True')
        {
            $name = $imgData['data']['file_name'];
        }
    }

    $insert="insert into chat (user,message,id_user,fileupload) VALUES ('$user','$message','$iduser','$name')";
    $this->db->query($insert);
  }
}

Comments

0

I think the point @kunal was making was that you should not add potentially sensitive data as hidden inputs ( anyone can change it ) but should reference the values held in those fields directly within your class before adding to the db. In addition using embedded variables opens your app to sql injection so use a prepared statement.

<?php 

    if ( ! defined('BASEPATH')) exit('No direct script access allowed');


    class Home extends CI_Controller {
      public function send_chat(){
        $name    = $_FILES['file']['name'];
        $error   = $_FILES['file']['error'];
        $size    = $_FILES['file']['size'];

        $user    = $this->session->userdata('username');
        $iduser  = $this->session->userdata('userID');
        $message = $this->input->post("message");


        $sql="insert into `chat` ( `user`, `message`, `id_user` ,`fileupload` ) values (?,?,?,?)";
        $stmt=$this->db->prepare( $sql );
        if( $stmt ){
            $stmt->bind_param('ssss',$user,$message,$userid,$name);
            $stmt->execute();
        }
      }
    }

I played around with your original javascript/jQuery code but could not get the function to work ( I don't use jQuery so I was guessing ) but using regular, vanilla javascript you can do it like this ~ the portion of php code at the top is not really relevant as you would be sending the ajax request to home/send_chat

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();
        /* send some sort of response...    */
        echo json_encode( $_POST );

        exit();
    }
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>xhr upload - no jquery</title>
        <script>
            document.addEventListener('DOMContentLoaded',function(){

                var callback=function( data ){
                    alert( data )
                }

                document.getElementById('submit').onclick=function(e){
                    e.preventDefault();
                    var url='<?php echo site_url('home/send_chat');?>';

                    var _file=document.querySelector('input[type="file"]');
                    var _form=document.querySelector('form[id="usr-upload"]');

                    var xhr = new XMLHttpRequest();
                    var fd=new FormData( _form );
                        fd.append('file', _file.files[0]);

                    xhr.onreadystatechange=function(){
                        if( xhr.readyState==4 && xhr.status==200 )callback.call( this, xhr.response );
                    };
                    xhr.onerror=function(err){
                        alert(err);
                    };
                    xhr.open('POST',url,true);
                    xhr.send( fd );
                };
            },false );
        </script>
    </head>
    <body>
        <form id='usr-upload' method='post' enctype='multipart/form-data'>
          <input name='message' type='text' />
          <input type='file' name='usrfile' />
          <br />
          <span class='input-group btn'>
            <input type='button' value='Enkripsi' id='submit' />
          </span>
        </form>
    </body>
</html>

1 Comment

i;m already edit my question. my message still not send. please what my problem :(
0

Submit all the data with or without file using ajax

<form method="post" action="" enctype="multipart/form-data" id="form"/>
   // your own input fields
</form>

$("#form").submit(function (event) {
 event.preventDefault();
 //tinyMCE.triggerSave();
$.ajax({
    url: "<?php echo base_url('your_own_controller/your_own_method'); ?>",
    type: "post",
    data: new FormData(this),
    processData: false,
    contentType: false,
    cache: false,
    async: false,

    beforeSend: function () {}, //if you like to do something before submit
    complete: function () {}, //if you like to do something before submit 

    success: function (response) {
     //check response and do some your own stuff
    };
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.