Want to create a simple form to send the values and image to database, below is the php code -
Created two php file process_upload and connection
processs_upload.php
<?php
require 'connection.php';
$conn = Connect();
$name=$conn->real_escape_string($_POST['name']);
$mobile_number=$conn->real_escape_string($_POST['mobile_number']);
$email_id=$conn->real_escape_string($_POST['email_id']);
$type=$conn->real_escape_string($_POST['type']);
$query = "INSERT into tb_cform (name,mobile_number,email_id,type) VALUES('" . $name . "','" . $mobile_number . "','" . $email_id . "','" . $type . "')";
if ( 0 < $_FILES['image_file']['error'] ) {
echo 'Error: ' . $_FILES['image_file']['error'] . '<br>';
}
else{
$time=time();
if(($type=='image/png') || ($type=='image/gif') || ($type=='image/jpeg') || ($type=='image/pjpeg') || ($type=='image/jpg')){ //if file is image
if(move_uploaded_file($_FILES['image_file']['tmp_name'], 'pictures/'.$time.'_'.$_FILES['image_file']['name'])){
echo 'done ';
}else{
echo 'image error';
}
}else{//if file is video
if(move_uploaded_file($_FILES['image_file']['tmp_name'], 'videos/'.$time.'_'.$_FILES['image_file']['name'])){
echo 'done';
}else{
echo 'video error';
}
}
}
$conn->close();
?>
connection.php
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "";
$dbname = "database";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
Created a table in phpmyadmin and below is the table -
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE IF NOT EXISTS `tb_cform` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` text CHARACTER SET utf8 NOT NULL,
`mobile_number` int(11) NOT NULL,
`email_id` text NOT NULL,
`type` longblob NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
HTML form
<!DOCTYPE HTML>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="Boomer" />
<title>Uploader</title>
<link href="css/upload_css.css" media="screen" rel="stylesheet" type="text/css" />
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.form.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var optionsH = {
target: '#H_output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmitH, // pre-submit callback
uploadProgress: OnProgressH,
error: onerrorH,
success: afterSuccessH, // post-submit callback
resetForm: true // reset the form after successful submit
};
$('#MyUploadFormH').submit(function(){
var name=$("#name").val();
var mobile_number=$("#mobile_number").val();
var email_id=$("#email_id").val();
if((name!='') && (mobile_number!='') && (email_id!='')){
$('#MyUploadFormH').attr("action","process_upload.php");
$(this).ajaxSubmit(optionsH);
// return false to prevent standard browser submit and page navigation
return false;
}else{
$("#H_output").html("All field are required");
}
});
function beforeSubmitH(){
//check whether browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob)
{
if(!$('#imageInputH').val()) //check eHty input filed
{
$("#H_output").html("select picture or video to upload");
return false
}else{
$("#H_output").html("file selected");
}
var fsize = $('#imageInputH')[0].files[0].size; //get file size
var ftype = $('#imageInputH')[0].files[0].type; // get file type
switch(ftype)
{
case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg': case 'video/mp4': case 'video/3gp': case 'video/avi': case 'video/mkv':
case 'video/flv': case 'video/wmv': case 'video/ovb': case 'video/ogg':
break;
default:
$("#H_output").html("<b>"+ftype+"</b> Unsupported file type!");
return false
}
//Allowed file size is less than 1 MB (1048576)
if(fsize>10485760)
{
$("#H_output").html("<b>"+bytesToSize(fsize) +"</b> is too big! <br />Please reduce the size and try again.");
return false
}
document.getElementById("header_submit-btn").setAttribute("disabled", true);
$("#H_output").html("");
}
else
{
//Output error to older unsupported browsers that doesn't support HTML5 File API
$("#H_output").html("Please upgrade your phone!");
return false;
}
}
function OnProgressH(){
$("#upload_formH").hide();
$("#upload_loader_header").show();
}
//when error occur
function onerrorH(){
document.getElementById("header_submit-btn").removeAttribute("disabled", true);
$("#H_output").html("connection error...");
//$('#staff_bfr_uplad_prv_cnt').html("");
//progressboxH.hide();
//$('#MyUploadForm').resetForm();
$("#upload_formH").show();
$("#upload_loader_header").hide();
}
//after succesful upload
function afterSuccessH()
{
document.getElementById("header_submit-btn").removeAttribute("disabled", true);
$("#upload_formH").show();
$("#upload_loader_header").hide();
var logo_thumb=$("#header_pix_location").html();
$("img[id^='eml_header_logo']").attr('src',dp_thumb);
}
document.querySelector('#H_fileSelect').addEventListener('click', function(e){
var fileInput = document.querySelector('#imageInputH');
//clickH(fileInput); // Simulate the click with a custom event.
fileInput.click(); // Or, use the native click() of the file input.
$("#H_output").html("");
}, false);
$("#imageInputH").change(function(){
var fsize = $('#imageInputH')[0].files[0].size; //get file size
var ftype = $('#imageInputH')[0].files[0].type; // get file type
if(fsize>10485760){
$("#H_output").html("<b>"+bytesToSize(fsize) +"</b> is too big! <br />Please reduce the size and try again.");
document.getElementById("header_submit-btn").setAttribute("disabled", true);
}else{
$("#type").val(ftype);
$("#H_output").html("<span style='color: green;'>file selected</span>");
document.getElementById("header_submit-btn").removeAttribute("disabled", true);
}
});
//function to format bites bit.ly/19yoIPO
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
});
</script>
</head>
<body>
<div id="add_cpp_form">
<center>
<div style="float: none; width: 270px; padding: 10px;" id="upload_formH">
<form onSubmit="return false" method="post" enctype="multipart/form-data" id="MyUploadFormH">
<input type="text" class="form_input" id="name" name="name" value="" placeholder="Name" />
<input type="text" class="form_input" id="mobile_number" name="mobile_number" value="" placeholder="Mobile Number" />
<input type="text" class="form_input" id="email_id" name="email_id" value="" placeholder="Email Id" />
<input name="image_file" id="imageInputH" type="file" />
<input name="type" id="type" type="hidden" />
<input type="submit" id="header_submit-btn" class="effect1 ripple" value="Submit" />
<div id="H_fileSelect" class="effect1 ripple" style="border-radius: 0px;">Select</div>
<img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
</form>
<div id="H_output"></div>
</div>
<div id="upload_loader_header" style="float: left; display: none; text- align: center; width: 100%;">
<img style="float: none;" src="img/ajax-loader.gif" width="32" height="32" />
</div>
</center>
</div>
</body>
</html>
Now when i am running the code I am getting image error and video error message, the connection is successfully done but getting the message.
Try grant permissions as in
suppose your code are under /var/www/my_project
try chmod -R 664 /var/www/my_project.
Related
folks! I'm trying to implement an audio recorder within my website. What I want is to make the user save the recorded file directly to the database and to a subfolder in my website (called /speaking_audios). There follows the main files:
recorder.php
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>FlashWavRecorder demo</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js'></script>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/recorder.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>FlashWavRecorder</h1>
<p><strong>Upload requires php, i.e. example will not work on github.com</strong></p>
<div id="recorder-audio" class="control_panel idle">
<button class="record_button" onclick="FWRecorder.record('audio', 'audio.wav');" title="Record">
<img src="images/record.png" alt="Record"/>
</button>
<button class="stop_recording_button" onclick="FWRecorder.stopRecording('audio');" title="Stop Recording">
<img src="images/stop.png" alt="Stop Recording"/>
</button>
<button class="play_button" onclick="FWRecorder.playBack('audio');" title="Play">
<img src="images/play.png" alt="Play"/>
</button>
<button class="pause_playing_button" onclick="FWRecorder.pausePlayBack('audio');" title="Pause Playing">
<img src="images/pause.png" alt="Pause Playing"/>
</button>
<button class="stop_playing_button" onclick="FWRecorder.stopPlayBack();" title="Stop Playing">
<img src="images/stop.png" alt="Stop Playing"/>
</button>
<div class="level"></div>
</div>
<div id="recorder-audio2" class="control_panel idle">
<button class="record_button" onclick="FWRecorder.record('audio2', 'audio2.wav');" title="Record">
<img src="images/record.png" alt="Record"/>
</button>
<button class="stop_recording_button" onclick="FWRecorder.stopRecording('audio2');" title="Stop Recording">
<img src="images/stop.png" alt="Stop Recording"/>
</button>
<button class="play_button" onclick="FWRecorder.playBack('audio2');" title="Play">
<img src="images/play.png" alt="Play"/>
</button>
<button class="pause_playing_button" onclick="FWRecorder.pausePlayBack('audio2');" title="Pause Playing">
<img src="images/pause.png" alt="Pause Playing"/>
</button>
<button class="stop_playing_button" onclick="FWRecorder.stopPlayBack();" title="Stop Playing">
<img src="images/stop.png" alt="Stop Playing"/>
</button>
<div class="level"></div>
</div>
<div class="details">
<button class="show_level" onclick="FWRecorder.observeLevel();">Show Level</button>
<button class="hide_level" onclick="FWRecorder.stopObservingLevel();" style="display: none;">Hide Level</button>
<span id="save_button">
<span id="flashcontent">
<p>Your browser must have JavaScript enabled and the Adobe Flash Player installed.</p>
</span>
</span>
<div><button class="show_settings" onclick="microphonePermission()">Microphone permission</button></div>
<div id="status">
Recorder Status...
</div>
<div>Duration: <span id="duration"></span></div>
<div>Activity Level: <span id="activity_level"></span></div>
<div>Upload status: <span id="upload_status"></span></div>
</div>
<form id="uploadForm" name="uploadForm" action="upload.php">
<input name="authenticity_token" value="xxxxx" type="hidden">
<input name="upload_file[parent_id]" value="1" type="hidden">
<input name="format" value="json" type="hidden">
</form>
<h4>Configure Microphone</h4>
<form class="mic_config" onsubmit="return false;">
<ul>
<li>
<label for="rate">Rate</label>
<select id="rate" name="rate">
<option value="44" selected>44,100 Hz</option>
<option value="22">22,050 Hz</option>
<option value="11">11,025 Hz</option>
<option value="8">8,000 Hz</option>
<option value="5">5,512 Hz</option>
</select>
</li>
<li>
<label for="gain">Gain</label>
<select id="gain" name="gain">
</select>
</li>
<li>
<label for="silenceLevel">Silence Level</label>
<select id="silenceLevel" name="silenceLevel">
</select>
</li>
<li>
<label for="silenceTimeout">Silence Timeout</label>
<input id="silenceTimeout" name="silenceTimeout" value="2000"/>
</li>
<li>
<input id="useEchoSuppression" name="useEchoSuppression" type="checkbox"/>
<label for="useEchoSuppression">Use Echo Suppression</label>
</li>
<li>
<input id="loopBack" name="loopBack" type="checkbox"/>
<label for="loopBack">Loop Back</label>
</li>
<li>
<button onclick="configureMicrophone();">Configure</button>
</li>
</ul>
</form>
</div>
</body>
</html>
Database table "recordings" SQL structure:
CREATE TABLE `recordings` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`username_id` int(5) NOT NULL,
`username` varchar(50) NOT NULL,
`upload_file` longblob NOT NULL,
`filename` varchar(100) NOT NULL,
`currenttime` datetime NOT NULL,
`type` longtext NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
config.php
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=database','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
?>
upload.php
<?php
$save_folder = dirname(__FILE__) . "/speaking_audios";
if(! file_exists($save_folder)) {
if(! mkdir($save_folder)) {
die("failed to create save folder $save_folder");
}
}
function valid_wav_file($file) {
$handle = fopen($file, 'r');
$header = fread($handle, 4);
list($chunk_size) = array_values(unpack('V', fread($handle, 4)));
$format = fread($handle, 4);
fclose($handle);
return $header == 'RIFF' && $format == 'WAVE' && $chunk_size == (filesize($file) - 8);
}
$key = 'filename';
$tmp_name = $_FILES["upload_file"]["tmp_name"][$key];
$upload_name = md5(uniqid() .rand()). ".wav";
#$_FILES["upload_file"]["name"][$key];
$type = $_FILES["upload_file"]["type"][$key];
$filename = "$save_folder/$upload_name";
#$filename = "$save_folder/$upload_name";
$saved = 0;
if($type == 'audio/wav' && preg_match('/^[a-zA-Z0-9_\-]+\.wav$/', $upload_name) && valid_wav_file($tmp_name)) {
$saved = move_uploaded_file($tmp_name, $filename) ? 1 : 0;
}
if($_POST['format'] == 'json') {
header('Content-type: application/json');
print "{\"saved\": $saved}";
} else {
print $saved ? "Saved" : 'Not saved';
}
exit;
# Save a few info to database
include "config.php";
$username = $_SESSION['username'];
$stmt = $pdo->prepare("INSERT INTO `recordings` (username, filename, currenttime) VALUES (:username, :filename, NOW())");
$stmt->execute(array(':username' => $username, ':filename' => $upload_name));
?>
Well, I just want you to concentrate on the upload.php file and see what I'm doing wrong. I don't know if the problem is caused by the line "exit;" in the upload.php file. The file is being saved to the subfolder "/speaking_audios", but not to the database. Why? Maybe the problem is in the upload.php file lines:
include "config.php";
$upload_file=$upload_name; # also $upload_name
$username_id = $_SESSION['username'];
$stmt = $pdo->prepare("INSERT INTO `recordings` (username, filename, currenttime) VALUES (:username_id, :upload_file, NOW())");
$stmt->execute(array(':username_id' => $username_id, ':upload_file' => $upload_file));
There is also the main audio controller in javascript:
js/main.js
$(function () {
var $uploadStatus = $('#upload_status'),
$showLevelButton = $('.show_level'),
$hideLevelButton = $('.hide_level'),
$level = $('.control_panel .level');
var CLASS_CONTROLS = "control_panel";
var CLASS_RECORDING = "recording";
var CLASS_PLAYBACK_READY = "playback_ready";
var CLASS_PLAYING = "playing";
var CLASS_PLAYBACK_PAUSED = "playback_paused";
// Embedding flash object ---------------------------------------------------------------------------------------------
setUpFormOptions();
var appWidth = 24;
var appHeight = 24;
var flashvars = {'upload_image': 'images/upload.png'};
var params = {};
var attributes = {'id': "recorderApp", 'name': "recorderApp"};
swfobject.embedSWF("recorder.swf", "flashcontent", appWidth, appHeight, "11.0.0", "", flashvars, params, attributes);
// Handling FWR events ------------------------------------------------------------------------------------------------
window.fwr_event_handler = function fwr_event_handler() {
$('#status').text("Last recorder event: " + arguments[0]);
var name, $controls;
switch (arguments[0]) {
case "ready":
var width = parseInt(arguments[1]);
var height = parseInt(arguments[2]);
FWRecorder.uploadFormId = "#uploadForm";
FWRecorder.uploadFieldName = "upload_file[filename]";
FWRecorder.connect("recorderApp", 0);
FWRecorder.recorderOriginalWidth = width;
FWRecorder.recorderOriginalHeight = height;
$('.save_button').css({'width': width, 'height': height});
break;
case "no_microphone_found":
break;
case "microphone_user_request":
recorderEl().addClass("floating");
FWRecorder.showPermissionWindow();
break;
case "microphone_connected":
FWRecorder.isReady = true;
$uploadStatus.css({'color': '#000'});
break;
case "permission_panel_closed":
FWRecorder.defaultSize();
recorderEl().removeClass("floating");
break;
case "microphone_activity":
$('#activity_level').text(arguments[1]);
break;
case "recording":
name = arguments[1];
$controls = controlsEl(name);
FWRecorder.hide();
setControlsClass($controls, CLASS_RECORDING);
break;
case "recording_stopped":
name = arguments[1];
$controls = controlsEl(name);
var duration = arguments[2];
FWRecorder.show();
setControlsClass($controls, CLASS_PLAYBACK_READY);
$('#duration').text(duration.toFixed(4) + " seconds");
break;
case "microphone_level":
$level.css({width: arguments[1] * 50 + '%'});
break;
case "observing_level":
$showLevelButton.hide();
$hideLevelButton.show();
break;
case "observing_level_stopped":
$showLevelButton.show();
$hideLevelButton.hide();
$level.css({width: 0});
break;
case "playing":
name = arguments[1];
$controls = controlsEl(name);
setControlsClass($controls, CLASS_PLAYING);
break;
case "playback_started":
name = arguments[1];
var latency = arguments[2];
break;
case "stopped":
name = arguments[1];
$controls = controlsEl(name);
setControlsClass($controls, CLASS_PLAYBACK_READY);
break;
case "playing_paused":
name = arguments[1];
$controls = controlsEl(name);
setControlsClass($controls, CLASS_PLAYBACK_PAUSED);
break;
case "save_pressed":
FWRecorder.updateForm();
break;
case "saving":
name = arguments[1];
break;
case "saved":
name = arguments[1];
var data = $.parseJSON(arguments[2]);
if (data.saved) {
$('#upload_status').css({'color': '#0F0'}).text(name + " was saved");
} else {
$('#upload_status').css({'color': '#F00'}).text(name + " was not saved");
}
break;
case "save_failed":
name = arguments[1];
var errorMessage = arguments[2];
$uploadStatus.css({'color': '#F00'}).text(name + " failed: " + errorMessage);
break;
case "save_progress":
name = arguments[1];
var bytesLoaded = arguments[2];
var bytesTotal = arguments[3];
$uploadStatus.css({'color': '#000'}).text(name + " progress: " + bytesLoaded + " / " + bytesTotal);
break;
}
};
// Helper functions ---------------------------------------------------------------------------------------------------
function setUpFormOptions() {
var gain = $('#gain')[0];
var silenceLevel = $('#silenceLevel')[0];
for (var i = 0; i <= 100; i++) {
gain.options[gain.options.length] = new Option(100 - i);
silenceLevel.options[silenceLevel.options.length] = new Option(i);
}
}
function setControlsClass($controls, className) {
$controls.attr('class', CLASS_CONTROLS + ' ' + className);
}
function controlsEl(name) {
return $('#recorder-' + name);
}
function recorderEl() {
return $('#recorderApp');
}
// Button actions -----------------------------------------------------------------------------------------------------
window.microphonePermission = function () {
recorderEl().addClass("floating");
FWRecorder.showPermissionWindow({permanent: true});
};
window.configureMicrophone = function () {
if (!FWRecorder.isReady) {
return;
}
FWRecorder.configure($('#rate').val(), $('#gain').val(), $('#silenceLevel').val(), $('#silenceTimeout').val());
FWRecorder.setUseEchoSuppression($('#useEchoSuppression').is(":checked"));
FWRecorder.setLoopBack($('#loopBack').is(":checked"));
};
});
When the file is saved, a green message shows after the upload status in recorder.php. That is when clicking on the arrow to save/upload the upload.php comes into action, but is not shown. the user so to speak remains on the page recorder.php.
Anything after the exit will not be executed!
just try removing it...
Also after your query try adding :
if($stmt->errorCode() == 0) {
echo "success";
} else {
$errors = $stmt->errorInfo();
print_r($errors);
}
It may give some explanation.
Also id put my db execute before the line:
if($_POST['format'] == 'json') {
Also just noticed all your table fields are set to NOT NULL, but you only insert 3 fields. This would cause a error if they are left blank.
Your username_id field is set to int and I think you maybe your trying to populate it with username which maybe a varchar
I know where the problem is. It's just to use:
if(isset($_FILES['upload_file'])){
before $stmt. Simple as that... Solved problem.
I am currently using this php form to submit into our mySQL database with a "chip_number" and "order_number" also with a date and time stamp. We want to use this with no keyboard or mouse, just a scanner. Currently it tabs the first field and when the second field is scanned the form is submitted, which is working as intended but it completely starts the form over, i would like it to keep the first field (order_number) after submitting so we can scan multiple "chip_numbers" on the same "order_number" then have a Master submit button if you will to send it all through when the employee is done with that order number and start with a blank form. This is the script i am using. thanks to all in advance!
<!-- Insert -->
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MICROCHIP_TBL (chip_number,order_number)
VALUES
('$_POST[chip_number]','$_POST[order_number]')";
IF (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: TRY AGAIN HUMAN!";
}
mysqli_close($conn);
?>
<html>
<head>
<!-- Validate form function -->
<!--<script type="text/javascript">
// function validateForm()
// {
// var x=document.forms["chip_insert"]["order_number"].value;
// var y=document.forms["chip_insert"]["chip_number"].value;
// if (x==null || x=="")
// {
// alert("Please enter an Order Number.");
// document.forms["chip_insert"]["order_number"].focus();
// return false;
// }
// if (y==null || y=="")
// {
// alert("Please enter a Microchip Number.");
// document.forms["chip_insert"]["chip_number"].focus();
// return false;
// }
// }
</script>
-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
</script>
</head>
<body onLoad="document.chip_insert.order_number.focus();">
<center>
<h1>Jeffers HomeAgain Microchip Entry</h1>
<form name="chip_insert" id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post">
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
Tag Number: <input tabindex="2" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" /><br /><br />
<input tabindex="7" type="submit" />
</center>
</form>
header('Location: http://JVSIntranet/microchip/homeagain.php');
This code redirects back to the form, I guess. You should add the ordernumber so it can be picked up by the form.
$ordernr = $_POST['order_number'];
header("Location: http://JVSIntranet/microchip/homeagain.php?order_number=$ordernr"); //mark the double quotes
in your form code you will have to use something like
<?php $value = (isset($_GET['order_number'])) ? " value=$_GET['order_number'] " : ""; ?>
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" <?php echo $value; ?> required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
I finally got it. i had to take out the Return function from my form and i added this to my script:
$value = "";
if( isset( $_POST ["order_number"] )) $value = $_POST ["order_number"];
then i put this in my input line and it works fine:
value="<?php echo $value; ?>"
Before i proceed, i would like to say i am a beginner and i am trying to validate a form using ajax, for username availability. Validations are done. But, everytime the page gets redirected to the form action page (Even if there are errors). I want, if there are errors i get a alert message and if no errors then data is written to db. I have been trying this for quite some time but i think i messed up and i dont understand what is wrong. Please, correct my mistakes. I am just trying to learn. What i am doing wrong here and what should i do?
registration.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--<link rel="stylesheet" type="text/css" href="css/style.css"/>-->
<title>Using AJAX</title>
<script type="text/javascript" src="jquery-2.1.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#txtUsr').on('keyup', function(){
var username=$("#txtUsr").val();
var user_name_avail_result=$('.check');
var userCorrect=true;
if(username.length>2)
{
$.ajax({
type : 'POST',
cache:'false',
data : "username="+username,
url : "usr_available.php",
beforeSend: function()
{
user_name_avail_result.fadeIn(1000).html('<img src="green_ajax-loader.gif" /> ');
},
success: function(responseText) {
if(responseText == 200)
{
$(".check").html("<img src='available.png'/><span style='color:#59b200;'>Username available</span>");
}
else if(responseText ==201)
{
$(".check").html("<img src='not-available.png'/><span style='color:#ff0033;'>Username not available</span>");
userCorrect=false;
}
else if(responseText==202)
{
$(".check").html("Username too short");
userCorrect=false;
}
}
});
}
else
{
user_name_avail_result.html('<span style="color:#e50000;">Name too Short!</span>');
userCorrect=false;
}
if(username.length == 0) {
user_name_avail_result.html("");
userCorrect=false;
}
var exprUsr=/(^[A-Za-z][A-Za-z0-9]*([._-][a-z0-9]+){3,15})$/;
if(!exprUsr.test(username))
{
userCorrect=false;
}
});
$("#txtPwd").on('keyup',function(){
var regPwd=/^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{6,12})+$/;
var passTxt=$('#txtPwd').val();
var pwdCorrect=true;
if(!regPwd.test(passTxt))
{
$(".chkPwd").html('<div style="width:200px; height:80px; margin-left:190px; margin-top:-20px; text-align:left;"><span style="font-size:small; color:#ff0033;">Password must contain at least one digit, one lowercase, one uppdercase and one special character</span></div>');
pwdCorrect=false;
}
else
{
$(".chkPwd").html("");
}
if(passTxt.length==0)
{
$(".chkPwd").html("You Must Enter a Password");
pwdCorrect=false;
}
});
$("#txtUsr,#txtPwd,#txtMob").keydown(function(e) { <!-- Dont allow users to enter spaces for their username and passwords and Mobile Number-->
if (e.which == 32) {
return false;
}
});
$("#txtMob").keydown(function(e){<!--No other keys except number keys and backspace and tab work-->
if(e.which==8 || e.which==9)
return true;
if(e.which<48 || e.which>57)
return false;
});
$("#txtMob").on('keyup',function(){
var exprMob=/^[789]\d{9}$/;
var mobNum=$('#txtMob').val();
var mobCorrect=true;
if(!exprMob.test(mobNum))
{
if(mobNum.length<10)
{
$("#span3").html("Number must be minimum 10 characters long");
mobCorrect=false;
}
else
{
$("#span3").html("Number in wrong format");
mobCorrect=false;
}
}
else
{
$("#span3").html("");
}
});
function Validation(n){
if(userCorrect==false || pwdCorrect==false || window.mobCorrect==false)
{
alert("One or More field(s) is/are unfinished/empty. Please re-check.");
return false;
}
else
{
return true;
}
}
});
</script>
<script type="text/javascript">
function clearAll()
{
document.getElementById("txtUsr").value="";
document.getElementById("txtPwd").value="";
document.getElementById("txtMob").value="";
}
</script>
<style>
.chkPwd
{
margin-left:80px;
}
.check
{
margin-left:90px;
}
.form
{
margin:auto;
text-align:center;
font-family:Consolas;
font-size:medium;
}
.texts
{
font-family:Consolas;
}
#userDiv
{
background-color:#ccdbff;
height:320px;
width:500px;
border-radius:10px;
opacity:0.8;
}
#mainBody
{
background-color:#7a7acc;
width:100%;
height:100%;
}
</style>
</head>
<body class="form" id="mainBody">
<h1 style="color:#bfff00;">Registration</h1><br>
<form class="form" id="regForm" action="registration_success.php" method="POST" onsubmit="return Validation(this)">
<div class="form" id="userDiv"><br><br>
Username: <input class="texts" id="txtUsr" name="txtUsr" type="text" placeholder="Type user name here" autocomplete="off" maxlength="15" autofocus="autofocus" title="Please dont enter an aweful username!"/><br>
<span id="span1" class="check" style="font-size:small; color:"></span>
<br>
Password: <input type="password" id="txtPwd" class="texts" name="txtPwd" placeholder="Type password here" autocomplete="off" maxlength="12" title="Password must contain at least one digit, one lowercase, one uppdercase and one special character"/><br>
<span id="span2" class="chkPwd" style="font-size:small; color:red;">Min 6 and Max 12 Characters</span><br>
MobileNo.:<input type="text" maxlength="10" id="txtMob" class="texts" name="txtMob" placeholder="Enter your mobile number here" autocomplete="off" title="Please enter numbers only"/><br>
<span id="span3" class="chkMob" style="font-size:small; margin-left:10px; color:#ff0033; font-size:small;"></span><br>
<pre class="texts"> <input type="button" value="Back To LogIn" id="register" class="texts" name="register"/> <input type="submit" value="Submit" id="submit" class="texts" name="send"/> <input type="button" value="Reset" id="clear" onclick="clearAll()"/></pre>
</div>
</form>
</body>
</html>
user_available.php
<?php
if($_SERVER['REQUEST_METHOD']==='POST'){
if(!empty($_POST['username'])){
mysql_connect("localhost", "root","") or die ("Oops! Server not connected"); // Connect to the host
mysql_select_db("db_chkAJAX") or die ("Oops! DB not connected"); // select the database
// Check for the username posted
$username= mysql_real_escape_string($_POST["username"]); // Get the username values & prevent SQL-Injection
if(strlen($username)>2){
$check_query= mysql_query('SELECT Username FROM LoginRecord WHERE Username = "'.$username.'" ') or die("Cannot get data from table"); // Check the database
if(mysql_num_rows($check_query)<1){ // check num or rows 0 or greater than 0
echo 200;//Username doesnot exist in database
}
else{
echo 201;//Username exists in databse
}
} else {
echo 202;//Too short username
}
}
mysql_close($link);
return;//Stop execution
}
?>
registration_success.php
<!--Writing to the database-->
<?php
if(isset($_POST['send']) && !empty($_POST['txtUsr']) && !empty($_POST['txtPwd']) && !empty($_POST['txtMob']))
{
//Connecting to databse
$usr_name=test_input(strtolower($_POST['txtUsr']));
$pwd=$_POST['txtPwd'];
$mob=test_input($_POST['txtMob']);
$db_host='localhost';
$db_user='root';
$db_pwd='';
$conn=mysql_connect($db_host, $db_user, $db_pwd,true);
if(!$conn)
{
echo "Database connection Unsuccessful".mysql_error($conn)."<br>";
}
else
{
echo "Database connection Successful"."<br>";
}
//Creating a new database
$sql="CREATE DATABASE IF NOT EXISTS db_chkAJAX";
if (mysql_query($sql,$conn))
{
echo "Database db_student created successfully"."<br>";
}
else
{
echo "Error creating database: "."<br>";
}
//Creating a Table
$dataselect=mysql_select_db("db_chkAJAX",$conn);
if(!$dataselect)
{
die("Database not Selected".mysql_error()."<br>");
}
else
{
echo "Database Selected"."<br>";
}
$sql_create="CREATE TABLE IF NOT EXISTS LoginRecord (Username varchar (50), Password varchar(15), MobileNumber bigint(10))";
$qry=mysql_query($sql_create);
if(!$qry)
{
die("Table not created".mysql_error()."<br>");
}
else
{
echo "Table Created Successfully"."<br>";
}
//Inserting values into table
$data_insert="INSERT INTO LoginRecord(Username, Password, MobileNumber) VALUES('$usr_name', '$pwd', '$mob')";
$data_insert_query=mysql_query($data_insert);
if(!$data_insert_query)
{
die(" Unsuccessful data Insertion into table".mysql_error()."<br>");
}
else
{
echo "Data inserted into table successfully"."<br>";
}
//Closing the connection
mysql_close($conn);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
One problem, you are using html comments in your javascript instead of javascript comments, use //
http://www.jshint.com
Also, It looks like you need to set the check variables as global, since you are validating outside of the function that checks if they are valid.
I don't think you need to put this inside of Validate()
http://www.w3schools.com/js/js_form_validation.asp
I have made a deep search and tried a lot to send value automatically to other php page. I don't know is it possible or not. But if someone knows then please kindly tell me.
Here is the code what I am trying:
t.html // for browsing
<html>
<head>
<style>
#boox{
overflow:auto;
width:600px;
height:400px;
}
</style>
<script>
alert("hello");
</script>
<script>
function pict(str)
{ alert("hel");
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
xmlhttp = new XMLHttpRequest();
var picInput = document.getElementById('userfile').value;
var uploadpic = document.getElementById('upload').value;
document.getElementById('usf').innerHTML = picInput;
document.getElementById('upic').innerHTML = uploadpic;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// var resp = xmlhttp.responseText;
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
// alert(resp);
} alert("a");
xmlhttp.open( "POST", "show.php.php?q"="+str, true); //POST Because you use $_POST in php
xmlhttp.send();// not happening
}
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="take.php">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<input name="upload" type="submit" onChange ="pict(this.value)" class="box" id="upload" value=" Upload ">
</tr>
</table>
</form>
<div id="txtHint">here div </div>
</body>
</html>
take.php // this is the page that i am trying to send without submit to other php
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$con=mysql_connect("localhost","root",'');
mysql_select_db("project",$con) or die("error db");
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
mysql_close($con);
echo "<br>File $fileName uploaded<br>";
// i am trying to send parameter that is "fileName" through header to show.php
header("location:show.php");
}
?>
show.php
<HTML>
<head>
<script>
#showpic
{
overflow:auto;
width:600px;
height:400px;
border:#000000 2px solid;
}
</script>
<script>
function changeThis(){
xmlhttp = new XMLHttpRequest();
var formInput = document.getElementById('theInput').value;
var title = document.getElementById('title').value;
/* formInput will be undefined */
document.getElementById('newText').innerHTML = formInput;
document.getElementById('ntitle').innerHTML = title;
/* also undefined */
// var xmlHttp = null;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var resp = xmlhttp.responseText;
document.getElementById("txtHint").innerHTML=resp;
alert(resp);
}
}
//alert("yes");
xmlhttp.open( "POST", "file2.php?q=+" , true); //POST Because you use $_POST in php
xmlhttp.send('theInput='+ encodeURIComponent(formInput) +
'&newText='+ encodeURIComponent(formInput) +
'&ntitle='+ encodeURIComponent(title));
}
</script>
</head>
<div id="showpic">
<?php
//header("location:event.php");
echo"heloo00";
$con=mysql_connect("localhost","root",'');
mysql_select_db("project",$con) or die("error db");
$sql="select * from upload";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query))
{
$image=$row ['name'];
echo '<img src="data:image/png;base64,' . base64_encode( $row['content'] ) . '" />';
}
?>
</div>
<body>
<p> <span name id='ntitle'></span> </p>
<p>You wrote: <span id='newText'></span> </p>
<body>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
Title :<textarea name="des" rows="1" cols="25" required></textarea>
<br>
Write :<textarea name="cht" rows="25" cols="25" required >write</textarea>
<input type=submit name="submit" onclick='changeThis() value ='Post event'/>
</form>
<?PHP
if(isset($_GET['submit']))
{
$u=$_GET['des'];
$k=$_GET['cht'];
$q="insert into event (title,detail) value('$u','$k')";
$con=mysql_connect("localhost","root","") or die ("connection Error");;
mysql_select_db("project",$con) or die ("db Error");
$r=mysql_query($q) or die ("Query Error");;
}
?>
</body>
</html>
To share data between php documents without explicitly passing that data, you can store it in a $_SESSION variable. This makes data available between php scripts when they are access by a user during the same session. Sessions are way to much to explain here, but you can read up on them in the PHP Manual section on session handling. When you have more specific questions, post them here and we can help you with them.
Hello i have an recaptcha working with ajax but it's not inserting my form infos into database, it inserts empty rows and i dont have any clue why
Here is my code:
require_once('inc/recaptchalib.php');
$publickey = "6LdW1N0SAAAAADMIPPkOGd939meXV9a9qDwwcxbu"; // you got this from the signup page
$privatekey = "";
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
</script>
<script type="text/javascript">
function validateCaptcha()
{
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
//alert(challengeField);
//alert(responseField);
//return false;
var html = $.ajax({
type: "POST",
url: "ajax.recaptcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if(html == "success")
{
$("#captchaStatus").html("Success. Submitting form.");
return false;
// Uncomment the following line in your application
//return true;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
}
</script>
Here is the form that i want to insert into database:
<form id="loginform" name="loginform" action="" method="post" enctype="multipart/form-data" onSubmit="return validateCaptcha()" >
<fieldset class="step">
<p>
<label for="nick">Nickname:</label>
<input type="text" name="nick" value="" id="nicknamee" value="" >
</p>
<p>
<label for="email">Email:</label>
<input type="text" name="email" value="" id="email_comm" value="" >
</p>
<p>
<textarea class="text-input textarea wysiwyg" name="add_comment" id="text_commentt"></textarea>
</p>';?>
<div id="login">
<?php echo recaptcha_get_html($publickey);?>
<p style="color: red;" id="captchaStatus"> </p>
</div>
<?php
echo'
<p style="margin-top:200px;"><button id="vote_petiton_submit" type="submit" ></button>
</p>
</fieldset>
</form>
Now the verification of the reCaptcha and database insert file. Validation is ok just inserting datas in database not working proper, it doesnt post the values.
<?php
require_once('inc/recaptchalib.php');
require_once('engine/db.php');
$publickey = "6LdW1N0SAAAAADMIPPkOGd939meXV9a9qDwwcxbu"; // you got this from the signup page
$privatekey = "";
mysql_query("SET NAMES utf8");
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
?>success<?
$nick=$_REQUEST['nick'];
$type=0;
$email=$_REQUEST['email'];
$descr=$_REQUEST['add_comment'];
$descriere=strip_tags($descr,'<br><p><a><i><u><b>');
$id=150;
$insert = "INSERT INTO comments (`nickname`,`desc`,`email`,`type`,`id_pet_dem_des`)
VALUES ('$nick','$descriere','$email','$type',$id)";
$result = mysql_query($insert)
or die("query failed: " . mysql_error());
$queryz = "update petition set comments=comments+1 where id_petition='$id'";
$resultz = mysql_query($queryz)
or die("query failed: " . mysql_error());
}
else
{
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
}
?>
Thnx in advance.
i fixed it with changeing data from ajax post with
data: $('#loginform').serialize() + "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,