I need to upload a file using ajax without refreshing the page. (I tried using form element it works. but it redirects to the other page).
<!DOCTYPE html>
<html>
<head>
<title> Test File Upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file"><br><br>
<button id="submitbtn"> Upload </button>
</body>
<script>
$(document).ready(function(){
$("#submitbtn").click(function(){
var property = document.getElementById('file').files[0];
var formData = new FormData();
formData.append("file", property);
$.ajax({
url: "AjaxPhp.php",
type: "POST",
data: formData,
cache : false,
contentType : false,
processType : false,
dataType: "json",
success: function(testresponse){
if(testresponse.success == true){
alert(testresponse.messages);
} else {
alert(testresponse.messages);
}
}
})
});
});
</script>
</html>
this is my php file... please help :) thank you so much!
<?php
$con = mysqli_connect("localhost", "root", "", "learningdb") or die("connection failed");
if($_POST){
$target_dir = "testupload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){
$sql = "INSERT INTO uploadfile(image) VALUES ('$target_file')";
mysqli_query($con, $sql);
$valid['success'] = true;
$valid['messages'] = "Successfully Uploaded!";
} else {
$valid['success'] = false;
$valid['messages'] = "Something went wrong...";
}
echo json_encode($valid);
}
?>
How do I proceed whith the problem. using Ajax for file upload while avoiding page reload.
To achieve this, prevent normal submission of the form.
Do this:
$("#submitbtn").click(function(e){
e. preventDefault();
If that doesn't work,
Add:
return false;
Just after the Ajax closing brace.
Apologies for the poor formatting. I'm typing via mobile
In AjaxPhp.php file , Use isset other wise ajax will not work.
if(isset($_POST)) {
//code
}
Rest all code is fine. Just add isset and it will solve the problem
#Christian jay Bringino here is how you can fix the issue.
Firstly when you are using var formData = new FormData(); it is very important to have <form> Tag because here i'm using query submit event.
Secondly it is not processType : false, it is actually processData : false,
HERE IS THE FULL ANSWERE
HTML CODE
<!DOCTYPE html>
<html>
<head>
<title> Test File Upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="" method="post" id="file_form">
<input type="file" name="file" id="file"><br><br>
<input type="submit" name="submitbtn" id="submitbtn" value="upload">
</form>
</body>
<script>
$(document).ready(function(){
$("#file_form").submit(function(e){
e.preventDefault();
var property = document.getElementById('file').files[0];
var formData = new FormData($(this)[0]);
formData.append("file", property);
$.ajax({
method: "POST",
url: "AjaxPhp.php",
data: formData,
cache : false,
contentType : false,
processData : false,
dataType:'json',
success: function(testresponse){
if(testresponse.success == true){
alert(testresponse.messages);
} else {
alert(testresponse.messages);
}
}
})
});
});
</script>
</html>
PHP code :AjaxPhp.php
Insisted of if($_POST) use if($_FILES['file']['name'])
Note: If you inserting data given by the user then use MYSQLI PREPARED STATEMENTS against sql injection here is the link click here.
Here are the 2 minor changes I made to script added by #Christian jay Bringino, and it works well .
<!DOCTYPE html>
<html>
<head>
<title> Test File Upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file"><br><br>
<button id="submitbtn"> Upload </button>
</body>
<script>
$(document).ready(function(){
$("#submitbtn").click(function(){
var property = document.getElementById('file').files[0];
var formData = new FormData();
formData.append("file", property);
$.ajax({
url: "AjaxPhp.php",
type: "POST",
data: formData,
cache : false,
contentType : false,
processData : false, //change processType to processData
dataType: "json",
success: function(testresponse){
if(testresponse.success == true){
alert(testresponse.messages);
} else {
alert(testresponse.messages);
}
}
})
});
});
</script>
</html>
AjaxPhp.php (I dont have the table with this database connection so I comment it)
<?php
//$con = mysqli_connect("localhost", "root", "", "learningdb") or die("connection failed");
if(isset($_POST)){ //use isset
$target_dir = "testupload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){
/*$sql = "INSERT INTO uploadfile(image) VALUES ('$target_file')";
mysqli_query($con, $sql);*/
$valid['success'] = true;
$valid['messages'] = "Successfully Uploaded!";
} else {
$valid['success'] = false;
$valid['messages'] = "Something went wrong...";
}
echo json_encode($valid);
}
?>
Related
I was trying to upload file on server using php with jQuery's ajax() function. Below is the code which I was trying. Things worked fine when I wrote PHP code on same page without jQuery, so there is no doubt that file upload is working.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$("form").submit(function(e){
e.preventDefault();
var fd = new FormData();
fd.append("files", $("#fileinput").prop("files"));
$.ajax({
url: "imgupload_.php",
type:"POST",
processData: false,
contentType: false,
data: fd,
success: function(result){
alert(result);
}
});
});
});
</script>
<form method="POST" action="#" enctype="multipart/form-data">
<input type='file' name='files' id="fileinput"/>
<input type='submit' value='Submit' name='submit'/>
</form>
imgupload_.php
if(isset($_POST["submit"])) {
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["files"]["name"]);
if (move_uploaded_file($_FILES["files"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["files"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
If you want any other info please comment below.
You're checking if(isset($_POST["submit"])) but this is not set.
Instead of just this:
var fd = new FormData();
Use this to pull in any non-file input values (such as your submit button.)
var fd = new FormData(this);
I use the code from talkerscode.com to implement file upload using drag and drop. The code is working. Now I would like to add additional input value during in the same ajax post. I add an input tag called "user_id" in the following html code. And I append the element into the formdata object. After the change drag and drop upload still work, but the PHP code complain the $_POST["user_id"] is not defined. Here is my code. Please help!
<html>
<!-- code original from talkerscode.com -->
<head>
<link rel="stylesheet" type="text/css" href="upload_style.css">
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="wrapper">
<input type="text" name="user_id", id="user_id" value="1228">
<input type="file">
<div id="drop-area">
<h3 class="drop-text">Drag and Drop Images Here</h3>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function()
{
$("#drop-area").on('dragenter', function (e){
e.preventDefault();
$(this).css('background', '#BBD5B8');
});
$("#drop-area").on('dragover', function (e){
e.preventDefault();
});
$("#drop-area").on('drop', function (e){
$(this).css('background', '#D8F9D3');
e.preventDefault();
var image = e.originalEvent.dataTransfer.files;
createFormData(image);
});
});
function createFormData(image)
{
var formImage = new FormData();
formImage.append('userImage', image[0]);
formData.append('user_id', $('#user_id').val());
uploadFormData(formImage);
}
function uploadFormData(formData)
{
$.ajax({
url: "upload_image.php",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData: false,
success: function(data){
$('#drop-area').html(data);
}});
}
</script>
----------------PHP code -------------------
<?php
if(is_array($_FILES))
{
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$sourcePath = $_FILES['userImage']['tmp_name'];
$targetPath = "images/".$_FILES['userImage']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
?>
<img src="<?php echo $targetPath; ?>">
<p> user_id = <?php echo $_POST["user_id"] ?> </p>
<?php
exit();
}
}
}
?>
-----------------------------------------------
function createFormData(image) {
var formImage = new FormData();
formImage.append('userImage', image[0]);
formData.append('user_id', $('#user_id').val()); //change formData to formImage
uploadFormData(formImage);
}
From:
formData.append('user_id', $('#user_id').val());
to:
formImage.append('user_id', $('#user_id').val());
As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>
I've made two pages, each one with a form sending a selected image to localhost through a ajax script pointing to a save.php (containing the code to rename, realocate, and update MySQL with the destination folder/filename.
The first form works fine. But when the second page loads and the file is selected, nothing more happens. Like I was unable to use the $_FILES variable twice.
Here the html of the first page (The second one is the same, but I changed the f_chassi to f_nmotor.
$(document).ready(function(){
$("#btn").on('click', function(){
var data = new FormData();
data.append('f_chassi', $('#f_chassi')[0].files[0]);
$.ajax({
url: 'salvar.php',
data: data,
processData: false,
contentType: false,
type: 'POST',
});
});
});
function filePreview(input) {
if (input.files) {
var reader = new FileReader();
reader.onload = function (e) {
$('#fotoPreview + img').remove();
$('#fotoPreview').before('<center><img src="'+e.target.result+'" width="75%"/></center>');
}
reader.readAsDataURL(input.files[0]);
}
}
$("#f_chassi").change(function () {
filePreview(this);
});
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<body>
<div id="wrapper">
<div class="titulo">O.S. <?php echo $_SESSION['novaOS']; ?></div>
<div id="novaos">
<div class="subtitulo">
<?php
echo "Placa: <i>".$_SESSION['placa']."</i>";
?>
</div>
<div class="subtitulo">FOTO CHASSI</div>
<form method="post" enctype="multipart/form-data" id="fotoPreview" action="fotoNumMotor.php">
<input type="file" name="f_chassi" id="f_chassi" accept="image/*" capture="camera">
<button type="button" id="btn">SALVAR</button>
<div>
<input type="submit" value="PRÓXIMA">
</div>
</form>
</div>
</div>
</body>
Here is the save.php code:
<?php
if (!empty($_FILES['f_chassi'])){
$dir_img = "../uploads/fotos/";
$prefix = time()."_";
$fn = $prefix."chassi_".$_FILES['f_chassi']['name'];
$src = $dir_img.$fn;
move_uploaded_file ($_FILES['f_chassi']['tmp_name'], $src);
$chassi = $src;
mysql_query ("UPDATE imagens SET chassi='$chassi' WHERE idp='".$_SESSION['novaOS']."'");
}
if (!empty($_FILES['f_nmotor'])){
$dir_img = "../uploads/fotos/";
$prefix = time()."_";
$fn = $prefix."nmotor_".$_FILES['f_nmotor']['name'];
$src = $dir_img.$fn;
move_uploaded_file ($_FILES['f_nmotor']['tmp_name'], $src);
$nmotor = $src;
mysql_query ("UPDATE imagens SET nmotor='$nmotor' WHERE idp='".$_SESSION['novaOS']."'");
}?>
I solved the problem changing the script to this:
<script type="text/javascript">
$(function(){
$('form').submit(function(){
var dados = new FormData();
dados.append('fotoNumMotor', $('#f_nmotor').prop('files')[0]);
$.ajax({
url: 'salvar.php',
data: dados,
type: 'POST',
processData: false,
cache: false,
contentType: false
});
});
});
</script>
Also, thanks to #JeremyHarris for calling my attention to the .append variables.
I have the most simple case of image upload. When I run this as a separate example it DOES work. When I incorporate the same .js code into my project's javascript code, and try the upload from my html page (.js and .php codes identical, id's and names adjusted etc.), it doesn't work.
html:
<html>
<head>
<title>HTML5 File API</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="main">
<h1>Upload Your Images</h1>
<input type="file" name="images" id="images"/>
<input type="submit" id="submitImages" onclick="submitImages()">
<div id="response"></div>
<ul id="image-list">
</ul>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="upload.js"></script>
</body>
</html>
javascript:
function submitImages(){
if (window.FormData) {
formdata = new FormData();
}
file = document.getElementById('images').files[0];
if (!!file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images[]", file);
}
}
if (formdata) {
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
console.log(res);
}
});
}
}
php:
<?php
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
}
}
echo "<h2>Successfully Uploaded Images</h2>";
?>
The message I get from server when I attempt the upload from my project:
POST-->POST:
Source
-----------------------------2656620091882 Content-Disposition: form-data; name="images[]"; filename="dock_2.jpg" Content-Type: image/jpeg ÿØÿáa"Exif��MM�*��
etc.
POST-->RESPONSE:
<br />
<b>Notice</b>: Undefined index: images in <b>C:\XAMPP\htdocs\Projects\DockMapper\add_edit_upload_images.php</b> on line <b>3</b><br />
<br />
<b>Warning</b>: Invalid argument supplied for foreach() in <b>C:\XAMPP\htdocs\Projects\DockMapper\add_edit_upload_images.php</b> on line <b>3</b><br />
<h2>Successfully Uploaded Images</h2>
It seems that something is sent to the server, but that it is not received on the server. When I run: print_r($_FILES); the array is empty. I spent probably two days over this and I couldn't find the problem. Any suggestions? Big thanks.
Use this
For example
Jquery
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data)
alert(form_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
alert(data);
}
});
});
PHP
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Ok, this was the issue:
In my project's html file, jquery was included inside the HEADER with these lines:
<head>
...
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
...
</head>
It worked when I deleted those lines, and included ONLY the following ajax library, inside the FOOTER:
<html>
<body>
...
</body>
...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
...
</html>