Have got an HTML and a PHP to upload the image to the server. I have used this same code previously and it works fine but I dont know why it is not working now,
Or its maybe the place where I am using the code is not appropriate. Below are the codes.
HTML to take input from user
<form action ="login.php" method="POST">
<label >USername :</label><br/>
<input type="text" name ="userid" /><br/>
<label >Password :</label><br/>
<input type="password" name="pid" /><br><br/>
<input type="submit" value ="Login" />
</form>
PHP for login.php
<?php
$x = 1;
while($row = mysqli_fetch_array($result)){
echo $x.'<br/>';
?>
//Form to upload the image
<form enctype="multipart/form-data" id="form" action="" method="post">
<input type="file" id="image" name="img" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type="button" value="upload" onclick="javascript:uploadInage();" />
</form>
<script type="text/javascript">
function uploadInage()
{
var file_data = $('#image').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "file.php",
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (result) {
alert(result)
}
});
}
</script>
<?
echo "-------------------------------------------------------".'<br/>';
$x = $x+1;
}
print_r($stores,$stores_add,$stores_chain,$jobs);
}
?>
PHP to upload File
file.php
<?php
$imagePath = "uploads/";
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$filename = $_FILES["file"]["tmp_name"];
$time = time();
move_uploaded_file($filename, $imagePath . $time . '.' . $extension);
echo "File Uploade";
exit;
?>
Kindly tell me why this code doesnt work.
<form enctype="multipart/form-data" id="form" action="" method="post">
<input type="file" id="image" name="img" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type="button" value="upload" onclick="javascript:uploadInage();" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function uploadInage()
{
var file_data = $('#image').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "file.php",
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (result) {
alert(result)
}
});
}
</script>
Thanks to I'am Back.
Just added jquery.min.js and it works completely fine.
Paste this code in login.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
I guess you are using ajax so you have to convert this file to DataUrl to send it by ajax
var fileInput = document.getElementById('YourInputID');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
$("#myTextAreaID").val(reader.result)
}
reader.readAsDataURL(file);
}
});
It will convert your file to data url and before save it on a textarea now you can send it by ajax
to convert it to an image at php script use
convert_data_url($data_url,$idFile,$folder) {
$image = base64_decode(str_replace('data:image/png;base64,','',$data_url));
save_to_file($image,$idp,$size,$pasta);
}
function save_to_file($image,$idFile,$folder) {
if(!file_exists($folder)){
mkdir($folder);
}
$fp = fopen($folder."/".$idFile.".jpg", 'w');
fwrite($fp, $image);
fclose($fp);
}
So you have to use this function convert_data_url($data_url,$idFile,$folder)
where data_url is the image
id idFile is the name that you want
and folder where you want to save it.
Related
Please refer question: Jquery Image Upload in Form with Plugin goes Null
I am trying to submit a form using JQuery Ajax and trying to retrieve in a PHP file and save. for the particular form there are two file inputs.
Image
Note
when I debug using var_dump($_FILES), I was able to see only Note's array but not Image's. for image upload I am using a plugin called FancyUpload, that is what probably causing the issue. below is the form
<form id="form" action="add.php" method="post" autocomplete="off" enctype="multipart/form-data">
<div>
<input aria-label="cxname" id="cxname" name="cxname" class="form-control" placeholder="Name" type="text">
</div>
<div>
<select name="sales" id="sales" class="SlectBox form-control">
<option value='0'>Sales</option>
<?php echo sales(); ?>
</select>
</div>
<div>
<input class="custom-file-input" placeholder="choose note" name="note" id="note" type="file">
<label class="custom-file-label">Choose Note</label>
</div>
<div>
<input class="custom-file-input" placeholder="Choose Image" name="image" id="image" type="file" multiple>
</div>
<div>
<button id="submit" class="btn btn-primary btn-size">Add</button>
</div>
</form>
Jquery Below along with its fancy uploader classes
<!-- JQuery min js -->
<script src="assets/plugins/jquery/jquery.min.js"></script>
<script src="assets/plugins/jquery-ui/ui/widget.js"></script>
<script src="assets/plugins/fancyuploder/jquery.ui.widget.js"></script>
<script src="assets/plugins/fancyuploder/jquery.fileupload.js"></script>
<script src="assets/plugins/fancyuploder/jquery.iframe-transport.js"></script>
<script src="assets/plugins/fancyuploder/jquery.fancy-fileupload.js"></script>
<script>
$(document).ready(function(e){
var image = $('#image').FancyFileUpload({
maxfilesize : 1000000,
params : {
action : 'form'
},
autoUpload: false
});
$("#form").on('submit', function(e){
e.preventDefault();
var fd = new FormData();
fd.append('pimage', $(image)[0].files[0]);
fd.append('deliveryNote', $("#note")[0].files[0]);
fd.append('cxname', $('input[name=cxname]').val());
fd.append('sales', $('select[name=sales]').val());
$.ajax({
type: 'POST',
url: 'add.php',
data: fd,
dataType: 'json',
processData:false,
contentType: false,
cache: false,
async: false,
success: function(response){
$('.statusMsg').html('');
if(response.status == 1){
$('#form')[0].reset();
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>');
alert('received');
}else{
$('.statusMsg').html(alert(response.message));
}
$('#form').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
Retreiving PHP
upload_dir = 'uploads/';
pdf_dir = 'doc/';
if (isset($_POST['cxname']) || isset($_POST['deliveryNote']) || isset($_POST['pimage']) || isset($_POST['sales'])) //even tried with ($_FILES['pimage'])
{
$cxname=$_POST['cxname'];
$sales=$_POST['sales'];
var_dump($_FILES);
//MOVE IMAGE -> Comes Empty
if(!empty($_FILES['pimage']['tmp_name']))
{
$temp = $_FILES['pimage']['tmp_name'];
$name = $_FILES['pimage']['name'];
$result = move_uploaded_file($temp,$upload_dir.$name);
$response['status'] = 1;
$response['message'] = 'IMAGE HAS BEEN SAVED';
}
else{
$name = '';
$response['status'] = 0;
$response['message'] = 'IMAGE CAME EMPTY!';
}
//SAVE NOTE
$_pdfDN = $_FILES['deliveryNote']['name'];
$Tempfile = $_FILES['deliveryNote']['tmp_name'];
$_pdfResult = move_uploaded_file($Tempfile,$pdf_dir.$_pdfDN);
}
If I do without image upload plugin, it works fine. Please advice.
I'm trying to upload a file with formdata. the file alone works, but I need to upload some userdata. I tried to append formdata, but when i "print_r" the array($_FILES) in the php file called by ajax it doesn't appear there.
If someone has a solution for the issue, or a better way to tackle a fileupload with userdata, please let me know!
Below you can find the code used:
php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-1.12.0.min.js"></script>
</head>
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" enctype="multipart/form-data" id="myform">
<input type="text" id="test" value="sample">
<div >
<img src="" id="img" width="100" height="100">
</div>
<div >
<input type="file" id="file" name="file" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
//console.log("piemel");
console.log(document.getElementById('test').value);
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('test', document.getElementById('test').value);
fd.append('file',files);
console.log(fd);
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</html>
Ajax file:
<?php
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "upload/".$filename;
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
echo $location;
}else{
echo 0;
}
I have an example working demo code for this (I was also facing this issue and created this script)
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="uploadForm" action="upload.php" method="post">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type='text' name="my_name" value="harish">
<input type="submit" value="Submit" class="btnSubmit" />
</form>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}
});
}));
});
</script>
upload.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_FILES["userImage"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["userImage"]["name"]);
$file_extension = end($temporary);
$file_type = $_FILES["userImage"]["type"];
if ((($file_type == "image/png") || ($file_type == "image/jpg") || ($file_type == "image/jpeg")
) /*&& ($_FILES["file"]["size"] < 100000)*/ //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions))
{
if ($_FILES["userImage"]["error"] > 0)
{
echo "Return Code: " . $_FILES["userImage"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("uploads/" . $_FILES["userImage"]["name"] . '-'.time()))
{
echo $_FILES["userImage"]["name"] . time() ." <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['userImage']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "uploads/".$_FILES['userImage']['name'].'-'.time(); // Target path where file is to be stored
//check the writable permissions
/*if (is_writeable('uploads/' . $_FILES['userImage']['name'])) {
die("Cannot write to destination file");
}*/
if(move_uploaded_file($sourcePath,$targetPath)) {
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["userImage"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["userImage"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["userImage"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["userImage"]["tmp_name"] . "<br>";
} else {
echo "<pre>"; print_r($_FILES['file']['error']); echo "</pre>";
}
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>
*Create a folder upload on the same level or change the upload path and make sure to give it writable permissions.
This script is working for both data and files, For post data you need to use $_POST['post_input'].
Give this script a go and hope it will help you.
$_FILES is for files not for data as you are sending data by post use $_POST
Hm. are you trying to upload large files? Because when i was messing around with $_FILES, uploading files bigger than 20mb was unsuccessful until i put the maximum file for upload in my IIS to maximum i could of transfer large files. Only thing i could upload without messing with IIS was normal images.
Your code doesnt seem wrong as it has to put the temp file into the location you provided so What are you exactly trying to upload? The folder "upload" that you are using in your code, does it exist? it wont move any files if the folder doesnt exist either
I'm having some difficulties with uploading an image from an html form. the form should be able to send the image name with other data to php page.
I used formData instead of serialized function, since it can't handle files data.
$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:"includes/widgets/insert.php",
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
success: function (data) {
alert(data);
},
});
return false;
});
html form
<form id="insert_post" action="includes/widgets/insert.php" method="post" enctype="multipart/form-data" >
<div class="row">
<div class="medium-6 columns">
<label>First name
<input type="text" name="first_name" id="first_name" contenteditable>
</label>
</div>
<div class="medium-6 columns">
<label>Last name
<input type="text" name="last_name" id="last_name" contenteditable>
</label>
</div>
<div class="medium-12 columns">
<label>Last name
<input type="file" name="file" id="image" multiple contenteditable>
</label>
</div>
</div>
<button type="button" name="btn_add" id="btn_add" class="button btn btn-xs btn-success" >Submit</button>
</form>
php page
<?php
$connect = mysqli_connect("localhost", "root", "", "myaddboard");
echo $_POST['first_name'];
echo $_POST['last_name'];
echo $image = $_FILES['file']['name'];
echo $image_tmp = $_FILES['file']['tmp_name'];
/*
if(empty($image)){
echo 'error';
}
move_uploaded_file($image_tmp,"img/$image");
//$sql = "INSERT INTO posts(post_content, post_author) VALUES('".$_POST["first_name"]."', '".$_POST["last_name"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Data Inserted';
} else {
echo 'error';
}
*/
?>
The php form is just to test if the ajax send the data correctly.
When I click on the button I always get errors that the php variables is not defined
The errors i get each time I submit the form
undefined index: frist_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 4
undefined index: last_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 5
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 8
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 9
what should I do to make the ajax send the data to the php page ?
This won't work because of how your selector is created.
$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);
In the above scenario, $(this)[0] is getting you the raw HTML interpretation of the button.
What you actually want is to change your button to a submit type, capture the form submit event, and then process your request.
button type="submit" <-- change
$(document).on('submit', '#insert_post', function(e){
e.preventDefault(); //stop default form submission
//do the rest of your stuff here
});
Now $(this)[0] is actually the form and not the button.
i am trying to use ajax submit form but for some reason it doesn't work for me, any suggestions how to fix it.
I'm getting the alert message when I submit but it takes me to another page, what am i doing wrong with ajax request ?
<!DOCTYPE html>
<html>
<head>
<title>Get Data From a MySQL Database Using jQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// AJAX forms
$("#search_form").submit(function(e){
e.preventDefault();
//var data = $(this).serialize();
var method = $(this).attr("method");
var action = $(this).attr("action");
var username = $('#username').val();
$.ajax({
url: 'process.php',
type: 'POST',
data: { name: username },
cache: false,
success: function(data){
$('#results').html(data);
}
})
})
});
</script>
</head>
<body>
<span>Search by name: </span>
<form method="POST" action="process.php" id="search_form">
<input type="text" id="username" name="name">
<input type="submit" id="submit" value="Search">
</form>
<div id="results"></div>
</body>
</html>
process.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Check if $_POST is set
if ( empty ( $_POST['name'] ) ) {
echo "Something wrong!";
exit;
}
$name = $_POST['name'];
$m = new MongoClient();
//echo "Connection to database successfully";
// select a database
$address = array(
'name'=>$name,
'city' => 'test',
'state' => 'test2',
'zipcode' => 'test3'
);
$db = $m->local;
//echo "Database mydb selected";
$collection = $db->user;
//echo "Collection selected succsessfully";
$collection->insert($address);
$user = $collection->findOne(array('name' => $name));
?>
<ul>
<li><?php echo $user['name']; ?>: <?php echo $user['city']; ?></li>
<script>
alert('test 1234');
</script>
</ul>
I had to change:
$("#search_form").submit(function(e){
to:
$(document).on('submit', '#search_form', function(){
Now it works fine.
<!DOCTYPE html>
<html>
<head>
<title>Get Data From a MySQL Database Using jQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
// AJAX forms
$(document).on('submit', '#search_form', function() {
//e.preventDefault();
//var data = $(this).serialize();
var method = $(this).attr("method");
var action = $(this).attr("action");
var username = $('#username').val();
$.ajax({
type: 'POST',
url: 'process.php',
data: {
name: username
},
cache: false,
success: function(data) {
$('#results').html(data);
}
})
return false;
});
});
</script>
</head>
<body>
<span>Search by name: </span>
<form method="POST" action="process.php" id="search_form">
<input type="text" id="username" name="name">
<input type="submit" id="submit" value="Search">
</form>
<div id="results"></div>
</body>
</html>
I create a form with PHP and jQuery, I add this in footer of my website, all I need is to display the form results in a popup in the main of my website not in the footer and make this to work without page refresh (with ajax). I add here my entire code:
<form enctype="multipart/form-data" action="" method="post">
<input name="url" type="text"/>
<input type="submit" name="submit" value="Check" class="btn btn-primary"/><br/>
</form>
<?php
if(isset($_REQUEST['submit'])) {
$url = $_REQUEST['url'];
if(substr( $string_n, 0, 7 ) != "http://" && substr( $string_n, 0, 8 ) != "https://")
$url = "http://".$url;
if(stripos($url,"folder/")>0)
$content = file_get_contents($url);
else
$content = file_get_contents($url."/folder/");
if(preg_match("/Copyright ver\. ([0-9.]+)/", $content, $result))
echo "Your year is : ".$result[1];
else
echo "Sorry cannot determine year";
}
?>
EDIT
dont forget to put jquery in top of the html page
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
Check below solution
//this will be your html file
<form id="form1" enctype="multipart/form-data" action="" method="post">
<input name="url" type="text"/>
<input type="submit" name="submit" value="Check" class="btn btn-primary"/><br/>
</form>
<script>
$(function() {
$('#form1').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function(html) {
alert(html);
}
});
});
});
</script>
create a post.php file put your php code
<?php
if (isset($_REQUEST['submit']))
{
$url = $_REQUEST['url'];
if (substr($string_n, 0, 7) != "http://" && substr($string_n, 0, 8) != "https://")
$url = "http://" . $url;
if (stripos($url, "folder/") > 0)
$content = file_get_contents($url);
else
$content = file_get_contents($url . "/folder/");
if (preg_match("/Copyright ver\. ([0-9.]+)/", $content, $result))
echo "Your year is : " . $result[1];
else
echo "Sorry cannot determine year";
}
?>
If you are only using the code provided, you are still missing some AJAX code. As you have used both the jQuery and JavaScript tags, I wasn't sure if you are using Vanilla or jQuery (my example uses jQuery).
My example will make an AJAX request when the user clicks the submit button. $your_url will need to be set to a file which contains your PHP code you specified in the question.
$('#my_button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
text: $('#some_text').val(),
},
url: "<?php echo $your_url; ?>",
success: function(data) {
console.log($data);
}
});
});
<form enctype="multipart/form-data" action="" method="post">
<input name="url" type="text" / id="some_text">
<input type="submit" name="submit" value="Check" class="btn btn-primary" id="my_button" />
</form>
Your PHP will need to be changed so that it works correctly with this AJAX request. As mentioned in the comments, it seems like you do not fully understand how AJAX works, and how it communicates with PHP. I suggest the following documentation and tutorials:
AJAX documentation
AJAX beginners guide