Skip to content

Instantly share code, notes, and snippets.

@mgng
Last active December 31, 2015 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgng/7941571 to your computer and use it in GitHub Desktop.
Save mgng/7941571 to your computer and use it in GitHub Desktop.
jquery + ajax file upload
<form action="javascript:;">
<input type="text" id="status" value="" />
<input type="file" id="file" />
<input type="submit" id="update" value="送信" />
</form>
<script>
$(function(){
$("#update").bind("click", function(){
// FormData オブジェクトを作成
var fd = new FormData();
// テキストデータおよびアップロードファイルが設定されていれば追加
fd.append( "status", $("#status").val() );
if ( $("#file").val() !== '' ) {
fd.append( "file", $("#file").prop("files")[0] );
}
// dataにFormDataを指定する場合 processData,contentTypeをfalseにしてjQueryがdataを処理しないようにする
var postData = {
type : "POST",
dataType : "text",
data : fd,
processData : false,
contentType : false
};
// ajax送信
$.ajax( "./post.php", postData ).done(function( text ){
alert( text );
});
});
});
</script>
<?php
// POSTされた status と アップロードされたファイルパスを返すだけ
$status = isset( $_POST['status'] ) ? $_POST['status'] : null;
$file = isset( $_FILES['file']['tmp_name'] ) ? $_FILES['file']['tmp_name'] : null;
var_dump( $status, $file );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment