How to pass a php code in a javascript function? - php

I want to append the name of the file uploaded into ('.list'). The name of the file has to be the name which it is called in the server when it is uploaded. For example I could have 2 files but one is known as mountains.png and the other mountains2.png.
But the problem is that how could I pass $_FILES["fileImage"]["name"] as argument to my js function and then append it because the javascript function and the php script are on seperate pages (even though the php script does do a call back to the javascript function)?
UPDATE
Below is the javascript code:
Below is the form code (QandATable.php)
<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startImageUpload(this);' class='imageuploadform' >
<p>Image File: <input name='fileImage' type='file' class='fileImage' />
<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' />
</p>
<ul class='list'></ul>
</form>
Below is the javascript function (QandATable.php)
function stopImageUpload(success){
var nameimagefile = <?php echo $nameimagefile?>;
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append(nameimagefile + '<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Below is the php script (imageupload.php):
$result = 0;
$nameimagefile = '';
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$nameimagefile = $_FILES["fileImage"]["name"];
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$nameimagefile = $_FILES["fileImage"]["name"];
}
?>
<script language="javascript" type="text/javascript">window.top.window.stopImageUpload(<?php echo $result;?>);</script>

You can simply take the value $_FILE filename into a php variable than echo it using
var yourjasvariable=<?php echo $yourvariable?>;
and use this js variable in append method. :-)

You could chose AJAX to do what you want.
Write your data in JSON. JSON can be read from PHP and JavaScript
- read the JSON to get data in PHP
- read the AJAX result (the JSON) to get the data from PHP
I would do something like this (untested example)
AJAX js part
<form method='post' enctype='multipart/form-data' onsubmit='startAjaxImageUpload(this);' >
...
</form>
/*
* ajax functions
*/
function startAjaxImageUpload(event){
/* Collect your formdatas as json with jquery this datas will be sent to php*/
var formDatas = {
'value1' : $('input[test1=eid]').val(),
'value2' : $('input[id=test2_id]').val(),
......
'value3' : $('input[id=test3_id]').val()
};
$.ajax({
cache: false,
url: "imageupload",
data: formDatas,
success: function(data) {
// data is the json Result from php => imageupload.php do what u want with them in js
// use the next line if u wanna see which json datas comes back from php if the ajax call wass successfull
// console.log("data is %o, data);
// ....
}
error:function(data){
// error function
// data is the json Result from php => imageupload.php do what u want with them in js
// use the next line if u wanna see which json datas comes back from php if the ajax call wass successfull
// console.log("data is %o, data);
alert(damn, something went wrong);
}
})
}
PHP part, imageupload.php
$result = 0;
$nameimagefile = '';
.....
// if done ure work on server side and no error was found, pass the result back to starAjaxImageUpload success function
return $nameimagefile = $_FILES["fileImage"]["name"];
}else
// abbort ajax, ajax error function will used
return false
}

Related

Want to perform php using OnClick function without clearing the current web page

This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'>&nbsp</div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?

upload file using ajax like facebook uploading

My problem is, I want to upload a csv file without pressing a submit button and I used ajax for that case. But now, their is something errors appear, and the error said fopen() Filename cannot be empty. But I already get the file value that I want, but the $_FILES[$fie]['tmp_name'] can't read this value. But if I attach the variable in an alert() they display the exact filename. This is my sample codes.
This is the html:
<form id="Form2">
<input type="file" id="fie" />
</form>
this is the javascript:
<script style="text/javascript">
$(function(){
$('#Form2').change(function(e){
e.preventDefault();
var sub = document.getElementById("fie").files[0].name;
if($('#cat1').hasClass('show')){
$('#cat1').hide();
$('#cat2').html("<img src='pb1.gif' />");
$.ajax({
url:'uploading.php',
action:'get',
data: 'fie='+sub,
success: function(data){
$('#cat2').html(data);
}
});
}
});
});
</script>
This is the Php:
uploading.php
<?php
include("conn.php"); //assuming that connected to a database.
if (isset($_GET['fie'])) {
echo "<script>alert('".$_GET['fie']."')</script>";//IN ALERT THEY EXECUTE THE EXACT VALUE OF THE FILE I INPUT
$fie = $_GET['fie'];
$file = $_FILES[$fie]['tmp_name']; //PROBLEM IS THIS. THEY CAN'T READ THE VALUE AND TELL THEIR IS NO FILE.
$handle = fopen($file,'r') or die ('Cannot open file');
fgets($handle);
do {
if (isset($data[0])) {
mysql_query("INSERT INTO tbl_numbers (numbers,cute) VALUES ('".addslashes($data[0])."','".addslashes($data[1])."')");
}
}
while ($data = fgetcsv($handle,1000,",","'"));
echo "Successful Upload~!";
}
?>
Thanks for the reply.

