Last active
December 31, 2015 05:29
-
-
Save mgng/7941571 to your computer and use it in GitHub Desktop.
jquery + ajax file upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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