I have some working code but want to add upload image field but with no success.
My current code is:
Form:
<form id="add_product_form" enctype="multipart/form-data">
<input id="uploadFile" type="file" name="image" class="img" /><br />
<input id="status" type="checkbox" checked /><br />
<input id="product" type="text" /><br />
<label for="button" id="response"></label>
<input type="button" id="button" value="Добави" /><br />
</form>
jQuery:
<script type="text/javascript">
$('document').ready(function(){
$('#button').click(function(){
var image = $('input[type=file]').val().split('\\').pop();
function chkb(bool){ if(bool) return 1; return 0; } var status=chkb($("#status").is(':checked'));
if($('#product').val()==""){ alert("enter name"); return false; } else { var product = $('#product').val(); }
jQuery.post("products_add_process.php", {
image: image,
status: status,
product: product
},
function(data, textStatus) {
$('#response').html(data);
if(data == 1){
$('#response').html("OK");
$('#response').css('color','green');
document.getElementById("add_product_form").reset();
} else {
$('#response').html("Not OK");
$('#response').css('color','red');
}
});
});
});
</script>
products_add_process.php:
<?php
$image_name = $_FILES['image']['name'];
$image_type = $_FILES['image']['type'];
$image_size = $_FILES['image']['size'];
$image_tmp_name = $_FILES['image']['tmp_name'];
$status = $_POST['status'];
$product = $_POST['product'];
if($image_name == '') {
echo "<script>alert('Select image')</script>";
exit();
} else {
$random_digit=rand(0000000000,9999999999);
$image=$random_digit.$image_name;
move_uploaded_file($image_tmp_name,"uploads/$image");
$query=mysql_query("INSERT INTO products(product, image, status) VALUES ('$product', '$image', '$status')");
if(mysql_affected_rows()>0){
$response = 1;
echo "1";
} else {
$response = 2;
echo "2";
}
}
?>
I put alert 'Select image' and then understand that $image_name is empty and maybe somewhere have to put some code to say that I want to send DATA TYPE. I try to add to form enctype="multipart/form-data" but won't work.
Where and what have to add in existing code to make sending data, without making very big changes because this code have in a lot of files and will be difficult to edit big part of codes.
Maybe have to add that form and jQuery are in php file which is called in other mother file and structure is something like this:
products.php /call products_add.php/
products_add.php /where is the form and jQuery/
products_add_process.php /called from products_add.php to upload data/
p.s. Sorry if I don't explain my problem well but I'm from soon at stackoverflow and still learning how to post my questions :)
Related
I am trying to create a facebook like status update where I want a user to be able to upload images exactly like facebook does. I have the following codes which allows a user to upload and preview images and remove them by clicking on a 'X' button.
HTML Form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server" enctype="multipart/form-data">
<textarea name="status" class="textarea newstatuscontent" placeholder="What are you thinking?"></textarea>
<input type="file" name="files[]" multiple="multiple" id="file-5" class="inputfile inputfile-4">
<div id="imgs"></div> // images preview and container
<input type="submit" name="post" value="Post" class="post-btn" id="submit" />
</form>
Ajax code to insert data to the database:
$(function() {
$("#submit").click(function() {
$(this).val("Please wait...");
var textcontent = $(".newstatuscontent").val();
/*if(media == ''){*/
if(textcontent == ''){
$('.cap_status').html("Status cannot be empty. Please write something.").addClass('cap_status_error').fadeIn(500).delay(3000).fadeOut(500);
$("#submit").val("Post");
}else{
/*}else{*/
$.ajax({
type: "POST",
url: "post-status.php",
data: {content:textcontent},
cache: true,
success: function(html){
$("#shownewstatus").after(html);
$(".newstatuscontent").val('');
$("#submit").val("Post");
}
});
}
//}
return false;
});
});
jQuery for Images preview:
function del(index) {
$('div.img_'+index).remove();
updateFiles();
}
function updateFiles() {
var fileIndexes = $('#imgs > div').map(function() {
return $(this).data('index');
}).get().join(",");
$('#files_selected').val(fileIndexes);
}
$(document).ready(function() {
$("#file-5").on('change', function() {
var fileList = this.files;
$('#imgs').empty();
if($('#imgs') != null){
$('.post-btn').css("margin-top","5px");
}
//$('#dimg').empty();
for (var i = 0; i < fileList.length; i++) {
var t = window.URL || window.webkitURL;
var objectUrl = t.createObjectURL(fileList[i]);
$('#imgs').append('<div data-index="' + i + '" class="img_' + i + '"><span class="img_' + i + '" onclick="del(' + i + ')" style="cursor:pointer; margin-right: 3px;"><b>x</b></span><img class="img_' + i + '" src="' + objectUrl + '" width="160" height="160" style="margin-right: 3px;"></div>');
j = i + 1;
if (j % 3 == 0) {
$('#imgs').append('<br>');
}
}
updateFiles();
});
});
post-status.php:
<?php
session_start();
include('config/db.php');
$time = date('Y-m-d H:i:s');
$curr_date = date('Y-m-d');
$yest = date("Y-m-d", strtotime("-1 day"));
$status = (!empty($_POST['content']))?nl2br(trim($_POST['content'])):null;
$status_fix = str_replace(array("\r", "\n"), '', $status);
$post = "INSERT INTO status(sts_status, sts_mem, sts_time)VALUES(:status, :mem, :time)";
$posq = $pdo->prepare($post);
$posq->bindValue(':status', $status_fix);
$posq->bindValue(':mem', $user_id);
$posq->bindValue(':time', $time);
$posq->execute();
$lastid = $pdo->lastInsertId();
?>
I want to combine the Image preview code with the ajax code above so that I can insert the data to the database. Now what I want?
Say for example I first selected 4 images like a.jpg, b.jpg, c.jpg, d.jpg. Then I got their preview. Then say I thought to remove b.jpg so I removed it. Now I have only the three images in preview a.jpg, c.jpg, d.jpg. Now finally, I want to rename these three files when I click on post to some random names and upload these images to the upload folder and insert their renamed names to the database.
NOTE: I want to insert and upload only those images that are in the preview div <div id="imgs"> and not from <input type="file">.
Please help me guys. I made it as much clear as possible. What I have already coded is already given above. Struggling with this problem from quite a few days. Please help me tackle this problem.
Hi i am trying to update data in a database from a form on the same page as the php code without redirecting/reloading the page.
I tried this tutorial but that didn't work: http://www.formget.com/form-submit-without-page-refreshing-jquery-php/
Update code:
<?php
include "db.php";
session_start();
$value=$_POST['name'];
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='$_SESSION['user']'");
?>
Profilecomplete.js:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
if (name == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {
value: name
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
The form:
<form method="POST" id="form">
<div class="input-field col s6">
<input id="name" type="text" class="validate">
<label for="name">Value</label>
</div>
<button type="submit" id="submit" class="btn-flat">Update</button>
</form>
Use this, it's working already.
index.php
<form method="post">
<input type="text" id="name">
<input type="submit" id="submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var nameInput = $("#name").val();
var name = {
'name' : nameInput
}
if (nameInput == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {value: name}, function(data) {
alert(data);
//$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
profilecomplete.php
<?php
$_POST = array_shift($_POST); // array_shift is very important, it lets you use the posted data.
echo $_POST['name'];
?>
if you want a more simple way.
try to use $.ajax()
It looks like the issue, or at least, one of the issues, is on this line;
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='$_SESSION['user']'");
You are opening and closing the single quotes twice, here
WHERE username='$_SESSION['user']'
Try using this instead;
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='" . $_SESSION["user"] . "'");
How your click event can occur even if you are not preventing the default behavior of the form submit button. Make the submit input as a button or use event.preventDefault() to submit the form via ajax.
<?php
include "db.php";
session_start();
if(isset($_POST)) {
$value=$_POST['name'];
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='{$_SESSION['user']}'");
echo ($query) ? "Updated" : "Not Updated";
exit;
} else {
?>
<form method="POST" id="form">
<div class="input-field col s6">
<input id="name" type="text" class="validate" name="name">
<label for="name">Value</label>
</div>
<button type="button" id="submit" class="btn-flat">Update</button>
</form>
<?php } ?>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
if (name === '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {name: name}, function(data) {
alert(data);
$('form')[0].reset(); // To reset form fields
});
}
});
});
</script>
I have a simple page. When I submit the form; I want to return the result that I get on the PHP page on the HTML page.
I have done the following:
<form id="myForm" action="addfaq.php" method="POST" enctype="multipart/form-data">
<input class="form-control focus" type="text" placeholder="Enter FAQ" name="faqQuestion" id = "faqQuestion">
<textarea class="form-control focus" placeholder="Enter FAQ description" name="faqDesc" id="faqDesc" draggable="false" style="resize:none" rows="4" cols="48"></textarea>
Select Images : <input type="file" id="files" name="img[]" accept="image/jpeg" multiple />
<button class="btn btn-info" id = "submit" name="submit_button">Submit</button>
This is my javascript code :
$("#submit").click( function() {
if( $("#faqQuestion").val() == "" || $("#faqDesc").val() == "" ){
$("#message").html("Question / description are mandatory fields -- Please Enter.");
} else{
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#message").empty();
$("#message").html("log = " + info);
console.log("log = " + info);
clear();
});
$("#myForm").submit( function() {
return false;
});
}
});
function clear() {
$("#myForm :input").each( function() {
$(this).val("");
});
}
The PHP code is for taking the form inputs from the user The PHP code is for taking the form inputs from the userThe PHP code is for taking the form inputs from the userThe PHP code is for taking the form inputs from the user:
<?php
if (isset($_POST['submit_button']))
{
$faqQuestion = $_POST['faqQuestion'];
$faqDesc=$_POST['faqDesc'];
$faqRole=$_POST['faqRole'];
if ($faqQuestion=="" and $faqDesc="" and $faqRole="")
{
echo "Incomplete information";
}
else
{
if(isset($_FILES['img'])){
// Database connectivity and query to database
$retval = mysql_query($sql);
if($retval){
echo "Question uploaded";
} else{
echo "Problem uploading question";
}
} else{
echo "Duplicate question";
}
mysql_close($con);
}
}
}
?>
The PHP code for inserting the info of above form to the database. The problem is that; the callback that my javascript gets is blank. Hence I am unable to get the result on the HTML page. Please correct me.
Only add this line in your form:
<input type="hidden" name="submit_button">
This will solve your issue.
And also do not forget to add faqRole field in your form.
i have a uploading script and works like a charm but i wanted to expand it with not only uploading one image, but several images. That resulted in my script only uploading the last image and not all of them with the text included with them in the textarea. i just can't figure out why it just won't upload all images.
my upload.php:
<?php // Start a session for error reporting session_start(); // Call our connection file require( "includes/conn.php"); // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds
all the valid image MIME types $valid_types=a rray( "image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file[ 'type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that 's easy to read
// I used this function during debugging but it serves no purpose at run time for this example
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
// Set some constants
// This variable is the path to the image folder where all the images are going to be stored
// Note that there is a trailing forward slash
$TARGET_PATH = "content/uploads/";
// Get our POSTed variables
$fname = $_POST['fname '];
$lname = $_POST['lname '];
$image = $_FILES['image '];
// Sanitize our inputs
$fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string(nl2br($lname));
$image['name '] = mysql_real_escape_string($image['name ']);
// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$TARGET_PATH .= $image['name '];
// Make sure all the fields from the form have inputs
if ( $fname == "" || $lname == "" || $image['name '] == "" )
{
$_SESSION['error '] = "All fields are required";
header("Location: indexbackup.php");
exit;
}
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!is_valid_type($image))
{
$_SESSION['error '] = "You must upload a jpeg, gif, or bmp";
header("Location: indexupload.php");
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
$_SESSION['error '] = "A file with that name already exists";
header("Location: indexupload.php");
exit;
}
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($image['tmp_name '], $TARGET_PATH))
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql="insert into people (fname, lname, filename) values ('$fname', '$lname', '" . $image[ 'name'] . "')"; $result=m ysql_query($sql)
or die ( "Could not insert data into DB: " . mysql_error()); header( "Location: indexupload.php"); exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod
the directory to be writeable $_SESSION[ 'error']="Could not upload file. Check read/write persmissions on the directory" ; header( "Location: indexupload.php"); exit; } ?>
and this is the page that let's me select the files and fill in the text area:
var abc = 0; // Declaring and defining global increment variable.
$(document).ready(function () {
// To add new input file field dynamically, on click of "Add More Files" button below function will be executed.
$('#add_more').click(function () {
$(this).before($("<div/>", {
id: 'filediv'
}).fadeIn('slow').append($("<input/>", {
name: 'image',
type: 'file',
id: 'file'
}), $("<br/><br/>")));
});
// Following function will executes on change event of file input to select different file.
$('body').on('change', '#file', function () {
if (this.files && this.files[0]) {
abc += 1; // Incrementing global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd" + abc).append($("<img/>", {
id: 'img',
src: 'images/x.png',
alt: 'delete'
}).click(function () {
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
}
;
$('#upload').click(function (e) {
var name = $(":file").val();
if (!name) {
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
<div id="maindiv">
<div id="formdiv">
<h2>Upload en delete pagina</h2>
<?php
if (isset($_SESSION['error'])) {
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload2.php" method="post" enctype="multipart/form-data">
<label>Merk</label>
<input type="text" name="fname" style="width:250px;"/><br />
<label>beschrijving</label>
<textarea name="lname" style="width:250px;height:150px;"></textarea><br />
<label>Upload afbeelding</label>
<div id="filediv"><input type="file" name="image" id="file"/></div>
<input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
<br /><br /><p>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<br /><br />
<input type="submit" value="Upload" name="submit" id="submit" class="upload" style="left:200px;"/>
</p>
</form>
<br /><br />
<p>
<form action="delete_multiple.php" method="post">
Wil je auto's van de site halen?
<input type="checkbox" name="formverkocht" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
</p>
</div>
</div>
thanks in advance guys!
You have spaces in ALL of your post parameters:
$fname = $_POST['fname '];
^--
That space DOES count for naming purposes, and is NOT the same as 'fname'. The keys in _POST/_GET must match EXACTLY what you have in the html:
<input type="text" name="foo"> -> $_POST['foo'] // note the LACK of a space
<input type="text" name="bar "> -> $_POST['bar '] // note the space
I have a problem with multipost file using jQuery. When I echo result, server return
A PHP Error was encountered. Severity: Notice; Message: Undefined index: files[]
I'm using php-framework CodeIgniter.
Here is a jQuery code:
jQuery(document).ready(function($){
$("#new_article").submit(function(event){
event.preventDefault();
var $form = $(this),
url = $(this).attr("action");]
var files = $form.find('input[name="files[]"]').val();
var posting = $.post(url,{
files: files
});
posting.done(function(data){
$("#result").empty().append(data);
});
return false;
});
});
Here is a HTML code:
<form method="post" enctype="multipart/formdata" action="/upload" id="new_article">
<input class="text-input" id="files" name="files[]" type="file" multiple="" accept="image/*" />
<input type="submit" name="submit" value="Submit" />
</form>
how are you trying to echo it?
I tested your code and it does what you are asking for. It sends the filenames, but not the files.
Run
var_dump($_POST['files'])
and it'll show you the files' names.
But If you need to upload files, here is an actual solution :
I suggest to use the next libraries
1. AjaxFileUpload (http://www.phpletter.com/Our-Projects/AjaxFileUpload/)
2. CodeIgniter Multi-Upload https://github.com/stvnthomas/CodeIgniter-Multi-Upload
Your Form:
<form method="post" enctype="multipart/formdata" action="/upload" id="upload_file">
<input class="text-input" id="files" name="files[]" type="file" multiple="" accept="image/*" />
<input type="submit" name="submit" id="submit" />
</form>
Your JS Script:
<script src="/assets/js/jquery.js"></script>
<script src="/assets/js/ajaxfileupload.js"></script>
<script>
$(function() {
$('#upload_file').submit(function(e) {
e.preventDefault();
$.ajaxFileUpload({
url :'/upload',
secureuri :false,
fileElementId : 'files',
dataType : 'json',
data : {
'somedata' : 'somedata'
},
success : function (data, status)
{
//do something here
}
});
});
});
</script>
Your Codeigniter upload method :
public function upload()
{
$status = "";
$msg = "";
$file_element_name = 'files';
if ($status != "error")
{
$this->load->library('upload');
$this->upload->initialize(array( // takes an array of initialization options
"upload_path" => "/mnt/httpd/htdocs/codeig/files/", // physical path where the files should be saved
"overwrite" => TRUE,
"encrypt_name" => TRUE,
"remove_spaces" => TRUE,
"allowed_types" => "gif|jpg|png|doc|txt",
"max_size" => 30000,
"xss_clean" => FALSE
));
if (!$this->upload->do_multi_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->get_multi_upload_data();
if($data)
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}