Uploading multiple images within a json call - javascript

I'm trying to modify a jquery script I use often in my websites to integrate image uploads within it. Maybe it's a script that cannot be modified for this purpose otherwise I could do with some help. I dont really understand the 64 bit encoding for json and if it is possible to upload an image with json data in parrallel so I can benefit from the success responce without reloading pages. I would also like to avoid the plugins such as uploadify etc if possible. Also I'm uploading to folders/diectories listed in my html code, using checkboxes to hide and show elements and to identify the folder path for images.
my jquery
<script type="text/javascript">
$(document).ready(function() {
var checkboxes = $("input[type='checkbox']");
checkboxes.click(function() {
$('#add_photo_but').show();
$('#photoChoose').show();
$('#addPhotoInstruction').hide();
});
$(".add_photo_but").click(function() {
var file = $("image").files[0];
var image = $("#addImage").val();
$.post("includes/add_photo.inc.php",{ checked_box : $('input:checkbox:checked').val(), image:image, imageFile:file},function(json) {
if(json.result === "success") {
$(".addPhoto_result").html(json.message);
//$(".checkbox")[0].remove();
$("input:checkbox:checked").parent().remove();
// $('.add_intern').get(0).reset();
}else{
$(".addPhoto_result").html(json.message);
}
});
});//submit click
});//doc ready
</script>
html form
<div id="photos">
<form enctype="multipart/form-data" name="add_photo" class="add_photo">
<?php
while($row = mysqli_fetch_array($result4)){ ?>
<div class="photoAlbum_list">
<div id="#photoAlbumId" class="albumPhoto"><?php echo $row['album_name'];?></div>
<img src="image/mandinga_folder.png" class="folder"/>
<input type="checkbox" class="photoAlbumId" id="photoAlbumList" value="<?php echo $row['albumid'];?>"/>
</div>
<?php } ?>
</form>
<div id="addPhotoInstruction" style="display:block">Please choose an Album to Upload Photo's to</div>
<div class="addPhoto_result"></div>
<input id="photoChoose" type="file" multiple style="display:none"/>
<input type="button" id="add_photo_but" class="add_photo_but" name="add_photo_but" value="Add Photo" form="add_photo" style="display:none"/>
</div>

Related

Control image upload size in textarea of HTML Form

I'm using the following WIZWIG editor "http://js.nicedit.com/nicEdit-latest.js" posting into the below HTML form. I want to control the size of images that are uploaded. Image size should be something like 200px height, 300px width. I've tried CSS, HTML & JavaScript to no avail. Can't figure this out...
<style>
.nicEdit-main{
background-color: white;
}
</style>
<script type="text/javascript" src="http://js.nicedit.com/nicEdit- latest.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() { nicEditors.allTextAreas({buttonList : ['bold','italic','underline','strikeThrough','html','forecolor','link','upload','unlink','removeformat']}) });
</script>
<form name="comments" action="<?php echo $_SERVER['PHP_SELF']; ?>"method="post" onsubmit="return checkForm();">
<?php if ($isGuest) { ?>
Comment:<br><br>
<div style="background: #fff;">
<textarea style="width: 100%;" name="comment" cols="111px" rows="4">disabled for guest account</textarea>
</div>
<input type="submit" name="action" disabled value="Add Comment" />
<?php } else { ?>
Comment:<br><br>
<div style="background: #fff;">
<textarea style="width: 100%;" name="comment" cols="111px" rows="4"></textarea>
</div>
<input type="submit" name="action" value="Add Comment" />
<?php //header("Location: test.php");
} ?>
</form>
Although this was not possible few years ago(you had to send the file to the server side to be able to process file information) now it is do possible with the FileReader() object and pure JS.
You use the .files[0] to get the file then create a temporary img object on the DOM(to be able to do the process) and then assign the file to that DOM object(with the help of FileReader())and then you just compare the file width or height. This is an example how you can do it:
imgfile.onchange = function(e) {
var oFile = document.getElementById("imgfile").files[0]; //Get the selected file by the user
var img = document.getElementById("imgdom"); //get the reserve image element on the dom to be able do all our processing with this object type
document.getElementById("imgdom").style.display = "none";//This is optional if you want to show or not the image to the user
var reader = new FileReader(); //This is the magic object that allows you to process a file on the client side
reader.onload = function (e) {
console.log(e.total); // file size
img.src = e.target.result; // putting file in dom without server upload.
alert(img.width);
//Do what ever condition you want here
//if img.width > 200 do this, else do that
};
reader.readAsDataURL(oFile );
//return false;
};
<form method="post" enctype="multipart/form-data" onsubmit="return false;">
<input type="file" name="imgfile" id="imgfile">
</form>
<div>
<img id="imgdom" src="" />
This issue has been resolved with the following CSS Code:
.nicEdit-main img {
width: 350px;
}
img[src*="http://somedomain.com"] {
width: 350px;
}
Thanks to all who commented...