PHP In ajax responseText take all the html cose instead of ONLY the echo passed trought PHP

Using that javascript ajax function I pass the content of a form, that contain
the dato value, to the PHP login.php than trought the echo pass back the content
(the insert form) that I want to be switched to the cancel form, using
the content respondText (that may take only the echo of the PHP).
BUT INSTEAD the responseText contain ALL the html code, with the old html
plus the cancella_form passed by the echo, that's also out of the div
with id=visibile.
Any ideas why? D:
//ajaxSubmit(dato)
function ajaxSubmit( url , divId , hideId ) {
//in setXmlHttpObject() I just control the user's browser
// and assign the right XmlHttp Object
var ajaxRequest = setXmlHttpObject();
var dato = 'nome='+document.getElementsByName('dato')[0].value;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dato);
ajaxRequest.onreadystatechange = function() {
//Comunication complete
if (ajaxRequest.readyState == 4 && ajaxRequest.status==200) {
//Comuncation succesfull
if(ajaxRequest.statusText === "OK"){
var str= ajaxRequest.responseText;//<<<HERE///////
$(str).replaceAll("#visibile");
}
//Comuncation failed
else{
var str= "ERROR: Ajax: "+ajaxRequest.responseText;
document.write(str);
}
}
}
}//FINE ajaxRequest();
<?php
include("prova_login_adv.php");
$conn= mysql_connect('localhost','root','');
mysql_select_db('db_prova',$conn ) or die(mysql_error());
//
if(isset($_POST['nome'])){
$dato= $_POST['nome'];
mysql_query(" INSERT INTO test (valore) VALUES ('$dato') ") or die(mysql_error());
/// NOW I declare what I want to be replaced in the div id="visibile"
echo "
<form id='form_cancella' name='form_cancella' action='' methos='POST' onSubmit=' return false;' >
<text name='dato' value='".$dato."' >Benvenuto <b>".$dato."</b></text>
<input type='submit' name='cancella' value='cancella' onClick=\" ajaxSubmit('logout.php','visibile','form_cancella');\" />
</form>
";
}
?>

How to delete database row in this php script

I have a situation with my php code. What I am currently doing is using the iframe to link the javascript message with the phe script. In the javascript function stopImageUpload, I have stated that if success = 2, then display the cancel message for the file upload.
So what I have tried but failed to do in the php script is to try and state that if the $result = 2 (In other words if success = 2 message appears in javascript), then delete the database row. How can this be done?
Below is the form code:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><p class='imagef1_cancel' align='center'><label>" +
"<input type='button' name='imageCancel' class='imageCancel' value='Cancel' /></label>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
Below is the startImageUpload() function where it starts an file upload and where the cancel button function is stored:
function startImageUpload(imageuploadform, imagefilename){
$('.imagef1_cancel').eq(window.lastUploadImageIndex).find(".imageCancel").on("click", function(event) {
return stopImageUpload(2);
});
return true;
}
Below is the stopImageUpload() function where it displays the cancel message using success and result:
function stopImageUpload(success, imagefilename){
var result = '';
if (success == 2){
result = '<span class="imagecemsg"> The file upload was canceled!</span><br/><br/>';
} else {
result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Finally below is the imageupload.php script which is linked to the QandATable.php (The script which contains the code above) using iframe and this is where the database row is suppose to be inserted and deleted from:
<?php
session_start();
...//connected to DB
$result = 0;
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
else
{
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
if ($result == 2) {
$imagecancelsql = "DELETE FROM Image
WHERE ImageFile = 'ImageFiles/".
mysql_real_escape_string($_FILES['fileImage']['name'])."'";
mysql_query($imagecancelsql);
}
mysql_close();
?>
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result ? 'true' : 'false'; ?>, '<?php echo $_FILES['fileImage']['name'] ?>');</script>
There are severe issues with your code that need to be addressed:
1)
This line:
return stopImageUpload(2);
Is calling the function:
function stopImageUpload(success, imagefilename){...}
But the stopImageUpload function needs two parameters, success and imagefilename
2)
This function returns true, but should return the contents of result.
function stopImageUpload(success, imagefilename){
...
return true;
}
3)
Here you set $result with the value 0, and compare it with the value 2 ?!?
$result = 0;
if ($result == 2) {
4)
This function accepts two parameters, but none of them is used inside ?!?
function startImageUpload(imageuploadform, imagefilename){...}
Also, it is returning
return stopImageUpload(2);
or
return true;
Are you controlling this situation!
Note: Where do you use this function ?!?
5)
This verification likely fails because file_exists checks whether a file or directory exists. So, if the file does not exist, surely the directory does, and it will continue to execute.
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
you should use is_file that tells you if the file is a regular file.
6)
You should not be using mysql_query anymore, please read PDO Tutorial for MySQL Developers
mysql_query($imagesql)
Please read this topics: to learn why are you failing to achieve your goal
PHP Variables
JavaScript Variables
JavaScript Functions
PHP File Upload e.g. 1 | PHP File Upload e.g. 2 | PHP File Upload e.g. 3
I hope this may help you getting on the right track and fixing some issues with your present code.
Best of Luck!

