My intention is to delete file from folder But Here in above script is not working properly can any one please suggest me about this
function deleteFile()
{
var myObject;
myObject = new ActiveXObject("Scripting.FileSystemObject");
myObject.DeleteFile("D:\\WEBSITE_FILES\\docs\\OTR\\"+db_unicid+"\\passportImage.jpg");
return true;
}
<input type='Button' value='Click to Delete File' onClick='return deleteFile()'>
You cannot delete files with Javascript. It mostly has to do with security issues. Also, right now ActiveX Object is only supported by IE, so you'll have troubles with it in every other browser. You should do it just with PHP or with an Ajax call to a PHP file.
the PHP (this would be a file called deleteFile.php)
<?php
unlink($_GET['file']);
?>
and the JavaScript
function deleteFile()
{
$.ajax({
url: 'deleteFile.php',
data: {'file' : "<?php echo dirname(__FILE__) . '/uploads/'?>" + file_name },
success: function (response) {
// do something
},
error: function () {
// do something
}
});
}
<input type='Button' value='Click to Delete File' onClick='return deleteFile()'>
Related
I know this question have been asked alot but none of the answer are related to my case ,I have a button ,onclick it should call a javascript function send it a php variable,and ajax would call a php file via post and send that vriable and the php file updates my table
so here is the onclick event first
<button class="button button6 " onclick="incrementclicks('<?php echo $id; ?>');">increment</button>
it should send a variable called $id to the javascript function
<script type="text/javascript">
function incrementclicks(id) {
$.ajax({
url: "increment.php",
data: "id=" + id,
type: "POST"
});
}
</script>
and the php file increment.php (I'm 100% sure it connects to the server just fine )
<?php
require_once 'dbconnect.php';
$db_handle = new DBController();
$id=$_POST["id"];
$q="UPDATE clicks SET linkclicks = linkclicks + 1 WHERE id = '".$id."'";
$result = mysql_query($q);
?>
it doesn't increment, I don't understand what did i do wrong here
First of all you can debug your code on the php by doing
echo $id;
exit();
My quess is that your are missing something there..
Use this method of ajax to check the issue.And if error found check in console for the issue
$.ajax({
url: "increment.php",
type: "post", //send it through post method
data: {
id:id
},
success: function (response) {
alert("success");
},
error: function (xhr) {
//Do Something to handle error
alert("some error found");
}
});
NB:Try to add type="button" to your button for not to reload
<button class="button button6 " onclick="incrementclicks(5);" type="button">increment</button>
I just want to answer this if anyone have future problems like this
The problem is I forgot to add script src at the beginning
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
after adding this my code worked just fine :)
I have to select a file locally and use it in a python script.
I can't get the filename in order to have it in my ajax script that i use to call a php function.
This is my javascript, called onclick over Ok button:
function myAjax () {
$.ajax( { type : 'POST',
data : {},
url : 'action.php',
success: function ( data ) {
alert( data );
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
},
complete: function (data) {
setImg();
}
});
}
This is the php script used to call python script:
<?
function bb(){
$out = shell_exec( 'python heatmap.py');
echo "ok";
$fp = fopen('log.txt', 'w');
fwrite
($fp, $out);
fclose($fp);
}
bb();
?>
I have to take filename from Browse button and send it to ok button, where the python is called.
What is the correct way to exchange data from input="file" html, javascript and php?
I'm making a lot of assumptions here as the question is not entirely clear...
But presumably you're wanting the name of a file that has been selected from the OS. In JS you can do this using the following.
var fileName, oForm = document.getElementById('my-file');
oForm.onchange = function(){
fileName = this.files[0].name;
}
Then in your AJAX call, add the fileName variable to your data property.
data : {"filename":fileName},
And then in your PHP access it via the $_POST variable. So...
echo $_POST['filename'];
I want to open PDF File onclick of a button. I tried doing this with AJAX but it doesn't open the PDF file.
I keep receiving this alert everything I clicked the View PDF button.
Here is the my code for AJAX:
function viewPDF(id){
$.ajax({ url: "viewCrf.php",
data: {'idd' : id},
type: "POST",
success: function (data) {
}
});
}
The AJAX code above will be trigger after the clicked of this button:
<td><input id='$idd'
type='button'
value='View PDF'class='btn btn-primary' onclick='viewPDF(this.id)'
target='_blank' ></td>
The viewCrf.php contains the code for generating the PDF. Uses POST method to get the value passed by the AJAX then get the data from the database
$id = $_POST['idd'];
$q = $db->query("SELECT * FROM crf where col_ID = ".$id);
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$last = $r['col_ln'];
$first = $r['col_fn'];
$middle = $r['col_mi'];
$civilstatus = $r['col_civilstat'];
$sex = $r['col_gender'];
$dob = $r['col_bday'];
}
My problem here is that, the PDF file isn't opening at all. Though the success part on the AJAX seems to alert something when I add alert(data).
This code supposedly should open a PDF file on the click of the button.
Since using FPDF, you certainly have some PHP code looking like this.
If you didn't specifed any aguments to output(), it produces inline HTML.
Reference about the output method here.
So, this should work:
<td>
<input id='$idd' type='button' value='View PDF'class='btn btn-primary' onclick='viewPDF(this.id)' target='_blank' >
</td>
<div id="pdfResult"></div>
<script>
function viewPDF(id){
$.ajax({ url: "viewCrf.php",
data: {'idd' : id},
type: "POST",
success: function (data) {
$("#pdfResult").html(data);
}
});
}
</script>
I change the button to an href instead and use GET METHOD.
<td>".$result['col_ID']."</td>
<td>".$result['col_fn']." ".$result['col_ln']."</td>
<td><a href='viewCrf.php?idd=".$idd."' type='button'
value='View PDF'class='btn btn-primary'
target='_blank' >
</td>
In your viewCrf.php file, you must edit headers for say that's a PDf file ( and not show the pdf code.)
<?php header('Content-Type: application/pdf');
i have an issue with my jquery upload plugin, I am using jQuery Upload File Plugin version: 3.1.10 from http://hayageek.com and the problem is with filename wich i want to copy it to database.
I have my html form little complex with texts, checkboxes, etc.
a part of my form looks like this:
<form>
<input type="text" name="titlu" value="Marcel">
<div id="incarcareImagine">Upload image</div>
<button type="button" onclick="showValues()">Publish</button>
</form>
<script>
function showValues() {
var str = $( "form" ).serialize();
$( "#results" ).html( str );
var dataString = "results="+ str;
$.post('motor/parser_incarcare.php',dataString,function(theResponse){
//alert('data is sended to php'); //shows data to php response
});
}
</script>
<script src="js/jquery.uploadfile.min.js"></script>
<script>
$(document).ready(function()
{
var settings = {
url: "upload.php",
method: "POST",
allowedTypes:"jpg,png,jpeg",
fileName: "myfile",
multiple: false,
onSuccess:function(files,data,xhr){}
}
$("#incarcareImagine").uploadFile(settings);
});
</script>
File upload plugin is here: https://rawgit.com/hayageek/jquery-upload-file/master/js/jquery.uploadfile.min.js
This script on succes of upload image is auto generating contet under #incarcareImagine like 1). the_name_of_the_uploaded_file.jpg and the progress bar under this text.
My question is how to generate inside of the <form> an child like this: <input type='hidden' name='image' value='the_name_of_the_uploaded_file.jpg'>
My upload.php looks like:
$director_Img = "fisiere_pub/Img/";
if(isset($_FILES["myfile2"]))
{
$ret2 = array();
$error =$_FILES["myfile2"]["error"];
{
if(!is_array($_FILES["myfile2"]['name'])) //single file
{
$fileName = $_FILES["myfile2"]["name"];
move_uploaded_file($_FILES["myfile2"]["tmp_name"],$director_Img. $_FILES["myfile2"]["name"]);
//echo "<br> Error: ".$_FILES["myfile"]["error"];
$ret2[$fileName]= $director_Img.$fileName;
}
else
{
$fileCount = count($_FILES["myfile2"]['name']);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile2"]["name"][$i];
$ret2[$fileName]= $director_Img.$fileName;
move_uploaded_file($_FILES["myfile2"]["tmp_name"][$i],$director_Img.$fileName );
}
}
}
echo json_encode($ret2);
}
So in the end I will have my complete form and will be ready for sending this complete data via ajax - serialize() to my php parser for copy all wanted data to the mysql database
Thanks in advance team!
Not sure why you NEED to do that (can't you just get the name from the PHP side?) but if you really want to do it you could just add something along the lines of:
function showValues() {
$("form").find("*[name=image]").remove();
var field = $("<input type='hidden' name='image' value=''>");
field.val($("form").find('input[type=file]').val());
$("form").append(field);
var str = $( "form" ).serialize();
Since you are uploading to a PHP file, and processing it on a PHP backend, what we tend to do is accept the upload, after accepting the upload rename so that there are no conflicting filenames in the upload folder, then echo from the php back to the javascript.
function upload() {
do_upload();
rename($file);
echo $filename;
}
Then from the javascript callback (xhr) , you have access to the echoed name.
onSuccess: function( files, data, xhr ) {
var filename = xhr.responseTxt // from php;
var field = $("<input type='hidden' name='images[]' value=''>");
field.val(filename);
$("form").append(field);
}
This way you can then send the filename back to the php, and associate it in the database.
I want to uplod multiple files through ajax but I can't figure out how I can grab the files in PHP. Can anyone help me? Thank you!
Here is the code:
HTML:
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file" multiple="multiple" name="file"/>
</form>
<div id="info"></div>
<div id="preview"></div>
JavaScript:
$(document).ready(function(){
$("#file").change(function(){
var src=$("#file").val();
if(src!="")
{
formdata= new FormData(); // initialize formdata
var numfiles=this.files.length; // number of files
var i, file, progress, size;
for(i=0;i<numfiles;i++)
{
file = this.files[i];
size = this.files[i].size;
name = this.files[i].name;
if (!!file.type.match(/image.*/)) // Verify image file or not
{
if((Math.round(size))<=(1024*1024)) //Limited size 1 MB
{
var reader = new FileReader(); // initialize filereader
reader.readAsDataURL(file); // read image file to display before upload
$("#preview").show();
$('#preview').html("");
reader.onloadend = function(e){
var image = $('<img>').attr('src',e.target.result);
$(image).appendTo('#preview');
};
formdata.append("file[]", file); // adding file to formdata
console.log(formdata);
if(i==(numfiles-1))
{
$("#info").html("wait a moment to complete upload");
$.ajax({
url: _url + "?module=ProductManagement&action=multiplePhotoUpload",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res){
if(res!="0")
$("#info").html("Successfully Uploaded");
else
$("#info").html("Error in upload. Retry");
}
});
}
}
else
{
$("#info").html(name+"Size limit exceeded");
$("#preview").hide();
return;
}
}
else
{
$("#info").html(name+"Not image file");
$("#preview").hide();
return;
}
}
}
else
{
$("#info").html("Select an image file");
$("#preview").hide();
return;
}
return false;
});
});
And in PHP I get $_POST and $_FILES as an empty array;
Only if I do file_get_contents("php://input"); I get something like
-----------------------------89254151319921744961145854436
Content-Disposition: form-data; name="file[]"; filename="dasha.png"
Content-Type: image/png
PNG
���
IHDR��Ò��¾���gǺ¨��� pHYs��������tIMEÞ/§ýZ�� �IDATxÚìw`EÆgv¯¥B-4 ½Ò»tBU©)"¶+*"( E¥J7ôÞ;Ò¤W©¡&puwçûce³WR¸ èóûrw»³ï}fö
But I can't figure out how to proceed from here.
I am using Jquery 1.3.2 maybe this is the problem?
Thank you!
Sorry about the answer, but I can't add a comment yet.
I would recommend not checking the file type in javascript, it is easily bypassed. I prefer to scrutinise the file in PHP before allowing it to be uploaded to a server.
e.g.
This answer taken from another question (uploaded file type check by PHP), gives you an idea:
https://stackoverflow.com/a/6755263/1720515
<?php
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);
?>
You can read the documentation on the exif_imagetype() function here.
Could you post your PHP code please? And I will update my answer if I have anything to add.
UPDATE:
NOTE: The 'multiple' attribute (multiple="multiple") cannot be used with an <input type='file' /> field. Multiple <input type='file' /> fields will have to be used in the form, naming each field the same with [] added to the end to make sure that the contents of each field are added to an array, and do not overwrite each other when the form is posted.
e.g.
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file_0" name="img_file[]" />
<input type="file" id="file_1" name="img_file[]" />
<input type="file" id="file_2" name="img_file[]" />
</form>
When the form is submitted, the contents of any <input type='file' /> fields will be added to the PHP $_FILES array. The files can then be referenced using $_FILES['img_file'][*parameter*][*i*], where 'i' is key associated with the file input and 'paramter' is one of a number of parameters associated with each element of the $_FILES array:
e.g.
$_FILES['img_file']['tmp_name'][0] - when the form is submitted a temporary file is created on the server, this element contains the 'tmp_name' that is generated for the file.
$_FILES['img_file']['name'][0] - contains the file name including the file extension.
$_FILES['img_file']['size'][0] - contains the file size.
$_FILES['img_file']['tmp_name'][0] can be used to preview the files before it is permanently uploaded to the server (looking at your code, this is a feature you want to include)
The file must then be moved to its permanent location on the server using PHP's move_uploaded_file() function.
Here is some example code:
<?php
if (!empty($_FILES)) {
foreach ($_FILES['img_file']['tmp_name'] as $file_key => $file_val) {
/*
...perform checks on file here
e.g. Check file size is within your desired limits,
Check file type is an image before proceeding, etc.
*/
$permanent_filename = $_FILES['img_file']['name'][$file_key];
if (#move_uploaded_file($file_val, 'upload_dir/' . $permanent_filename)) {
// Successful upload
} else {
// Catch any errors
}
}
}
?>
Here are some links that may help with your understanding:
http://www.w3schools.com/php/php_file_upload.asp
http://php.net/manual/en/features.file-upload.multiple.php
http://www.sitepoint.com/handle-file-uploads-php/
Plus, some extra reading concerning the theory around securing file upload vulnerabilities:
http://en.wikibooks.org/wiki/Web_Application_Security_Guide/File_upload_vulnerabilities
You can use ajax form upload plugin
That's what i have found couple of days ago and implemented it this way
Ref : LINK
You PHP Code can be like this
uploadimage.php
$response = array();
foreach ($_FILES as $file) {
/* Function for moving file to a location and get it's URL */
$response[] = FileUploader::uploadImage($file);
}
echo json_encode($response);
JS Code
options = {
beforeSend: function()
{
// Do some image loading
},
uploadProgress: function(event, position, total, percentComplete)
{
// Do some upload progresss
},
success: function()
{
// After Success
},
complete: function(response)
{
// Stop Loading
},
error: function()
{
}
};
$("#form").ajaxForm(options);
Now you can call any AJAX and submit your form.
You should consider below code
HTML
<input type="file" name="fileUpload" multiple>
AJAX
first of all you have to get all the files which you choose in "input type file" like this.
var file_data = $('input[type="file"]')[0].files;
var form_data = new FormData();
for(var i=0;i<file_data.length;i++)
{
form_data.append(file_data[i]['name'], file_data[i]);
}
then all your data is in formData object now you can send it to server(php) like this.
$.ajax({
url: 'upload.php', //your php action page name
dataType: 'json',
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (result) {
// code you want to execute on success of ajax request
},
error: function (result) {
//code you want to execute on failure of ajax request
}
});
PHP
<?php
foreach($_FILES as $key=>$value)
{
move_uploaded_file($_FILES[$key]['tmp_name'], 'uploads/' .$_FILES[$key]['name']);
}