How to submit two forms at a time and store first form submit output value as 2nd form value?

Using the below form 1, i'm generating a goo.gl short url inline in #shortUrlInfo area. I want to use the generated short url in 2nd form to save it in wordpress custom field.
Form 1:
<form method="post" action="">
<input style="display:none;" type='text' id='longUrl' value='<?php echo get_post_meta( get_the_ID(), 'longurl', true ); ?>' />
<input name="shorturlinput" type="button" id="shortIt" value="Short It" /></form>
<div class="info" id="shortUrlInfo"></div>
Form 2:
<?php
global $post;
if( isset($_POST['submit_meta']) ) {
if( ! empty($_POST['change_meta']) ) {
update_post_meta($post->ID, 'shorturl', $_POST['change_meta']);
}}
?>
<form method="post" action="">
<input type="text" name="change_meta" value="" />
<input type="submit" name="submit_meta" value="Submit" />
</form>
How can i submit the first form and pass the generated short url to 2nd form and submit that short url value in custom field with one click?
Or atleast, how can we display the generated short url in 2nd form input, which if we click on submit button, it should save in database.
It's my first question here & I've tried my best to find answer before posting here with no luck.
Well its all ajax . you need to post your data with ajax function to the controller which save the shortened url in data base , how ? like this :
give your second form + the first input of your second form 2 ids
$("#shortIt").click(function(){
var longUrl = $('#longUrl').val()
$.post("ur_url.php",
{
"longUrl": longUrl // here the url will be sent to your server and server communicates
// with goo.gl url shorter by its api and respond you with a variable called data
},
function(data, status){ // your server send here the shorturl and this function calls it
//also this function will be run after the server respond is completed
$('#inputID').val(data) // data will be set inside the input value
document.getElementById("#SecondForm").submit(); // your second form submits and your
// server needs to get the data and save it in your data base
});
});
all will be done with a single click .
also you can do many things when the process is going on . but i hope i gave you some clue :P
Try this in HTML:
<form (return to script)>
<input 1>
</form>
<input 2>
Then in script:
get input 1 and input 2
Next example code shows how to achieve what I believe you want (with one click!). Explanation first: one form (file #1) sends a text to a script (file #2), this script redirects to another form (file #3), this form gets the original text and automatically resend it to another script (file #4) that inserts it in database, next image explains it better:
As you can see, the text in the first form becomes a value for the second form.
Now the code. In order to test next code, you will have to create four text files and give them the given names (if you change the filenames, you will have to change the "action" property in the forms), copy-paste my code in your files, then, open you browser and run only the first file like this) :
http://localhost/form_sequence_1.php
These are the files:
form_sequence_1.php
<html>
<body>
FORM 1
<br/>
<form method="post" action="form_sequence_2.php">
Enter a text
<input type="text" name="my_text" />
<br/>
<input type="submit" value="Send text" />
</form>
</body>
</html>
form_sequence_2.php
<?php
session_start();
$_SESSION[ "my_text" ] = $_POST[ "my_text" ];
header( "Location: form_sequence_3.php" );
?>
form_sequence_3.php
<?php
session_start();
?>
<html>
<head>
<script type="text/javascript">
function autosendform () {
setTimeout( "sendform()","3000" );
}
function sendform () {
document.getElementById( "my_form" ).submit();
}
</script>
</head>
<body onload="autosendform();">
FORM 2
<br/>
<form method="post" action="form_sequence_4.php" id="my_form">
Text entered in previous form
<input type="text" name="my_text" value="<?php echo $_SESSION[ "my_text" ]; ?>"/>
<br/>
<input type="submit" value="AUTOSENDING FORM IN 3 SECONDS" />
</form>
</body>
</html>
form_sequence_4.php
<?php
session_start();
echo $_SESSION[ "my_text" ] . " succesfully inserted into database.";
?>
More explanations:
Value in form 1 sends the text to form 2.
In the middle of form 1 and form 2 we need a script to capture the value.
Form 2 automatically resends the value thanks to a timer in JavaScript.
The last script gets the value and insert it in database (not for real).
The advantage of this approach is that the scripts allow you to do many things with the value or values, like validating or conversion.
Next is your code with my JavaScript timer code adapted :
<?php
global $post;
if ( isset($_POST['submit_meta']) )
if ( ! empty($_POST['change_meta']) )
update_post_meta( $post->ID, 'shorturl',$_POST['change_meta'] );
?>
<html>
<head>
<script type="text/javascript">
function autosendform () {
setTimeout( "sendform()","3000" );
}
function sendform () {
document.getElementById( "my_form" ).submit();
}
</script>
</head>
<body onload="autosendform();">
<form method="post" action="" id="my_form">
<input type="text" name="change_meta" value="" />
<input type="submit" name="submit_meta" value="Submit" />
</form>
</body>
</html>