I am getting an undefined variable

I am trying to retrieve a file name from one page where the php script uploads the file (imageupload.php), and I want to display it in another page within a javascript function (QandATable.php). But I don't know how to do this
I will show you all of the relevant code so you can follow it and so you are able to understand what is happening.
UPDATE: BELOW I WILL SHOW YOU THE STEPS ON HOW THE FILE IS UPLOADED. THE CODE BELOW SUCCESSFULLY UPLOADS THE FILE.
Below is the form (QandATable.php);
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
<label>Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><ul class='listImage' align='left'></ul>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
On the same page when the user submits the form, it will go onto the function below, it will check for validation and then when validation is clear, it will go onto the startImageUpload() function:
function imageClickHandler(imageuploadform){
if(imageValidation(imageuploadform)){
return startImageUpload(imageuploadform);
}
return false;
}
If there is no validation then it will go onto the JS function (QandATable.php) below where it hides the file input and it will submit the form to the imageupload.php where the file uploading occurs. When the file is uploaded it then calls back to the stopImageUpload() function (QandAtable.php) where it will display the message on whether the file is uploaded or not and this is where I want the name of the file from the server to be appended.
Below is startImageUpload() function:
var sourceImageForm;
function startImageUpload(imageuploadform){
$(imageuploadform).find('.fileImage').css('visibility','hidden');
sourceImageForm = imageuploadform;
return true;
}
Below is the php script where it uploads the file (imageupload.php):
<?php
session_start();
$result = 0;
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
?>
<script language="javascript" type="text/javascript">
window.top.window.stopImageUpload(<?php echo $result;?>);
</script>
Finally when upload is finished it goes back to the stopUploadImage() function (QandATable.php) to display the message on whether file is successfully uploaded or not. This is also where I want the uploaded file name from the server to be appended.
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append('<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Your $_POST won't contain fileimagename. Instead, your form input was called fileImage. Use that instead:
// Check $_POST for fileImage, which was the form input name
if (isset($_POST['fileImage'])) {
$_SESSION['fileimagename'] = $_FILES['fileImage']['name'];
// Proceed with the file upload and save.
}
else {
// oops, can't proceed
}
On the JavaScript page, do some error checking when accessing the value:
<?php
session_start();
if (isset($_SESSION['fileimagename'])) {
$fileimagename = $_SESSION['fileimagename'];
// output JS code...
?>
<script type="text/javascript">Your JS code here...</script>
<?php
}
else {
// No filename - can't proceed with JavaScript code
// Display an eror or a message with instructions for user...
}
Note: Don't use the user-supplied filename to store the image! It opens you up to a directory traversal attack, and makes it possible for the user to write a file anywhere on your filesystem the web server has write-access to.
// This is unsafe!
move_uploaded_file($_FILES["fileImage"]["tmp_name"], "ImageFiles/" . $_FILES["fileImage"]["name"]);
Instead, it's common to store the value from $_FILES['fileImage']['name'] in your database, along with an identifier value for the actual file, and use the identifier to store it on disk.
$info = pathinfo($_FILES['fileImage']['name']);
// Get the original extension
$filext = $info['extension'];
// Make a unique filename and add the extension
$stored_filename = uniqid() . $filext;
// Use that to store the file on disk
move_uploaded_file($_FILES["fileImage"]["tmp_name"], $stored_filename);
// Now store BOTH $_FILES['fileImage']['name'] and $stored_filename in your database together
// The original user-supplied filename can be used for display, but isn't used on disk

Categories