I'm working with Ajax, PHP.
I want to upload an image without clicking the submit button and I'm using the approach described in this answer: How to upload file using jquery ajax and php (without clicking any submit button)
But it's not working. Do I need to change the data type or something else?
Here's my code:
jQuery/Ajax
$(document).ready(function(){
var b = new FormData($(this).closest("form")[0]);
b.append('image', $('input[type=file]')[0].files[0]);
$("#imgInput").change(function(){
$.ajax({
url: "test.php",
type: "post",
datatype: 'json',
processData: false,
contentType: false,
data: b,
success: function(text){
if(text== "success"){
alert("Image uploaded");
}
},
error: function(){
alert("Not uploaded");
}
});
});
});
test.php
<?php
$filename=$_FILES["image"]["name"];
$filetmp=$_FILES["image"]["tmp_name"];
$filetype=$_FILES["image"]["type"];
$filepath="images/".$filename;
move_uploaded_file($filetmp, $filepath);
?>
HTML
<form name="form1" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input type="text" name="name" placeholder="Enter your name" /></td>
<td rowspan="3"><div class="propic"><img id="" /></div>
<input id="imgInput" type="file" name="image" /></td>
</tr>
<tr>
<td><input type="text" name="username" placeholder="Enter username"/></td>
</tr>
<tr>
<td><input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no."/></td>
</tr>
<tr>
<td><input type="password" name="password" maxlength="12" placeholder="Enter password"/></td>
<td><input id="button" type="submit" name="submit" value="Sign Up" /></td>
</tr>
</table>
</form>
You need to use FormData() to send files to server through AJAX. Change your script to:
$.ajax({
url: "test.php",
type: "POST",
data: new FormData($(this).closest("form")[0]), // This is the main place you need.
contentType : false,
async: false,
processData: false,
cache: false,
success: function(text) {
if(text== "success"){
alert("Image uploaded");
}
}
});
If you are just looking to get it working, I recommend Ravishanker Kusuma's Hayageek jQuery File Upload plugin. I don't usually recommend plugins, but this one is excellent. It does almost all the work for you.
http://hayageek.com/docs/jquery-upload-file.php
He breaks down the process into four simple steps, that basically look like this:
Look for //1 //2 //3:
<head>
// (1) Load the js files (note that it requires jQuery, which we also load)
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script> // (1)
</head>
<body>
<div id="fileuploader">Upload</div> // (2) Create DIV
<script>
$(document).ready(function(){
$("#fileuploader").uploadFile({ // (3) initialize plugin
url:"my_php_processor.php",
fileName:"myfile"
});
});
</script>
</body>
The final (fourth) step is to create a PHP file with same name as specified above in the jQuery code (in this case my_php_processor.php) to receive and process the file:
my_php_processor.php:
<?php
$output_dir = "uploads/";
$theFile = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename myfile specified in the jQuery code block.
On the Hayageek web page, study the upload.php example on the Server tab.
Note that you can also pass additional variables to the my_php_processor.php processor file by using dynamicFormData. See this other example:
$("#fileuploader").uploadFile({
url:"my_php_processor.php",
fileName:"myfile",
dynamicFormData: function(){
return {
//my_php_processor.php will receive POST vars below
newSubj: $("#newSubj").val(),
newBody: $("#newBody").val(),
};
},
onSuccess:function(files,data,xhr,pd){
//files: list of files
//data: response from server
//xhr : jquery xhr object
alert(xhr.responseText); //displays data ECHOd by `my_php_processor.php`
}
});
my_php_processor.php:
<?php
$n = $_POST['newSubj'];
$b = $_POST['newBody'];
$uploadedFile = $_FILES["myfile"]["name"];
//etc.
echo 'This will display in the alert box';
jsFiddle Sample Code -
Click on Image Example
Related
My code is a form where it picks a file from the user, then send the data using jQuery to a PHP file where it gets the image content and displays it and in a success function: it alerts the data received from the PHP file. For example, the image received from the HTML page.
Actually, the code inserts the image into the database, but I plucked the code out and inserted a direct view of image in PHP file without inserting in the database because I wanted to make it short(database insertion code has no error: it inserts other variables provided with image and image stays blank)
Also am using my script on XAMPP localhost. So do not worry about that i am running it like file://... . All is that i can't figure out why the data aren't being passed to php file.
HTML:
<input style="border:none" type="file" id="photo" /> <br>
JavaScript:
$("#submit-form").click(function() {
var formadata = {
"photo": $("#photo").val(),
};
$.ajax({
url: './enter-registration-form.php',
data: formadata,
cache: false,
contentType: false,
processData: false,
method: 'POST',
success: function(val) {
if (val == "done") {
alert("Data Accepted");
} else {
alert(val);
}
}
});
});
PHP:
$i = $_FILES['photo']['name'];
//get the content of the image and then add slashes to it
$imagetmp=addslashes (file_get_contents($_FILES['photo']['tmp_name']));
echo '<img src="data:image/jpeg;base64,'.base64_encode($imagetmp).'" style="width:100px;height:autoborder:none">';
Now I am getting this error message:
Notice: Undefined index: photo in
/opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 5
Notice: Undefined index: photo in
/opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 8
Warning: file_get_contents(): Filename cannot be empty in
/opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 8
I can't figure out why this error is thrown.
Approach
You need to use new FormData() object.
The FormData interface provides a way to easily construct a set of
key/value pairs representing form fields and their values, which can
then be easily sent using the XMLHttpRequest.send() method. It uses
the same format a form would use if the encoding type were set to
"multipart/form-data".
So you don't actually have to declare a form tag and add inputs inside, yes it makes it easier if you have let us make a call assuming that you do not have a form tag.
Problem
The problem in your script is that your formdata is a json rather than a FormData() interface object, which uses formdataObject.append() which appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
See code below which posts email, file label and a file to a PHP page without using form tag for the inputs.
Without <form> tag
Assuming that your html looks like below without a form
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="file" name="file" required />
<input type="button" name="submit" value="Stash the file!" />
Your javascript code will look like below
$(document).ready(function () {
$("input[name='submit']").on('click', function (event) {
event.preventDefault();
//START Append form data
var data = new FormData();
data.append(
'userid', $("input[name='userid']").val());
data.append(
'label', $("input[name='filelabel']").val()
);
data.append('file', $("input[name='file']")[0].files[0], 'somename.jpg');
//END append form data
$.ajax({
type: "POST",
url: "file.php",
data: data,
processData: false,
contentType: false,
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
});
});
And your file.php will look like below
<?php
print_r($_POST);
print_r($_FILES);
This should show you the file inputs and file both of them in the console when you hit the stash file button.
With <form> tag
If you have the inputs wrapped inside the form tag then your code will be changed on the following sections
Change binding of click event to form submit event.
Change button type to submit in the HTML.
Get the form object.
Use form object to initialize the FormData().
See below How your HTML will look like
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="file" name="file" required />
<input type="submit" value="Stash the file!" />
</form>
And your javascript will look like below
$(document).ready(function () {
$("form").on('submit', function (event) {
event.preventDefault();
var form = this;
var data = new FormData(form);
$.ajax({
type: "POST",
url: "file.php",
data: data,
processData: false,
contentType: false,
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
});
});
This should work!
HTML:
<form id="my-upload-form" method="post" enctype="multipart/form-data">
<input type="file" name="required-image" />
<button> Upload </button>
</form>
JS:
$("button").click(function(e) {
/* prevent default form action */
e.preventDefault();
/* get form element */
var formElement = document.getElementById("my-upload-form");
/* collect all form data from Form element */
var formData = new FormData(formElement);
$.ajax({
url: '/path-to-form-handler.php',
data: formData,
cache: false,
contentType: false,
processData: false,
method: 'POST',
success: function(response) {
console.log(response);
}
});
});
PHP:
<?php
/* for this example, $_FILES["required-image"] would be an array having image details */
echo $_FILES["required-image"]["name"];
echo $_FILES["required-image"]["type"];
echo $_FILES["required-image"]["tmp_name"];
echo $_FILES["required-image"]["size"];
?>
First of all insert your input file tag in a form and use enctype="multipart/formdata"
to send an image otherwise you will not able to send image
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to validate individual text field and input type="file" field using onblur and onchange. I am using AJAX, jQuery, PHP in this code. Please help me to resolve this.
AJAX code:
function validate()
{
var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
var other_data = $('#user_details').serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: "validate.php",
type: "POST", // Type of request to be send, called as method
data: fd, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function(data) { $("#firstname").html(data); },
failure: function(errormsg) { console.log(errormsg); }
});
}
HTML code:
<form id="user_details" method="post" enctype="multipart/form-data">
<table>
<tr><td>First Name</td><td><input type="text" id="first_name" name="firstname" onblur="validate()"></td><td id="firstname"></td></tr>
<tr><td>Last Name</td><td><input type="text" id="last_name" name="lastname" onblur="validate()"></td><td id="lastname"></td></tr>
<tr><td>Upload File</td><td><input type="file" id="file_name" name="file" onchange="validate()"></td><td id="file"></td></tr>
<tr><td><input type="submit" value="Submit"></td></tr>
<table>
</form>
Try the following code. simple ajax file uploading and php valiadation its working fine check and let me know
<!DOCTYPE html>
<html>
<head>
<title>test2</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<?php
if(isset($_GET['ajaxcall'])){
$data=array();
if(!isset($_FILES['file_name']['name']) || $_FILES['file_name']['name'] == ""){
$data[]['msg']="File is required";
}
if(!isset($_POST['firstname']) || $_POST['firstname']==""){
$data[]['msg']="First name is required";
}
if(!isset($_POST['lastname']) || $_POST['lastname']==""){
$data[]['msg']="Last name is required";
}
echo json_encode($data);
exit();
}
?>
<form id="user_details" method="post" enctype="multipart/form-data">
<table>
<tr><td>First Name</td><td><input type="text" id="first_name" name="firstname" onblur="validate()"></td><td id="firstname"></td></tr>
<tr><td>Last Name</td><td><input type="text" id="last_name" name="lastname" onblur="validate()"></td><td id="lastname"></td></tr>
<tr><td>Upload File</td><td><input type="file" id="file_name" name="file_name" onchange="validate()"></td><td id="file"></td></tr>
<tr><td><input type="button" value="Submit" value="1"></td></tr>
<table>
</form>
<script type="text/javascript">
function validate()
{
var fd = new FormData(document.getElementById("user_details"));
$.ajax({
url: "stack2ajaxfile.php?ajaxcall=1",
type: "POST", // Type of request to be send, called as method
data: fd, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function(data) { $("#firstname").html(data); },
failure: function(errormsg) { console.log(errormsg); }
});
}
</script>
</body>
</html>
I am trying to upload a file with ajax and php without page refresh and for submit.
my code is able to run and alert the valid message if I just do the preg_match, but when I add the rest of the validation which need to use the $_FILES[$filrec]["tmp_name"], it won't alert me the valid message.
What is wrong here? isn't it possible to upload the file without submitting the form with the following method?
There are bunch of different suggestions and examples with more complicated javascript or jquery methods, but I am trying to simply the ajax and leave the rest for PHP. is that possible with my bellow ajax function ?
Javascript :
var fileselected = $("#browse").val().replace(/C:\\fakepath\\/i, '');
setTimeout(function() {
$.ajax({
type: 'POST',
url: "ajax/extval.php",
data: {fileprs: fileselected},
dataType: 'json',
cache: false,
success: function(resuval) {
// file validation result
if (resuval === "valid"){
alert ("valid")
PHP :
<form id="upload" method="post" class="<?php echo $orvalue."<separator>".$user_id ?>" action="" enctype="multipart/form-data">
<div id="formcontent">
<label class="required" for="unitprice" title="Unit price"><input type="text" id="unitprice" name="unitprice" />Unit price</label>
<label class="required" for="qty" title="How many pcs"><input type="text" id="qty" name="qty" />Quanity</label>
<label class="required" for="express" title="Express within China"><input type="text" id="express" name="express" />Express</label>
<label class="required" for="linkURL" title="Insert a full URL http:\\"><input type="text" id="linkURL" name="linkURL" />Link</label>
<label for="yourdesc" title="Describe your need clearly"><textarea id="yourdesc" name="yourdesc"></textarea>Description<li><font size="-2">You can type 400 letters only, you typed :</li><li id="lettercounter"></li>letters</font></label>
<label for="formsubmit" class="nocontent"><input type="button" id="submitButton" href="#" class="progress-button" value="Add to order" /><strong>Note:</strong> Items marked <img src="../../images/required.jpg" alt="Required marker" width="20" height="20" /> are required fields</label>
</div>
</form>
PHP :
$filrec =mysql_real_escape_string($_POST['fileprs']);
if(preg_match("/\.(gif|png|jpg|JPG|jpeg|bmp|BMP)$/", $filrec))
{
$fileType = exif_imagetype($_FILES[$filrec]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
$allin = "valid";
echo json_encode($allin);
}
Appreciated
You can use the following PHP code to get the file received from Ajax:
$data = split(",",file_get_contents('php://input'));
$img_data = base64_decode($data[1]);
file_put_contents( 'uploads/' . $_SERVER['HTTP_X_FILENAME'],
$img_data );
You can use Following Ajax POST Request this will help you
<script>
$(document.body).on('click','.postDefects',function(){
var form_data = new FormData();
var defect = $(this).closest('tr').find( "input[name='defect_id']" ).val();
var txt_defect=$("#text_defect").val();
var upload_defect = document.getElementById("upload_defect").files[0];
form_data.append("upload_defect",upload_defect);
form_data.append("defect_id",defect_id);
form_data.append("txt_defect",txt_defect);
console.log(form_data);
$.ajax({
url:"postsample_defects.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading..</label>");
},
success:function(data)
{
$('#uploaded_image').html(data);
}
});
});
</script>
at the first , excuse me for my bad english
i working in ubuntu for a jquery/ajax system
my codes in below:
index.html
...
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
</head>
<body>
<form name="stuSelForm" id="stuSelForm">
<table id="inputTable">
<tr><td colspan="3" align="center">Stu From</td></tr>
<tr>
<td> </td>
<td>St No : </td>
<td><input type="text" name="StNo" id="StNo" /></td>
</tr>
<tr>
<td></td>
<td>name : <br/> family : </td>
<td><input type="text" name="Fname" id="Fname" /><br/><input type="text" name="Lname" id="Lname" /></td>
</tr>
<tr>
<td colspan="3" align="right"><input type="submit" id="send" name="send" value="show" /></td>
</tr>
</table>
</form>
</body>
<script type="text/javascript" src="js/jscodes.js"></script>
...
js file :
$(document).ready(function()
{
$('#stuSelForm').submit(function(event)
{
var form = $(this);
inputs = form.find("input");
serializedData = form.serialize();
inputs.attr("disabled","disabled");
$.ajax({
url:'process.php',
type:'POST',
data: serializedData,
dataType:'text',
cache: false,
success : function(data,textStatus,jqXHR){ alert(data); },
error : function(jqXHR,textStatus,errorThrown) { alert(textStatus+jqXHR.status+jqXHR.responseText+"..."); },
complete : function(jqXHR,textStatus)
{
inputs.removeattr("disabled");
}
});
event.preventDefault();
});
});
and process.php :
<?php
header("Content-Type: text/html");
$StNo = $_POST['StNo'];
echo $_POST['StNo'];
?>
now all things are ok but the return value isn't StNo
it is whole content of process.php
it's mean
please help me why this happen
are this for php extensions or a mistake from me or ...
tanx for ur help
It sounds like the php is not running. Are you running your HTML file which calls the php file through localhost / a server or directly from the directory? You need the php server to evaluate your php script.
problem in your header:
you write in jquery dataType: text but you write in php header("Content-Type: text/html");
change it for get success:
like this:
$.ajax({
url:'process.php',
type:'POST',
data: serializedData,
cache: false,
success : function(data,textStatus,jqXHR){ alert(data); },
error : function(jqXHR,textStatus,errorThrown) { alert(textStatus+jqXHR.status+jqXHR.responseText+"..."); },
complete : function(jqXHR,textStatus){inputs.removeattr("disabled");}
});
I remove dataType:, because jquery default settings is dataType:'html'
and you don't need write dataType in this case
I have got this html/php in my index.php
if (isset($_POST['UploadMSub'])) {
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)) {
if ($fileP_error===0) {
if ($fileP_size<=2097152) {
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
$_SESSION['fileP']=$fileP;
$_SESSION['fileP_name']=$fileP_name;
$_SESSION['fileP_tmp']=$fileP_tmp;
$_SESSION['fileP_size']=$fileP_size;
$_SESSION['fileP_error']=$fileP_error;
$_SESSION['fileP_extension']=$fileP_extension;
$_SESSION['fileP_new_name']=$fileP_new_name;
}
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" type="text" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
And this ajax
$(".UploadMSub").click(function() {
var text=$(".Text").val();
var file=$("#Nameupload").val();
$.ajax({
type: "GET",
url: '../connect.php',
data: "Text=" + text+"&&file="+file,
success: function(data)
{
alert(data);
}
});
return false;
});
connect.php
if (isset($_GET['Text'])) {
$Text=htmlspecialchars($_GET['Text'],ENT_QUOTES);
$file=htmlspecialchars($_GET['file'],ENT_QUOTES);
echo $Text." ".$_SESSION['fileP_new_name'];
}
But when i submit form it returns(alerts)
"Undefine index ''fileP_new_name'"
Is there any other way of getting all information about file in my connect.php?
The problem is,
When you hit the submit button, the form doesn't get submitted, which means none of your session variables are set when you hit the submit button. Instead jQuery script runs straight away when you hit the submit button, and that's why you're getting this error,
Undefine index: fileP_new_name
From your question,
Is there any other way of getting all information about file in my connect.php?
So the solution is as follows. You have to change few things in your code, such as:
Add a name attribute in your <textarea> element, like this:
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
Instead of returning false from your jQuery script, use preventDefault() method to prevent your form from being submitted in the first place, like this:
$(".UploadMSub").click(function(event){
event.preventDefault();
// your code
});
If you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
Set the following options, processData: false and contentType: false in your AJAX request. Refer the documentation to know what these do.
So your code should be like this:
HTML:
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
jQuery/AJAX:
$(".UploadMSub").click(function(event){
event.preventDefault();
var form_data = new FormData($('form')[0]);
$.ajax({
url: '../connect.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data){
alert(data);
}
});
});
And on connect.php, process your form data like this:
<?php
if(is_uploaded_file($_FILES['Upload_f']['tmp_name']) && isset($_POST['new_post'])){
// both file and text input is submitted
$new_post = $_POST['new_post'];
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)){
if ($fileP_error===0) {
if ($fileP_size<=2097152){
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
// your code
//echo $fileP_new_name;
}
?>