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');
Related
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>
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.
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>
I'm creating a simple website and a html page on it which contains a table that shows products. I load this table using AJAX and it work properly. Here is a screenshot:
Under the table I have buttons which perform CRUD operations using AJAX.
They communicate to a php script on a server outside of my domain using GET method.
When I click on Add product it opens a form with a button that whose onclick event calls a function which adds a product using AJAX. But, when I click, the whole page reloads and the product is not added. If I put the value that says wheter the call is async to false, it works as intended and the product is added to the table, however that is not the point of AJAX.
This is my code for adding a product(delete and update are almost the same).
<div id="addProductPopup">
<div id="popupContact">
<form id="form" method="post" name="form">
<img id="close" src="/servis/Resursi/Slike/close.png" onclick ="hide('addProductPopup');">
<h2>Dodavanje proizvoda</h2>
<hr>
<input id="name" name="naziv" placeholder="Naziv proizvoda" type="text" required>
<input id="kolicina" name="kolicina" placeholder="Količina proizvoda" type="text" required>
<input id="url" name="url" placeholder="URL slike" type="text" required>
<input type="submit" value="Pošalji" class="popupButtons" onclick="addProduct()">
</form>
</div>
When I click on submit this function is called:
function addProduct(){
var isValid = true;
var url = "http://zamger.etf.unsa.ba/wt/proizvodi.php?brindexa=16390";
var amount = document.form.kolicina.value;
var naziv = document.form.naziv.value;
var slikaurl = document.form.url.value;
var validity = validateFields(naziv, slikaurl, amount);
if(!validity) return false;
var product = {
naziv: naziv,
kolicina: amount,
slika: slikaurl
};
var requestObject = new XMLHttpRequest();
requestObject.onreadystatechange = function(event) {
if (requestObject.readyState == 4 && requestObject.status == 200)
{
loadProducts();
event.preventDefault();
}
}
requestObject.open("POST", url, true);
requestObject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
requestObject.send("akcija=dodavanje" + "&brindexa=16390&proizvod=" + JSON.stringify(product));
}
It is because you are not preventing the default action of the submit button click.
You can return false from an event handler to prevent the default action of an event so
<input type="submit" value="Pošalji" class="popupButtons" onclick="addProduct(); return false;">
But since you have a form with a submit button, I think it will be better to use the submit event handler like
<form id="form" method="post" name="form" onsubmit="addProduct(); return false;">
....
<input type="submit" value="Pošalji" class="popupButtons">
Your problem is that your submit button still executes a real submit. You could change your addProducts method. The method have to return false to prevent the real submit.
Submit button performs default Submit action for HTML code.
Try to change Submit tag into Button tag. Or after AddProduct() in OnClick JS Action put
return false;
Simple Change put input type="button" instead of tpye="submit"
<input type="button" value="Pošalji" class="popupButtons" onclick="addProduct()">
I have a webpage written in C#/Razor. I am printing all the values from a database on this page like so :
<div style="min-height: 150px; font-size: 1.25em">
<div style="margin-bottom: .5em">
<table>
<thead>
<tr>
<th>Name</th>
<th>Branch</th>
<th>Phone No.</th>
<th>Extension</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#foreach (var prod in Model)
{
<tr>
<td>#prod.FullName</td>
<td>#prod.Branch</td>
<td>#prod.PhoneNo</td>
<td>#prod.Extension</td>
<td>#prod.Email</td>
#if (User.IsInRole(#"Admins") || User.Identity.Name == prod.DomainAC)
{
<td>edit</td>
}
else
{
<td>User => #User.ToString()</td>
}
<td>
<input type="checkbox" name="message" value="#prod.PhoneNo">Message<br>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
This works fine to display their info. What I would like to do now is a small bit more difficult.
Below this, I have a form with a username, password and message. Using this form, I would like to have the behaviour that on submit, it will take the values in the input boxes of the form and the above C#, construct a link, navigate to the link and print the response of the server
So I have :
#{if (IsPost)
{
//handle and print response
}
else
{
<form method="post" action="">
Username:<br />
<input type="text" name="u" /><br />
Password<br />
<input type="text" name="p" /><br />
<br />
Password<br />
<textarea name="m" cols="25" rows="5">
Enter your comments here...
</textarea><br>
<br />
<input type="submit" value="Submit" class="submit" />//when this is clicked, construct url and navigate to it.
</form>
}
}
The URL I want to construct from this form is :
http://webaddress.com/web/d.php?u=<Username entered by user>&p=<Password entered by user>&s=<List of Phone Numbers from the C# above where the checkbox is selected, comma separated>&m=<Comment submitted by user>
So, if my name is "John", Password is "Password1", Comment is "Test" and I have selected one checkbox for a user with the phone number "12345678", the URL I will navigate to is :
http://webaddress.com/web/d.php?u=John&p=Password1&s=12345678&m=Test
Ideally I would like to print the response of the webpage in a <div> while still on the same parent web page rather than going to a new one if this is possible.
I have no idea where to begin with this, how to do it or even if this is possible. Can anyone help me please ?
UPDATE :
Trying this JQuery which does not alert me so I cannot debug :
<script>
$("#thebutton").click(function() {
var form = $(document.getElementById('FormID'));
var urlToConstruct = 'http://webaddress.com/web/d.php';
urlToConstruct += '?u=' + form.find('#u').val();
urlToConstruct += '&p=' + form.find('#p').val();
('#employeeTable tbody tr').has(':checkbox:checked').find('td:eq(2)').each(function() {
urlToConstruct.append($(this).text());
alert(urlToConstruct);
})
});
</script>
$("#SubmitButtonID").click(function() {
var form = $(document.getElementById('FormID');
var urlToConstruct = 'http://webaddress.com/web/d.php';
urlToConstruct += '?u=' + form.find('#iDoFInputControl1').val();
urlToConstruct += '&p=' + form.find('#iDoFInputControl2').val();
form.submit();
});
this example uses jQuery, a javascript library (jquery.com), i'm using getElementById to find your form, faster then the native jQuery() selector. This example assumes all your controls are inside your form (but if they are not it wouldn't be a train smash, just cant use (jQuery obj).find).
.val() gets the value, and it should work for checkboxes too, but if it doesn't, a quick google search for getting values from checkboxes using jquery will return loads of results.
p.s. I've written that code mostly freehand, not checked it in a browser to make sure that it is completely correct.
Update... to answer your follow up question...
If you are using mvc (assumed as you using razor), inside your controller you can use Request.Params["urlParameter"] or Request.Form["controlID"] to access what you've received from the browser. Then once you've got those values, you should place them inside the 'ViewBag' (ViewBag.yourVariableHere="val") for them to be accessible in your view via #ViewBag.yourVariableHere, or you can include the required data in your model which can also be accessed in your view