Why do I get only 000000 as the add on number in a PHP Ajax file transfer with add on number?

I got help from stackoverflow but I do get now only 000000 as the add on numbers:
1) I want to Format ID2 to "000000" six digits, example if the ID2 is 302 then should it be "000302"
2) I want to combine the now formatted data (000302) in with .$_FILES['file']['name'] in the upload.php file and save the file with this new file name.
The $new_id have always "000000", whatever I do.
I am still lost how to do it, even the first help was very good!
The file transfer code is not from me. It is a code that is from the internet.
I would be very happy for any help!
This is the in the head section:
<script type="text/javascript" src="js/multiupload.js"></script>
<script type="text/javascript">
var config =
{
support : "image/jpg,image/png,image/bmp,image/jpeg,image/gif", // Valid file formats
form: "demoFiler", // Form ID
dragArea: "dragAndDropFiles", // Upload Area ID
uploadUrl: "upload.php" // Server side upload url
}
$(document).ready(function(){
initMultiUploader(config);
});
</script>
This in the body section:
<div id="dragAndDropFiles" class="uploadArea">
<br>
<span style="padding-left: 20px">To upload more pictures for this item click Browse</span>
<br>
<span style="padding-left: 20px">The order of the upload decide the order to show the pictures</span>
</div>
<form name="demoFiler" id="demoFiler" enctype="multipart/form-data" style="">
<input id="ID2" type="hidden" name="ID2">
<input type="file" name="multiUpload" id="multiUpload" multiple />
<input type="submit" name="submitHandler" id="submitHandler" value="Upload" class="buttonUpload" />
</form>
<div class="progressBar">
<div class="status"></div>
</div>
This the file upload.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
$new_id = sprintf( "%06d", $_POST['ID2']);
if(move_uploaded_file($_FILES['file']['tmp_name'], "sobimages/" . $new_id . $_FILES['file']['name'])){
echo($_POST['index']);
}
exit;
}?>
You are sending a form field in the form that is hidden:
<input id="ID2" type="hidden" name="ID2">
But it has no value and as the user will not see it and fill in a value, it will always be empty / 0.
You should not use this approach as the user could manipulate the number. If you have the number already available, you should keep it on the server, for example in a session variable, and use that instead.

Convert a DIV to textarea with specific "name" attribute

