I want to upload a file with ajax
here is my code
php, html:
<form action="uploadVideo.php" method="POST" enctype="multipart/form-data">
<input type="file" name="choosefilebtn" id="choosefilebtn" size="50" />
<input type="button" class="uploadbutton" value="upload" name="uploadbtn" id="uploadbtn" />
</form>
jquery:
$(function() {
$('#uploadbtn').click(function() {
var filename = $('#choosefilebtn').val();
alert(filename);
$.ajax({
type: "POST",
url: "uploadVideo.php",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function() {
alert("Data Uploaded: ");
}
});
});
});
when I use type sumbmit for upload button ( without ajax) it works, but with ajax it doesnt work, can any body help me,
Thanks
Edit:
Added uploadVideo.php code
$publish->remotehost=$ftpremotehost;
$publish->username=$ftpusername;
$publish->password=$ftppassword;
$publish->remotedir=CONSTANT_SERVERROOT.$folderName;
$publish->filename=$_FILES['choosefilebtn']['name'];
$publish->FTPLogin();
$publish->filecontent = fread( fopen($_FILES['choosefilebtn']['tmp_name'], "rb"),
$_FILES['choosefilebtn']['size']);
$publish->makedir($publish->remotedir);
$result=$publish->Publish();
You'll notice with the ajax call you are sending the filename, and not the contents of that file:
$.ajax({
//...
data: {
file: filename //just a name, no file contents!
},
//...
});
the only way that I am aware of sending file data via ajax is using a hidden iframe and submitting a form to that
i.e. have
<iframe style="display: none" id="formtarget" />
<form action="uploadVideo.php" method="POST" enctype="multipart/form-data"
target="formtarget">
<input type="file" name="choosefilebtn" id="choosefilebtn" size="50" />
<input type="button" class="uploadbutton" value="upload" name="uploadbtn" id="uploadbtn" />
</form>
markup
<form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
<input name="FileInput" id="FileInput" type="file" />
<input type="submit" id="submit-btn" value="Upload" />
<img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
</form>
<div id="progressbox">
<div id="progressbar"></div>
<div id="statustxt">0%</div>
</div>
<div id="output"></div>
jquery
$(document).ready(function () {
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
success: afterSuccess, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
resetForm: true // reset the form after successful submit
};
$('#MyUploadForm').submit(function () {
$(this).ajaxSubmit(options);
return false;
});
});
Related
When I try to submit my form everything seems to work, but it doesn't actually work when I add the $ _FILES variable to my PHP file.
This is my code and it doesn't work:
action.php
<?php
if (isset($_FILES['logoUp']['name'][$key])){
echo 'success form submit';
}
echo $_POST['test'];
?>
form.html
<form id="co-heared4us-form" name="co-heared4us-form" method="post" enctype="multipart/form-data" autocomplete="off">
<input type="file" id="logoUp" name="logoUp[]" accept=".ai, .pdf, .eps, .svg, image/png, image/jpeg, image/jpg" multiple="multiple"/>
<input type="text" name="test" value="test" id="test" />
<input type="submit" value="send" />
</form>
<script>
$("html").on("submit", "form#co-heared4us-form", function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'action.php',
data: $('form#co-heared4us-form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
</script>
I noticed that if I run the action.php without submit ajax the action.php works correctly even with $ _FILES.
How can i do?
PFB my Html code :
<form id="form" enctype="multipart/form-data">
<label>File One</label>
<input type="file" name="file[]" id="file[]">
<br/>
<label>File Two</label>
<input type="text" id="name" name="name">
<input type="file" name="file[]" id="file[]">
<br/>
<label>File Three</label>
<input type="file" name="file[]" id="file[]">
<input type="submit" id="submit" name="submit" value="Submit">
</form>
I am trying to submit this form using ajax as below :
<script type="text/javascript" >
$(function() {
$('#form').submit(function(event) {
var name = $("#name").val();
var file[] = $("#file[]").val();
var dataString = 'name='+name+'&file[]='+file[];
$.ajax({
type: "POST",
url: "k.php",
data: dataString,
success: function(data123){
alert(data123);
}
});
return false;
});
});
</script>
But its not working. i:e the below line :
var file[] = $("#file[]").val();
var dataString = 'name='+name+'&file[]='+file[];
Any help would be highly useful.
I need to submit multiple photos along with text fields using ajax function but I am stuck in this issue from the past many days.
For uploading files using ajax, you need to do some extra work using the FormData object.
Check out http://blog.teamtreehouse.com/uploading-files-ajax for an example of how to do this.
I am trying to upload a file using ajax which is giving me an error and the rest of data upload successfully i have try without ajax the file is uploading but when i try to upload file via ajax it give me error i am totally confuse why ajax is giving me the problem.here is my code.
<html>
<head>
<script src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button").click(function(){
var form_data = $('#reg_form').serialize();
$.ajax({
type:"POST",
url:"process.php",
data:form_data,
success: function(data)
{
$("#info").html(data);
}
});
});
});
</script>
</head>
<body>
<form id="reg_form" enctype="multipart/form-data" method="post" action="">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
Image : <input type="file" name="file" id="file" />
<input type="button" value="Send Comment" id="button">
<div id="info" />
</form>
</body>
</html>
The process.php file coding is here.
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajaxdatabase");
$name=$_POST["name"];
$message=$_POST["message"];
//storing file in filename variable
$fileName = $_FILES['file']['name'];
//destination dir
$to="image/".$fileName;
move_uploaded_file($_FILES['file']['tmp_name'],$to);
$query=mysql_query("INSERT INTO common(name,message,destination) values('$name','$message','$to') ");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>
First of all serialize() function don't work for file you should have to make an object of form through which you can post the data and will work perfectly I had the same problem and I have just resolved your issue and is working 100% because I have tested this. Please check out.
The form.
<form name="multiform" id="multiform" action="process.php" method="POST" enctype="multipart/form-data">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
Image : <input type="file" name="file" id="file" />
</form>
<input type="button" id="multi-post" value="Run Code"></input>
<div id="multi-msg"></div>
The script.
<script type="text/javascript">
$(document).ready(function(){
$("#multiform").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
if(window.FormData !== undefined)
{
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
$("#multi-msg").html('<pre><code>'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#multi-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault();
e.unbind();
}
});
$("#multi-post").click(function()
{
//sending form from here
$("#multiform").submit();
});
});
</script>
And your php file is the same I have tested and is working.
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajaxdatabase");
$name=$_POST["name"];
$message=$_POST["message"];
//storing file in filename variable
$fileName = $_FILES['file']['name'];
//destination dir
$to="image/".$fileName;
move_uploaded_file($_FILES['file']['tmp_name'],$to);
$query=mysql_query("INSERT INTO common(name,message,destination) values('$name','$message','$to') ");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>
i am using the following code to auto-submit a form
<script type="text/javascript">
$(function () {
$('#submit').click();
});
</script>
<div style="display:none">
<form method="post" action="http://mydomain/texting/register.php?list_id=15">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form>
</div>
i want to submit the same data to two urls ...
http://mydomain/texting/register.php?list_id=15
http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>
how can edit my code to submit same form data automatically?
i tried this code
<script type="text/javascript">
function submitTwice(f){
f.action = 'http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>';
f.target='ifr1';
f.submit();
f.action = 'http://mydomain.com/texting/register.php?list_id=15';
f.target='ifr2';
f.submit();
}
</script>
*/
<script type="text/javascript">
$(function () {
$('submitTwice(f)').click();
});
</script>
<div style="display:none">
<iframe name="ifr1" width="20" height="20">
<form method="post" action="http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form></iframe>
</div>
<div style="display:none"><iframe name="ifr2" width="20" height="20">
<form method="post" action="http://mydomain.com/texting/register.php?list_id=15">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form></iframe>
</div>
but it is not working, any suggestion to make it happen, the same data is to be sent to both the urls automatically using javascript
You can use jQuerys ajax and send the data with post, to both the urls.
first save all data you want to send in an valid data array. if you want it automated, you can do something like this:
var sendData = {};
$("#formId").find("input").each(function(i, item){
sendData[item.name] = item.value;
});
or as a simple string:
var sendData = "name=value&email=value";
then send the form data to both urls with ajax, as post type:
$.ajax({ url: "http://url1/", type: "POST", data: sendData,
success: function(response){
alert(response);
}
});
$.ajax({ url: "http://url2/", type: "POST", data: sendData,
success: function(response){
alert(response);
}
});
Note: make sure to return false to the button or sending form, you can do that something like:
$("formId").submit(function(){
// do ajax send data
return false;
}
EDIT: added unchecked code for this, with comments
$(document).ready(function(){
// grab the form and bind the submit event
$("#formId").submit(function(){
// collect all the data you want to post
var sendData = {};
this.find("input").each(function(i, item){
sendData[item.name] = item.value;
});
// send the request to both urls with ajax
$.ajax({ url: "url1", type: "POST", data: sendData,
success: function(response){
// handle response from url1
alert(response);
}
});
$.ajax({ url: "url2", type: "POST", data: sendData,
success: function(response){
// handle response from url2
alert(response);
}
});
// return false, to disable default submit event
return false;
});
});
just send name and email to the server script in a regular form,
then do two requests from within your register.php with something like HttpRequest or the like...
some freehand code:
client:
<form id="autoSubmitForm" method="post" action="/register.php?list_id=15">
<input type="hidden" name="name" value="<?php data['name2']; ?>" />
<input type="hidden" name="email" value="<?php data['email2']; ?>" />
<input type="submit" name="submit" value="Sign Up" style="visibility:hidden;" />
</form>
<script>
$(document).ready(function(){
$('#autoSubmitForm').submit();
});
</script>
server:
<?php
$name = $_POST["name2"];
$email = $_POST["email2"];
$url1 = 'http://lala'; //or relative to server root: '/lala'
$url2 = 'http://other';
sendRequest($url1, $name, $email);
sendRequest($url2, $name, $email);
?>
The implementation of sendRequest is worth another question (or reading the documentation of HttpRequest mentioned above)
Good luck, I see your duplicate question got closed...
This file index
<form name="classupload" method="post" enctype="multipart/form-data" action="">
<h3>Select pictures: </h3><br />
<input type="file" name="Filedata[]" style="margin-top:2px;"/><br />
<input type="file" name="Filedata[]" style="margin-top:2px;"/><br />
<input type="file" name="Filedata[]" style="margin-top:2px;"/><br />
<input type="file" name="Filedata[]" style="margin-top:2px;"/><br />
<input type="file" name="Filedata[]" style="margin-top:2px;"/><br />
<div id="viac"></div>
<div style="margin-top:4px;"><a onclick="multiupload();">More</a><br /></div>
<input type="submit" value="Upload" id="classupload"/>
</form>
And file javascript
jQuery(document).ready(function() {
$("#classupload").click(function() {
var xleng=document.classupload.elements['Filedata[]'].length;
dv = document.createElement("div");
for (var i = 0; i < xleng ; i++)
{
img=document.classupload.elements['Filedata[]'][i].value;
if(img.toString().length > 1){
$.ajax({
type: "POST",
url: "upload.php",
data: img,
success: function(data_response) {
dv.innerHTML = i + ' - ' + data_response;
}
});
}
}
responseStatus("Done!");
document.getElementById("result").appendChild(dv);
return false; // avoid to execute the actual submit of the form.
})
});
And file upload.php
if ($_REQUEST['Filedata']) {
}
Please help me write file upload.php display file
because Instead of the file being uploaded, I get nothing ,Please HELP ?
You can't upload files via AJAX directly. You need a plug-in that uses a hidden Iframe or makes use of HTML5 features.