I have an HTML form in which I have to upload 3 files.
I have to call a create.js script after form submission which uses getElementById to format the input in desired way. Then it uses a xmlHTTPRequest to call create.php which inserts the form data into mysql database, and in the mean time fetches some data that it sends back to create.js using json_encode.
So I don't use the form action attribute but instead use the onClick attribute on my Submit button to call create.js.
But I have to upload my 3 files also on clicking Submit. I tried using $_FILE['file1']['name'] and other $_FILE[][] variables, where I use <input type="file" name="file1" id="file1"> to uplaod my first file but it gave the following error:
Undefined index: file1 in C:\xampp\htdocs\mywebsite\sites\all\themes\danland\create.php on line 77
So how can I incorporate my code for storing uploaded files on my server in the same php that returns xmlhttp.responseText to my .js file ?
I also tried putting my code of uploading in upload.php and called it using <form action="the/correct/path/upload.php"> besides using onClick = "my_create.js_function()" in my submit button but it did not work
Note that I have read html upload using ajax and php and know that I cannot upload my file using xmlhttprequest, but I am not trying to do that. I want my xmlhttprequest to fetch data after submit is clicked and my submit button to also store my files.
My HTML form is:
<script src="http://localhost/mywebsite/sites/all/themes/danland/src/create.js">
</script>
<script type="text/javascript" src="http://localhost/mywebsite/sites/all/themes/danland/src/datepickr.js"></script>
<script>
window.onload = create_new_project_getoptions();
</script>
<div class="searchinterfacecontainer">
<p id="my_first_para"></p>
<p id="this_is_my_new_para"></p>
<h2>Enter Details</h2>
<form id="create_projectform1" name="create_projectform1" method="POST" enctype="multipart/form-data" action="http://localhost/mywebsite/sites/all/themes/danland/create_new_project_upload.php">
<input type="text" name="project_id" id="project_id" required/>
<input type="text" name="project_name" id="project_name" required/>
<input id="project_start_date" onClick="new datepickr('project_start_date')" required/>
<select id="project_geography" name="project_geography">
<option value="">Select Country </option>
</select><br/>
<input type="file" name="file1" id="file1">
<input type="file" name="file2" id="file2">
<input type="file" name="file3" id="file3">
<div class="searchinterfacebuttons"><input type="submit" class="searchinterfaceform1go" value="Search" onClick="create_new_project()"/> <button class="searchinterfaceform1go" type="reset" value="Reset"> Reset </button></div>
</form>
</div>
My create.js:
function create_new_project( )
{
alert("entered");
var project_id = document.getElementById("project_id").value;
var project_name = document.getElementById("project_name").value;
var project_start_date = document.getElementById("project_start_date").value;
// some more getElementByID
var error_para = document.getElementById("my_first_para");
var my_error = "";
error_para.innerHTML = my_error;
// some string manipulation with the above defined variables
project_start_date = date_fixer(project_start_date);
project_completion_date = date_fixer(project_completion_date);
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var params = "project_id=" + project_id + "&project_name=" + project_name ; // + some more parameters
var url = "http://localhost/mywebsite/sites/all/themes/danland/create.php";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var val = xmlhttp.responseText;
//alert(val);
var jsonData = JSON.parse(val);
// some manipulation with json data
var answer = document.getElementById("this_is_my_new_para");
answer.innerHTML = jsonData;
}
}
xmlhttp.send(params);
}
function date_fixer(my_date)
{
// code here that works fine
}
My create.php:
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'this_user');
define('DB_PASSWORD', 'this_password');
define('DB_DATABASE', 'mywebsite');
$project_id = $_POST["project_id"];
$project_name = $_POST["project_name"];
$project_start_date = $_POST["project_start_date"];
// some more $_POST[]
$date_status1 = date_fixer($project_start_date);
$date_status2 = date_fixer($project_completion_date);
//echo "date status 1 is $date_status1 and date_status2 is $date_status2";
if ( $date_status1 == -1 || $date_status2 == -1 ) // not a valid date
{
echo "The date was not in correct format. Please use the date picker";
}
else
{
try
{
$db = new PDO('mysql:host=' .DB_SERVER . ';dbname=' . DB_DATABASE . ';charset=utf8', DB_USERNAME, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query_geography = "INSERT into " . DB_TABLE . "( projectID, project_name, start_date) values ( (:pid), (:pname), (:sdate))";
$parameters1 = array(':pid'=>$project_id, ':pname'=>$project_name, ':sdate'=>$project_start_date);
$statement1 = $db->prepare($query_geography);
$statement1->execute($parameters1);
}
catch(Exception $e)
{
echo 'Exception -> ';
var_dump($e->getMessage());
}
}
function date_fixer($my_date)
{
// valid function that works fine
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file1"]["name"]);
$extension = end($temp);
print_r($temp);
print_r($extension);
if ( ( ($_FILES["file1"]["type"] == "image/gif") || ($_FILES["file1"]["type"] == "image/jpeg") || ($_FILES["file1"]["type"] == "image/jpg") || ($_FILES["file1"]["type"] == "image/pjpeg") || ($_FILES["file1"]["type"] == "image/x-png") || ($_FILES["file1"]["type"] == "image/png") ) && ($_FILES["file1"]["size"] < 20000) && in_array($extension, $allowedExts) )
{
if ($_FILES["file1"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file1"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file1"]["name"] . "<br>";
echo "Type: " . $_FILES["file1"]["type"] . "<br>";
echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file1"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file1"]["name"]))
{
echo $_FILES["file1"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file1"]["tmp_name"], "upload/" . $_FILES["project_file1"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["project_file1"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
to get values from $_FILE you have to set form enctype to multipart/form-data.
if you want to read the value of file field then in jQuery simply write $('#id_filefield').val();
Related
I have a simple HTML page that allows the user to select the amount of fields to enter information. Once the user selects a number, a Javascript onchange method is called that sends the parameter to a PHP page where data is retrieved from a database and stored in a datalist, that is dynamically appended to the HTML page.
When I access this function on the host PC, everything works perfectly. However, when I access this from a remote client, the input fields dont generate automatically.
Here is the code:
<html>
<head>
<script>
function GetInfo(str) {
if (str == "") {
document.getElementById("items").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("items").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/Return-List.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form method="POST" action="../php/Submit.php">
<label>Number of Items</label>
<input type="number" name="numberofitems" onchange='GetInfo(this.value)'>
<br/>
<div id="items"></div>
<input type="submit" value="Go" />
</form>
</body>
</html>
PHP:
<?php
include("connection.php");
if($conn->connect_error) {
die("Connection Failed");
} else {
$items = $_GET['q'];
$fields = "";
$query = mysqli_query($conn,"SELECT name, desc FROM ItemTB");
for($i=1; $i<=$items ; $i++) {
$fields .= "<label>Input</label>
<input list='items' name='items[]' />
<datalist id='items'>";
while($row = mysqli_fetch_array($query)) {
$fields .= "<option value='" . $row['name'] . " | " . $row['desc'] . "'> " . $row['desc'] . "</option>";
}
$fields .= "</datalist>";
}
echo $fields;
}
?>
I have tried using relative and fixed locations in the JavaScript, and limiting the results to 500. Limiting the database results works, and it is important to note that the table returns upwards of 170 000 results. This seems to be the issue here.
How do I retrieve the entire dataset? Is there a way to do this more efficiently, to pack all data without lag?
Thanks in advance.
I am calling a JS function using a form:
HTML form:
<form class="addBlock" method="post" name="addBlockForm">
<input type="image" id="addBlockBtn" name="addedBlock" src="images/addCassette.png" onclick="addBlock( <?php echo $rowSize + 1 ?>)">
<input type="hidden" name="specNum" value="<?= $_SESSION["specNum"] ?>">
</form>
Javascript function:
function addBlock(num) {
var form = document.forms['addBlockForm'];
var nb = document.createElement("input");
nb.type = "hidden";
nb.name = "NewBlockNum";
nb.value = ([num]);
form.appendChild(nb);
addBlock.submit();
}
Which submits the form, triggering the Php stored procedure and refreshes the page
PHP Stored procedure:
if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['NewBlockNum'])) {
// run the stored procedure for adding a new block
$callSP_addBlock = "{ CALL AddBlockByID( ?, ?, ? ) }";
$accID = $row[12];
$spID = $row[13];
$nBlockNum = $rowSize + 1;
$ad_params = array(
array($accID,SQLSRV_PARAM_IN),
array($spID, SQLSRV_PARAM_IN),
array($nBlockNum, SQLSRV_PARAM_IN),
);
/* Execute the query. */
$stmt6 = sqlsrv_query( $conn, $callSP_addBlock, $ad_params);
header('Location: '.$_SERVER['PHP_SELF']);
if( $stmt6 === false ) {
echo "Error in executing statement 6.\n";
die( print_r( sqlsrv_errors(), true));
}
}
The order on the page is the Php, then the JS function definition, and then the html form.
Everything works, however the new added data does not display in the page.
The data display code (that lives after the JS function, but before the form) is this
PHP Data display code:
<?php
do {
if (isset($row[15])) {
$timeStamp = //date_format($row[15], 'Y-m-d h:i');
$printedLabel = 'Printed ';
$printedClass = 'printed';
} else {
$timeStamp = '';
$printedLabel = '';
$printedClass = '';
}
if (isset($row[14])) {
$numOfPieces = $row[14];
$piecesLabel = 'Pieces ';
} else {
$numOfPieces = '';
$piecesLabel = '';
}
echo '<div class="'.$printedClass.'cassetteDataRow">
'.$row[9].'<br>
<form action="#" class="printForm" method="post" name="printedCass"><br>
<input type="image" id="cassPrintBtn" name="cPrinted" src="images/cassetteIcon.png" onclick="cassPrint(1)"><br>
<input type="hidden" name="'.$row[0].'" value="'.$row[0].'"><br>
<input type="hidden" name="specNum" value="'.$specNum.'"><br>
<input type="hidden" name="BlockID" value="'.$row[10].'"><br>
</form><br/>
'.$numOfPieces.' '.$piecesLabel.'<br>
'.$printedLabel.' '.$timeStamp.'
<input type="image" id="cassInfoBtn" src="images/cassettePrintBtn.png" onclick="div_show('.$row[10].')">
</div> <br/>';
} while ($row = sqlsrv_fetch_array($stmt));
?>
I have tried moving the php for the stored procedure call below the form (didn't work),I tried form action to $_SERVER['PHP_SELF'] and location.reload(); (also didn't work).
Any advice is greatly appreciated.Thank you
i'm having trouble uploading image with other input text form and send to ajax_php_file.php. But only image is uploaded, my input text is all empty. Would appreciate if anyone can assist here. Thanks alot.
<div id="imagebox">
<div class="image_preview">
<div class="wrap">
<img id="previewing" />
</div>
<!-- loader.gif -->
</div><!--wrap-->
<!-- simple file uploading form -->
<form id="uploadimage" method="post" enctype="multipart/form-data">
<input id="file" type="file" name="file" /><br>
<div id="imageformats">
Valid formats: jpeg, gif, png, Max upload: 1mb
</div> <br>
Name:
<input id="name" type="text"/>
<input id="cat" type="hidden" value="company"/>
Description
<textarea id="description" rows="7" cols="42" ></textarea>
Keywords: <input id="keyword" type="text" placeholder="3 Maximum Keywords"/>
<input type="submit" value="Upload" class="pre" style="float:left;"/>
</form>
</div>
<div id="message">
</div>
script.js
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
var name = document.getElementById("name").value;
var desc = document.getElementById("description").value;
var key = document.getElementById("keyword").value;
var cat = document.getElementById("cat").value;
var myData = 'content_ca='+ cat + '&content_desc='+desc+ '&content_key='+key+ '&content_name='+name;
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this,myData), // Data sent to server, a set of key/value pairs representing form fields and values
//data:myData,
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
// Function to preview image
$(function() {
$("#file").change(function() {
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewing').attr('src','noimage.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$("#file").css("color","green");
$('#image_preview').css("display", "block");
$('#previewing').attr('src', e.target.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
};
});
ajax_php_file.php
<?php
session_start();
$user_signup = $_SESSION['user_signup'];
if(isset($_FILES["file"]["type"]))
{
$name = filter_var($_POST["content_name"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$ca = filter_var($_POST["content_ca"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$desc = filter_var($_POST["content_desc"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$key = filter_var($_POST["content_key"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
$imagedata = addslashes(file_get_contents($_FILES['file']['tmp_name']));
$imagename= ($_FILES['file']['name']);
$imagetype =($_FILES['file']['type']);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 1000000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
mysql_query("INSERT INTO upload(name,picname,image,type,email,cat,description,keyword) VALUES('".$name."','".$imagename."','".$imagedata."','".$imagetype."','".$user_signup."','".$ca."','".$desc."','".$key."')");
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>
the format of the formData maybe incorrect. Change it like the following:
var myData = {'content_ca':cat,
'content_desc':desc
}
i think you are using jquery
So you can use
data:$("#uploadimage").serialize(),
i have a problem with my simple program in php that include an alert javascript.
This is the code:
<?php
function iva(){
$country='IT';
$vatnum=$_POST['n'];
$a="Work";
$b="NotWork";
$url='http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
$response = file_get_contents($url);
//global $a, $b;
if( $response == 'true' ){
echo $a;
}
if ($response != 'true'){
echo $b;
}
}
?>
<script>
function ivaz(){
alert("<?php iva() ?>");
}
</script>
<form method="post">
<input name="n" type="textarea" >
<input onclick="ivaz();" value="Validate" type="submit"> </input> </form>
My program take a value from input text box and pass the value to php script that return true or false in a javascript alert. The program work, but return previous value passed in input box.
Can someone help me to solve it?
Thanks guys.
No, it doesn't work that way. If you want to call a PHP function from Javascript without the page refreshing, you need an XMLHttpRequest.
Example:
<?php
// your php process when called by XMLHttpRequest
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$vatnum = $_POST['n'];
$country='IT';
$a = "Work";
$b = "NotWork";
$url = 'http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
$response = file_get_contents($url);
//global $a, $b;
if( $response == 'true' ){
echo $a;
} else {
echo $b;
}
exit;
}
?>
<form method="post" id="form1">
<input name="n" type="text" id="n" />
<input value="Validate" type="submit">
</form>
<script type="text/javascript">
// when the form is submitted
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault();
var n = document.getElementById('n').value; // get the textbox value
var xmlhttp = new XMLHttpRequest();
var params = 'n=' + n;
var php_url = document.URL;
xmlhttp.open('POST', php_url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
alert(response); // alert the server response
}
}
xmlhttp.send(params);
});
</script>
Remove onclick="ivaz();" from input tag
You cannot run the php script without reloading the page as php is generated serverside and javascript runs clientside.
i have the following HTML, JavaScript and PHP code to upload a text file which has a table and display it in the same page,
HTML:
<panel action="#" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" onchange="return ajaxFileUpload(this);">
</panel>
<iframe width="300px" height="300px" name="upload_iframe" id="upload_iframe" ></iframe>
JavaScript:
function ajaxFileUpload(upload_field)
{
var filename = upload_field.value;
upload_field.form.action = 'upload_file.php';
upload_field.form.target = 'upload_iframe';
upload_field.form.submit();
return true;
}
PHP:upload_file.php
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$filepath = $_FILES["file"]["name"];
if (file_exists($filepath)) {
$file = fopen($filepath, 'r');
echo '<table border=1>';
while (!feof($file)) {
$line = fgets($file);
$first_char = $line[0];
if ($first_char != '*' && $first_char != '^' && trim($line) != '') {
if (strstr($line, '|')) {
$split = explode('|', $line);
echo '<tr>';
foreach($split as $line) {
echo '<td>'.$line.'</td>';
}
echo '</tr>';
} else {
echo '<tr><td>'.$line.'</td></tr>';
}
}
}
echo '</table>';
} else {
echo 'the file does not exist';
}
}
?>
Now, i have the following php code to read/extract the file contents and display it in another text file, but i cannot get the output with this code. This code works fine when i tried to read/extract the values form an input in html page, am i thinking in the right direction ? how can i achieve this?
PHP:
file_put_contents($file, "\n File Contents: ", FILE_APPEND | LOCK_EX);
//$ret = file_put_contents($file, $_POST['file'], FILE_APPEND | LOCK_EX);
ajaxFileUpload cannot send a $_FILESvariable (only with exporer or old browsers)
I sugest you to Upload your file with normal file input.
You don't need copy the uploaded file to a directory after sent form.
Only get the temporany file contents with file_get_contents of $_FILES["file"]["tmp_name"];