I have a small admin panel that I have created to do simple database tasks for my DayZ server. Now I want to make a simple editor for the news blurb on my website. The news blurb is stored in a table on my database. What I want is when the page loads it simply echo's the data and looks like it does on the live site. Then, when I click on it, I want it to convert into:
<textarea name="edit><?php echo news; ?></textarea>
This is my current code:
function divClicked() {
var divHtml = $(this).html();
var editableText = $("<textarea name="edit" />");
editableText.val(divHtml);
$(this).replaceWith(editableText);
editableText.focus();
// setup the blur event for this new textarea
editableText.blur(editableTextBlurred);
}
$(document).ready(function() {
$("#editable").click(divClicked);
});
<form method="post" action="newsedit.php">
<div id="editable"><?php echo $news; ?></div>
<input type="submit" value="Edit News" />
</form>
Now, this does work in the sense that when I click on the text it does convert into a textarea. The problem is that it doesn't give it the "edit" name so when I hit the sumbit button, it is as if I submitted nothing and it deletes all the data out of the table because
<textarea name="edit"></textarea>
is technically empty. Are there any ways to make it so when I click on the text it will convert the code to textarea with that specific name so there is actual data when I hit submit?
Change the form to:
<form method="post" action="newsedit.php">
<div id="<?php echo $newsID;?>"><?php echo nl2br($news); ?></div>
<input type="submit" value="Edit News" />
</form>
Where $newsID is returned along with the $news text.
The nl2br($news) will just make sure the line breaks are honored.
var editableText = $("<textarea name='edit' />");
http://jsfiddle.net/H5aM4/ inspect the textarea
TRY This
$("#editable").click( function(){
$(this).replaceWith(function() {
return $("<textarea name='edit'>").text(this.innerHTML);
});
});
Here is the working example

How to upload files using submit without reloading the page

I am uploading files to the tomcat server using a submit button but my problem is that the page is reloading. If I use return false the file is not uploaded. I tried to use button its not uploading the files.
I am using jstl and javascript for my client side.
<form:form modelAttribute="uploadItem" name="frm" method="post"
enctype="multipart/form-data">
<fieldset>
<legend>Upload File</legend>
<table>
<tr>
<td><form:label for="fileData" path="fileData">File</form:label><br />
</td>
<td><form:input path="fileData" id="csv" type="file" /></td>
</tr>
<tr>
<td><br /></td>
<td><input id="subUpload" type="submit" value="Upload" /></td>
</tr>
</table>
</fieldset>
</form:form>
For my javascript:
$("#subUpload").click(function(e) {
var image = document.getElementById("csv").value;
if(image!=''){
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.CSV|\.csv)$/)){
alert("Please enter Image File Extensions .jpg,.png,.jpeg");
document.getElementById("image").focus();
return false;
}
}
return true;
e.preventDefault();
});
I also used e.preventDefault() but still its reloading.
Please help.
this is possible if you use an iframe.
Anything under and in the same block with return [optional value here]; will be omitted so your e.preventDefault() line will never get executed.
return true will tell the button to behave normal, so it will try to take its regular action
return false and e.preventDefault() will do the same thing (stop the form from submitting the file), except, return false additionally blocks bubbling the click event up the document.
If you want to send the file seamlessly you might want to use an iframe or send the data using jQuery instead of letting the form to handle that data transfer.
you can use uploadify type component which can upload a file before submission of a form
create a form.. ex
<form name="form" method="post" enctype="multipart/form-data" action="test.php">
<input type="file" name="piture" value="" onChange="window.document.forms['form'].submit();"/> </form>
test.php
if(preg_match('/[.](jpg)|(gif)|(png)$/', $_FILES['picture']['name'])) {
$rand=rand(000000000,9999999);
$fl_name = $_FILES['picture']['name'];
$expld = explode('.', $fl_name);
$extnnew = $expld[1];
$filename = $rand.'.'.$extnnew;
$source = $_FILES['picture']['tmp_name'];
$path_to_image_directory = "uploads/";
if(!is_dir($path_to_image_directory)){
mkdir($path_to_image_directory, 0777);
chmod($path_to_image_directory, 0777);}
$target = $path_to_image_directory . $filename;
move_uploaded_file($source, $target);
$sql ="insert into picture values('','".$filename."','Now()')";
mysql_query($sql) or die(mysql_error());
}
header('Location:page.php');

Categories