javascript - How to echo value input type text when use ajax upload? -
how echo value input type text when use ajax upload ?
this code upload file dir attachments_files
, it's work good.
but have issue. want know how echo value id="username_uploader"
in upload.php
using php ?
i tried use this
echo $_post['username_uploader'];
but not work. please me .
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <input id="username_uploader" type="text" name="username_uploader" value="test_user"/> <input id="attachment_file_input_id" type="file" name="sortpic" onchange="test_fn()"/> <div id="demoajax"></div> <script> function test_fn () { var file_data = $('#attachment_file_input_id').prop('files')[0]; var form_data = new formdata(); form_data.append('file', file_data); $.ajax({ url: 'upload.php', datatype: 'text', cache: false, contenttype: false, processdata: false, data: form_data, type: 'post', success: function(php_script_response){ alert("upload success"); $('#demoajax').append(php_script_response); } }); }; </script>
upload.php
<?php if ( 0 < $_files['file']['error'] ) { echo 'error: ' . $_files['file']['error'] . '<br>'; } else { move_uploaded_file($_files["file"]["tmp_name"], "attachments_files/" .$_files["file"]["name"]); echo $_post['username_uploader']; } ?>
you need include username_uploader
value in formdata
send, omit it. try this:
var form_data = new formdata(); form_data.append('file', file_data); form_data.append('username_uploader', $('#username_uploader').val());
it better practice php code return json, way don't need worry formatting or whitespace in returned value. here's complete example:
function test_fn () { var form_data = new formdata(); form_data.append('file', $('#attachment_file_input_id').prop('files')[0]); form_data.append('username_uploader', $('#username_uploader').val()); $.ajax({ url: 'upload.php', type: 'post', datatype: 'json', cache: false, processdata: false, data: form_data, success: function(response){ alert("upload success"); $('#demoajax').append(response.uploader); } }); };
<?php if (0 < $_files['file']['error']) { echo json_encode(array('error' => 'error: ' . $_files['file']['error'] . '<br>')); } else { move_uploaded_file($_files["file"]["tmp_name"], "attachments_files/" .$_files["file"]["name"]); echo json_encode(array('uploader' => $_post['username_uploader'])); } ?>
Comments
Post a Comment