2017-12-16 11 views
2

ajax経由でphpファイルのアップロードとajaxでデータを送信することはできません。 This my code just send file upload。データは私のPHPコードに送信されません。私はフォームを作成し、関数はphpに投稿するためにajaxを使用してクリックして送信します。 I'm using codeigniterphp jquery ajaxでファイルをアップロードしてデータを挿入する方法

この私形式:

<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> 

AJAXを使用してPHPにポストを送信するためにこのJavaScript:

$('#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); 
    } 
    }); 
}); 

私はすでに$_POST['message'];を使用して試してみて、$this->input->post("message");その両方 このPHPに動作していませんよ処理コード:

<?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); 
    } 
} 

データベースでは、私はちょうど送信していない名前のファイルupload.user、メッセージ、およびiduserを送信しています。

+1

それにメッセージ変数を追加してみてください、私のメッセージはにキャプチャすることはできません@kunalその – kunal

+0

のセッションを使用して隠されたフィールドのデータを送信しないようにしてください。このメッセージは非表示フィールドではありません – Stfvns

+0

あなたはuseridとメッセージを隠しフィールドに渡していますか、auth componenetを使うかセッションを使うことができますか?隠しフィールドでuseridを直接渡すことはできません。あなたが理解し、将来のコード化に役立つことを願っています – kunal

答えて

1

にAJAXリクエストを送信されるように上部のPHPコードの部分は実際には関係ありません私はあなたがFORMDATAオブジェクトを使用しているので、あなたの問題はAjaxコード であってもよいと思います。

$('#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); 
    } 
    }); 
}); 
+0

よろしくお願い致します!それは働く!!!!! – Stfvns

0

このようなajaxコードを作成しようとします。

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) { 

    } 
    }); 

とあなたのコントローラが、それは私

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); 
    } 
} 
0

ためのコードを働いている。このようにする私は(誰がそれを変更することができ@kunalを作っていたポイントは、あなたが隠された入力として潜在的に機密データを追加してはならないことだったと思います)、dbに追加する前にクラス内のフィールドに保持されている値を直接参照する必要があります。さらに、埋め込み変数を使用すると、アプリをSQLインジェクションに開くので、準備されたステートメントを使用します。

<?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(); 
     } 
     } 
    } 

私は〜しかし、あなたはこのようにそれを行うことができますJavaScriptの正規、バニラを使用して(私は、私が推測されたjQueryのを使用していない)元のJavaScript/jQueryのコードで遊んが、機能は動作させることができませんでしたあなたは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> 
+0

私はすでに自分の質問を編集しています。私のメッセージはまだ送信されません。どうか私の問題:( – Stfvns

関連する問題