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.
Related
I have a program which is running server script on raspberry pi (client which is also a server). I'm scanning a barcode which then executes few commands (including generating XML file). When I submit the form with the 'serial' number, I want to be able to retrieve the filename (string) returned from AJAX ($_POST) method in server.php? if (isset($_POST['filename']) does not return the filename, how do I obtain filename with a single AJAX? and use it in PHP? I have no error messages, the $_POST['filename'] is empty. I tried separating the script into a different file and creating another AJAX calling that PHP script but it did not fully work and I wonder if there is a possibility to do it with a single AJAX and make PHP listen for the returned filename.
Or maybe is there a better way to obtain the filename of the external file than through client-side? (there is always single XML file waiting to be picked up).
server.php
<?php
$show_error = "";
if (isset($_POST['serial'])) {
$serialnumber = $_POST['serial'];
if ($serialnumber > 0) {
if (isset($_POST['filename'])) {
$filenamer = $_POST['filename'];
echo $filenamer;
} else {
echo "no filename returned from ajax call";
}
$remote_file_url = 'http://' . $_SERVER['REMOTE_ADDR'] . '/345.xml'; //FILENAME NEEDED
$local_file = '345.xml'; //FILENAME NEEDED
$copy = copy( $remote_file_url, $local_file );
}
?>
<html>
<body>
<form name="test" method="post">
<input type="number" name="serial" id="serial" value="1">
<input type="submit" name="">
</form>
</body>
<script type="text/javascript">
function scan(serialnumber)
{
return $.ajax({
url : 'http://localhost/test.php',
type : 'POST',
dataType : 'json',
data : { serial_no : serialnumber},
cache : false,
success : function(data) {
var filename = data[Object.keys(data)[1]];
console.log(filename);
}
});
};
scan(<?php echo $serialnumber; ?>);
</script>
</html>
test.php
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: text/json');
# Get the serial
$serial_no = $_POST['serial_no'];
$return['serial_no'] = $serial_no;
# Get the filename of the XML file
$filename = shell_exec('find /var/www/html/*.xml -printf "%f"');
$return['filename'] = $filename;
$return['scanpink'] = 1;
echo json_encode($return);
?>
As I mentioned in my comment, you don't have filename in php because your form does not include filename field. After receiveing filename from ajax you can do another ajax request with serial & filename fields or the second solution is to use a hidden field. After receiving data in ajax you cannot use them in php - You have to send it (filename) to php.
this is the flow I am trying to accomplish:
Form completed -> Data Sent to PHP File With Data -> PHP File Takes Data, Queries API -> PHP File Then Returns Query Results back to Original Page as an echo.
The round trip time for this should be around 10 seconds. Here is my form, AJAX, and PHP file.
Form
<form id="query_form">
<input type="text" id="query_input" name="query_input" required>
<button id="send_btn" type="submit" name="send_query" value="Submit Request">
</form>
AJAX
<script type="text/javascript">
$(document).on("click", "button[id='send_btn']", function(e){
e.preventDefault(); // Prevents any default actions by clicking submit in a form.
var query = $("#query_input").val(); // Gets the value of an input
$.ajax({
type: "POST",
url: "run.php",
data: {query:query},
success: function(r){ alert(r); }
});
});
</script>
PHP
<?php
require('RestClient.php');
$term = "";
if(isset($_POST['query'])){
$term = $_POST['query']
try {
$client = new RestClient('https://api.dataforseo.com/', null, '#########', '###########');
$post_array = array("language" => "en","key" => $term); // This is the term to search, correct?
$sv_post_result = $client->post('v2/kwrd_sv', array('data' => $post_array));
$search_volume = $sv_post_result["results"][0]['sv'];
echo "<div id='results_div'>
<table id='results_table'>
<tr class='results_table_row'>
<td id='SEO_Search_Volume_Cell'>
$search_volume <span>Approximate Number Of Searches Per Month</span>
</td>
</tr>
</table>
</div>";
} catch (RestClientException $e) {
echo "\n";
print "HTTP code: {$e->getHttpCode()}\n";
print "Error code: {$e->getCode()}\n";
print "Message: {$e->getMessage()}\n";
print $e->getTraceAsString();
echo "\n";
echo "An Error Has Occured, Please Try Again Later";
exit();
}
}
?>
Obviously the data echo'd back needs to appear on the same page as the form, yet nothing comes back. Why would this be?
try posting the data in a 'string' format, e.g.
var query = $("#query_input").val(); // Gets the value of an input
var queryString = 'query='+ query; and then use it in your $.ajax call with: data: queryString,
pick-up the value with $_POST['query']
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
}
I am using this code to make the user input a name to create a folder. I have modified the code to try and send the form data via jQuery and receive the success/failure message from PHP through jQuery.
However, when I enter the name of the folder, nothing happens. No folder is created nor any error displayed. Firebug does not show any error either.
This is the code I have till now:
create.php:
<html>
<head><title>Make Directory</title></head>
<body>
<div id="albumform">
<form id="album_form" method="post" action="createAlbum.php" enctype="multipart/form-data">
<p id="message" style="display:none;">
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
</p>
<input type="text" id="create_album" name="create_album" value="" />
<input type="button" onclick="return checkForm('album_form');" id="btn_album" name="btn_album" value="Create" />
</form>
</div>
</body>
</html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
/* $("#btn_album").click(function() { */
function checkForm(form) {
//create post data
var postData = {
"create_album" : $("#create_album").val()
};
//make the call
$.ajax({
type: "POST",
url: "createAlbum.php",
data: postData, //send it along with your call
success: function(response){
$('#message').fadeIn();
}
});
/* }); */
}
</script>
createAlbum.php:
<?php
/**********************
File: createDir.php
Author: Frost
Website: http://www.slunked.com
***********************/
// set our absolute path to the directories will be created in:
$path = $_SERVER['DOCUMENT_ROOT'] . '/web/photos/images/';
if (isset($_POST['btn_album'])) {
// Grab our form Data
$dirName = isset($_POST['create_album'])?$_POST['create_album']:false;
// first validate the value:
if ($dirName !== false && preg_match('~([^A-Z0-9]+)~i', $dirName, $matches) === 0) {
// We have a valid directory:
if (!is_dir($path . $dirName)) {
// We are good to create this directory:
if (mkdir($path . $dirName, 0775)) {
$success = "Your directory has been created succesfully!<br /><br />";
}else {
$error = "Unable to create dir {$dirName}.";
}
}else {
$error = "Directory {$dirName} already exists.";
}
}else {
// Invalid data, htmlenttie them incase < > were used.
$dirName = htmlentities($dirName);
$error = "You have invalid values in {$dirName}.";
}
}
?>
There are at least two seperate problems with your code:
In the php-file, you check if $_POST['btn_album'] is set. This field is not sent as it is not part of your ajax-request (You're only sending "create_album" : $("#create_album").val()). So the code that creates the folder is never executed.
Another problem is the part
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
in your response-message. This code is evaluated when the page loads, not during your ajax-request, so the php-variables $success and $error will always be undefined. You have to return those response-messages as response to the actual request and then use javascript to display them.
The ajax request has a bad habit of failing silently.
You should use jQuery post and take advantage of .success(), .complete(), and .error() functions to track your code.
Also use the console.log() to check if the parameters are sent corectly. I'll try out the code myself to see the problem.
http://api.jquery.com/jQuery.post/
Due to the nature of the $.ajax request, $_POST['btn_album'] is not sent. So your php file gets here
if (isset($_POST['btn_album'])) {
and returns false.
also you need to echo $error to get a response.
I need to take a CSV file from the client's machine and extract the data from it. I cannot save this CSV file, which is crucial (otherwise I would be laughing!). My PHP so far works like a charm:
upload.php
<?php
$file = $_FILES['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
$ext = substr($file["name"], strrpos($file["name"], '.') + 1);
$maxSize = 3000000;
//Check file extension, MIME-type and size limit (3 MB).
if ($ext == "csv") {
if ($file["type"] == "text/csv" ||
$file["type"] == "text/comma-separated-values") {
if ($file["size"] < $maxSize) {
//CSV -> JSON
$fileAsArray = Array();
if (($handle = fopen($file["tmp_name"], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$fileAsArray[] = $data;
}
fclose($handle);
}
echo json_encode($fileAsArray);
die(json_encode($fileAsArray));
}
else {
echo "File size: ".$file["size"]."bytes<br>Limit: ".$maxSize." (3MB)";
}
}
else {
echo "MIME-type: ".$file["type"]."<br>Required: text/csv";
}
}
else {
echo "File Extension: ".$ext."<br>Required: csv";
}
}
else
die("Cannot upload");
?>
Ignore the echo. It was just so I knew it was actually working. However, I've been using jQuery with this website and can't figure out the code to properly get the form to submit the file and retrieve the JSON data back (fileAsArray) at the same time. Here is my HTML/jquery in index.html:
<script type="text/javascript">
var csvData = {}; //My global variable (two-dimensional JSON array)
$(document).ready(function(){
$("#upload").click(function(){
alert('test');
$.ajax({
type: "POST",
url: "upload.php",
data: "don't know what goes here",
dataType: "json",
success: function (data) {
alert(data); //Tried everything here too. :(
}
});
});
});
and HTML:
<form method="POST" action="upload.php" enctype="multipart/form-data" class="file_upload">
<input id="getFile" type="file" name="file">
<input value="Extract Data" id="upload" type="button">
</form>
I tried type="submit" as well, and a bunch of other things including just a 'form' tag and letting jQuery handle the POST... Thanks. If there is a better way to do this, please let me know :)
(I've been struggling with this for several days now... Having gone through many renditions of the code outlined below, I've stripped it down to its basics.)
If you want to upload CSV data through an Ajax post request, you must read the content of the file and insert it into the data: "don't know what goes here" field. Currently, only HTML5 browsers provides FileReader API that enables JavaScript to read the file, for Internet Explorer you must use a Flash-based solution.
I wrote a jQuery plug-in before that works with HTML5 browsers and jQuery. It would work with jQuery 1.4 - I am not sure about jQuery 1.5.