Hi all you fantastic people. I'm a bit of a newbie on this.
I want to local select a file -> greyscale and downscale it (because it offen comes from a mobile devices) -> And then upload it to the ocr.space
Here is what I have so far on downscale:
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width=800
canvas.height=600
ctx.drawImage(img, 0, 0, 800, 600);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
<html>
<head>
<title>Upload PNG, JPG file</title>
</head>
<body>
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<canvas id="imageCanvas" name="imageCanvas"></canvas>
</body>
</html>
How do I send it to OCR with the following code so far:
(My OCR code takes file input, but I have a canvas because I need to downscale it first).
<?php
if(isset($_POST['submit']) && isset($_FILES)) {
require __DIR__ . '/vendor/autoload.php';
$target_dir = "uploads/";
$uploadOk = 1;
$FileType = strtolower(pathinfo($_FILES["attachment"]["name"],PATHINFO_EXTENSION));
$target_file = $target_dir . generateRandomString() .'.'.$FileType;
// Check file size
if ($_FILES["attachment"]["size"] > 990000) {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, filen er desværre for stor";
$uploadOk = 0;
}
/*if($FileType != "png" && $FileType != "jpg") {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, det skal være en jpg, jpeg eller png fil";
$uploadOk = 0;
}*/
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["attachment"]["tmp_name"], $target_file)) {
uploadToApi($target_file);
} else {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, der skete en fejl da foto blev uploadet.";
}
}
} else {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, venligst upload en fil";
}
function uploadToApi($target_file){
require __DIR__ . '/vendor/autoload.php';
$fileData = fopen($target_file, 'r');
$client = new \GuzzleHttp\Client();
try {
$r = $client->request('POST', 'https://api.ocr.space/parse/image',[
'headers' => ['apiKey' => 'xxxxxxxx'],
'multipart' => [
[
'name' => 'file',
'contents' => $fileData
]
]
], ['file' => $fileData]);
$response = json_decode($r->getBody(),true);
if($response['ErrorMessage'] == "") {
?>
<html>
<head>
<title>Result</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.min.js'></script>
</head>
<body>
<div class="form-group container">
<label for="exampleTextarea">Result</label>
<input type="text" id="nummerplade" name="nummerplade" value="<?php foreach($response['ParsedResults'] as $pareValue) {echo $pareValue['ParsedText'];}?>">
<textarea class="form-control" id="exampleTextarea" rows="30"><?php foreach($response['ParsedResults'] as $pareValue) {echo $pareValue['ParsedText'];}?></textarea>
</div>
</body>
</html>
<?php
} else {
header('HTTP/1.0 400 Forbidden');
echo $response['ErrorMessage'];
}
} catch(Exception $err) {
header('HTTP/1.0 403 Forbidden');
echo $err->getMessage();
}
}
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
I'm writing this answer to clarify how to apply the information referenced in my previous comment. You won't use the $_FILES variable at all. You will instead post your canvas as a data url in a normal variable through ajax and you will access it through the $_POST variable. Then you will process this data url to get the binary image and do everuting you want with it, i.e. save it to a file, post it to ocr service, etc.
The following code on the client side uses jquery, you have to download it in the same dir or replace the src attribute with a public available url (CDN):
<html>
<head>
<script src="jquery-3.6.0.min.js"></script>
<script>
$(function() {
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
var img = new Image();
img.onload = function() {
canvas.width=80
canvas.height=60
ctx.drawImage(img, 0, 0, 80, 60);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
$('#upload').click(function() {
var canvasData = canvas.toDataURL("image/png");
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: canvasData
}
}).done(function(o) {
alert('Image sent to the server');
});
});
});
</script>
</head>
<body>
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<canvas id="imageCanvas" name="imageCanvas"></canvas>
<button id="upload">Upload</button>
</body>
</html>
The php script should be like this:
<?php
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//... do anything you want with $fileData ...
?>
I have written a code to insert the values into the database table using ajax. If u see the image below ,the values are appeared in the text boxes and when pressed add areas button, these values must be added to the table.
image:
From the image, the values of X,Y,W and H are gathered and when the add areas button is clicked, it should insert the values of x,y,w and h in the table.
index.php:
<table>
<tr>
<div class="actions">
<input type="button" id="btnView" value="Display areas" class="actionOn" />
<input type="button" id="btnReset" value="Reset" class="actionOn" />
<input type="button" id="btn_add" value="add areas" class="actionOn" />
</div>
<br>
<div id="output" class='output'> </div>
</table>
<p>X:<input type= "text" id="x" name ="x" value="-">
<p>Y:<input type= "text" id="y" name ="y" value="-">
<p>W:<input type= "text" id="w" name ="w" value="-">
<p>H:<input type= "text" id="h" name ="h" value="-">
<script>
var selectionExists;
function areaToString (area) {
document.getElementById('x').value = area.x;
document.getElementById('y').value = area.y;
document.getElementById('w').value = area.width;
document.getElementById('h').value = area.height;
return (typeof area.id === "undefined" ? "" : (area.id + ": ")) + area.x + ':' + area.y + ' ' + area.width + 'x' + area.height + '<br />'
}
$('#btn_add').click(function(){
var x_value= document.getElementById('x').value;
var y_value= document.getElementById('y').value;
var w_value= document.getElementById('w').value;
var h_value= document.getElementById('h').value;
$.ajax({
type:'POST',
url: 'server.php',
data:{
'x_value': x_value,
'y_value': y_value,
'w_value': w_value,
'h_value': h_value
},
success: function(data){
alert("x:" + x_value +"y:" +y_value+"w:" +w_value+"h:" +h_value);
}
});
});
function output (text) {
$('#output').html(text);
}
// Log the quantity of selections
function debugQtyAreas (event, id, areas) {
console.log(areas.length + " areas", arguments);
};
// Display areas coordinates in a div
function displayAreas (areas) {
var text = "";
$.each(areas, function (id, area) {
text += areaToString(area);
});
output(text);
};
</script>
Server.php:
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'project_focus');
if(isset($_POST['x_value'])){
$x= $_POST['x_value'];
$valid="SELECT * FROM sample";
$validdb=mysqli_query($db, $valid);
while (mysqli_fetch_array($validdb)){
$add_x= "INSERT INTO sample (x_value) VALUES ($x)";
mysqli_query($db, $add_x);
}
}
?>
The database table name is sample and its fields are id, x_value, y_value , w, h.
The server.php is the file where i tried to use the mysql query to insert the values into the table. but when i run the code, the output is not achieved. The insert values did not work. I think i made some mistake with the query i think. but i couldnt figure it out. Can someone help me fix this problem.
Did you try to remove the while clause?
You shouldn't need to first query the database in order to do the insert. Just executing the connect and insert commands should work.
Be sure that the other columns in the table are not required, and are set as DEFAULT NULL, so that the query doesn't error on other columns not being set in your insert.
$add_x= "INSERT INTO sample (x_value) VALUES ($x)";
mysqli_query($db, $add_x);
HTML, CSS, and JavaScript should be more like
//<![CDATA[
/* js/external.js */
let get, post, doc, htm, bod, nav, M, I, mobile, S, Q, aC, rC, tC, shuffle, rand; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, context)=>{
const x = new XMLHttpRequest;
const c = context || x;
x.open('GET', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
x.send();
}
post = function(url, send, success, context){
const x = new XMLHttpRequest;
const c = context || x;
x.open('POST', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
if(typeof send === 'object' && send && !(send instanceof Array)){
if(send instanceof FormData){
x.send(send);
}
else{
const fd = new FormData;
for(let k in send){
fd.append(k, JSON.stringify(send[k]));
}
x.send(fd);
}
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
aC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.add(...a);
return aC;
}
rC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.remove(...a);
return rC;
}
tC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.toggle(...a);
return tC;
}
shuffle = array=>{
let a = array.slice(), i = a.length, n, h;
while(i){
n = Math.floor(Math.random()*i--); h = a[i]; a[i] = a[n]; a[n] = h;
}
return a;
}
rand = (min, max)=>{
let mn = min, mx = max;
if(mx === undefined){
mx = mn; mn = 0;
}
return mn+Math.floor(Math.random()*(mx-mn+1));
}
// magic below
const x = I('x'), y = I('y'), w = I('w'), h = I('h'), display = I('display');
const reset = I('reset'), add = I('add'), error = I('error');
function valid(){
let xv = x.value, yv = y.value, wv = w.value, hv = h.value;
if(xv === '' || isNaN(xv) || yv === '' || isNaN(yv) || wv === '' || isNaN(wv) || hv === '' || isNaN(hv)){
error.textContent = 'Invalid Number';
return false;
}
error.textContent = ''; return true;
}
x.oninput = y.oninput = w.oninput = h.oninput = ()=>{
valid();
}
display.onclick = ()=>{
const fd = new FormData; fd.append('get_xywh', true);
post('xywh.php', fd, data=>{
output.innerHTML = '';
data.xywh.forEach(o=>{
const sect = M('div'), sx = M('div'), sy = M('div'), sw = M('div');
const sh = M('div');
sx.textContent = 'X: '+o.x; sy.textContent = 'Y: '+o.y;
sw.textContent = 'W: '+o.w; sh.textContent = 'H: '+o.h; sect.appendChild(sx);
sect.appendChild(sy); sect.appendChild(sw); sect.appendChild(sh);
output.appendChild(sect);
});
});
}
reset.onclick = ()=>{
x.value = y.value = 0; w.value = h.value = 1; error.textContent = '';
}
add.onclick = ()=>{
if(valid()){
const fd = new FormData;
fd.append('x', x.value); fd.append('y', x.value); fd.append('w', w.value);
fd.append('h', h.value);
post('xywh.php', fd, json=>{
error.textContent = json.success ? 'Hacker' : 'Content Added';
});
}
}
}); // end load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body,.main{
width:100%; height:100%; background:#ccc;
}
.main{
padding:10px;
}
.er{
color:#900;
}
#xywh{
display:flex; flex-wrap:wrap; align-content:top center;
}
#xywh>*{
margin-bottom:7px;
}
#xywh>label{
flex:0 5%; text-align:center; padding-top:3px;
}
input{
padding:3px 5px; border:0;
}
input[type=number]{
border-radius:3px;
}
#xywh>input{
flex:0 95%;
}
.main{
text-align:center;
}
.main>input[type=button]{
background:linear-gradient(#1b7bbb,#147); color:#fff; font:bold 14px Tahoma, Geneva, sans-serif; padding:5px 10px; border-radius:5px;
}
#error{
margin-top:5px;
}
#output{
background:#000; color:#0c0; text-align:left; padding:5px 10px; margin:15px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>index.php</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<div id='xywh'>
<label for='x'>X:</label><input id='x' type='number' min='0' value='0' />
<label for='y'>Y:</label><input id='y' type='number' min='0' value='0' />
<label for='w'>W:</label><input id='w' type='number' min='1' value='1' />
<label for='h'>H:</label><input id='h' type='number' min='1' value='1' />
</div>
<input id='display' type='button' value='Display Areas' />
<input id='reset' type='button' value='RESET' />
<input id='add' type='button' value='Add Area' />
<div id='error' class='er'></div>
<div id='output'>No Data Requested</div>
</div>
</body>
</html>
Put your MySQL connect.php in a restricted folder with permission 700.
<?php /* restricted/connect.php */
$db = #new mysqli('host', 'username', 'password', 'database');
?>
Let's say you have the following table made in MySQL like:
`CREATE TABLE xywh(
x INT NOT NULL,
y INT NOT NULL,
w INT NOT NULL,
h INT NOT NULL
)ENGINE=InnoDB;`
Now in a folder with the normal permission 755 (directly in your site root in this case)
<?php /* xywh.php */
if(!isset($_SERVER['HTTPS'])){ // force https or comment out if no https - but why are you making a site with no https?
header('LOCATION:https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']); die;
}
$o = new StdClass;
if(isset($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'])){
$x = $_POST['x']; $y = $_POST['y']; $w = $_POST['w']; $h = $_POST['h'];
$r1 = '/^(0|[1-9]+[0-9]*$/'; $r2 = '/^[1-9]+[0-9]*$/';
if(!preg_match($r1, $x) || !preg_match($r1, $y) || !preg_match($r2, $w) || !preg_match($r2, $w)){
$o->hacker = true;
}
else{
require_once 'restricted/connect.php';
$s = $db->prepare('INSERT xywh (x, y, w, h) VALUES (?, ?, ?, ?)');
$s->bind_param('iiii', $x, $y, $w, $h); $s->execute(); $s->close(); $db->close();
$o->success = true;
}
}
elseif($_POST['get_xywh']) && $_POST['get_xywh'] === true){
require_once 'restricted/connect.php'; $a = [];
if($q = $db->query('SELECT x, y, w, h FROM xywh')){
while($r = $q->fetch_object()){
$a[] = $r;
}
$q->close();
}
$o->xywh = $a; $db->close();
}
else{
$o->hacker = true;
}
echo json_encode($o);
?>
Note that this is a very crude and simple example. You should have users that are allowed to input the data. So, you need a login that verifies users first. It's much more work. Also, this example just INSERTs a new row no matter if one exists that is the same... which, is what you would want if there is more than one of the same. If not, you'll have to test for sameness with a WHERE condition, and do an UPDATE if it already exists. Make sure you use prepared statements, unless you are doing very simple queries. Good Luck... this might take a while to understand. It's mostly an AJAX example for you.
i have an array in java script, that array have file name and file path, now i have to assign that array in php and upload that file which are store in array, what can i do please give me solutions.
This is my javascript
<script type="text/javascript">
var arrImgNPath = [];
var arrUniqueIds = [];
function myFunction() {
var files = $('#filesID').prop("files");
var names = $.map(files, function(val) { return val.name; });
console.log(names);
console.log("N the final result is :");
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
//$('#str').val(JSON.stringify(dict));
console.log("obj value :",dict);
}
}
function removeImageDataFromArray(spanId){
console.log("spanID--------------------------------------"+spanId);
arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; });
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
console.log("obj value :",dict);
}
}
function uniqId() {
while (1) {
var uid = Math.round(new Date().getTime() + (Math.random() * 100));
var isPresent = false;
for(var i=0; i<arrUniqueIds.length; i++){
var idFromArray = arrUniqueIds[i];
if (uid == idFromArray){
isPresent = true;
}
}
if (isPresent === false) {
return uid;
}
}
}
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#filesID").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
//console.log(files);
var filePath = $(this).val();
//console.log("fake pathddddddddddd"+filePath);
for (var i = 0; i < filesLength; i++) {
var tmppath = URL.createObjectURL(event.target.files[0]);
filePath =tmppath;
var f = files[i];
var randomId = uniqId();
var dict = {};
dict.name = f.name;
dict.path = filePath;
dict.ID = randomId;
arrImgNPath[arrImgNPath.length] = dict;
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
//console.log("bfsd dsf sdfdsfds"+e.target.result);
// console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);
$("<span id=\"" + randomId + "\" class=\"pip\" >" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#filesID");
$(".remove").click(function(){
//$(this).find("span").attr("id", "myspan_"+i);
console.log("files id values :"+ $(this).parent(".pip").attr("id"));
removeImageDataFromArray($(this).parent(".pip").attr("id"));
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API");
}
});
</script>
dict is my array how can assign that array in php and upload in file,
you can check in console to gat the value
php file
<!DOCTYPE html>
<head>
<style>
input[type="file"] {
display: block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
padding: 1px;
cursor: pointer;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post" enctype="multipart/form-data" >
<h3>Upload your images</h3>
<input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >
<input type="submit" name="submit" >
<input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>
whenever click the clickMe button you can the file name and file path in console check it and please help me
Sorry for the late return. I am not 100% sure if this is what you wanted. But i did it anyway :). Thanks to #Ben_Lee with his answer I managed to wrap the initiation inside a function.
var arrImgNPath = [];
var arrUniqueIds = [];
function myFunction() {
var files = $('#filesID').prop("files");
var names = $.map(files, function(val) { return val.name; });
console.log(names);
console.log("N the final result is :");
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
//$('#str').val(JSON.stringify(dict));
console.log("obj value :",dict);
}
}
function removeImageDataFromArray(spanId){
console.log("spanID--------------------------------------"+spanId);
arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; });
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
console.log("obj value :",dict);
}
}
function uniqId() {
while (1) {
var uid = Math.round(new Date().getTime() + (Math.random() * 100));
var isPresent = false;
for(var i=0; i<arrUniqueIds.length; i++){
var idFromArray = arrUniqueIds[i];
if (uid == idFromArray){
isPresent = true;
}
}
if (isPresent === false) {
return uid;
}
}
}
function initiateFiles(file) {
var tmppath = URL.createObjectURL(event.target.files[0]);
filePath =tmppath;
var f = file;
var randomId = uniqId();
var dict = {};
dict.name = f.name;
dict.path = filePath;
dict.ID = randomId;
arrImgNPath[arrImgNPath.length] = dict;
var fileReader = new FileReader();
fileReader.onload = (function(e) {
//var file = e.target;
//console.log("bfsd dsf sdfdsfds"+e.target.result);
// console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);
$("<span id=\"" + randomId + "\" class=\"pip\" >" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#filesID");
$(".remove").click(function(){
//$(this).find("span").attr("id", "myspan_"+i);
console.log("files id values :"+ $(this).parent(".pip").attr("id"));
removeImageDataFromArray($(this).parent(".pip").attr("id"));
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#filesID").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
var filePath = $(this).val();
for (var i = 0; i < filesLength; i++) {
initiateFiles(files[i]);
}
console.log(arrImgNPath);
var myJSON = JSON.stringify(arrImgNPath);
$("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");
});
} else {
alert("Your browser doesn't support to File API");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post" action="yourOther.php" enctype="multipart/form-data" >
<h3>Upload your images</h3>
<input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >
<input type="submit" name="submit" >
<input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>
Here i created a hidden input, which stores the array.
$("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");
And then assigned an action to the form to send the data to another php file.
<form method="post" action="yourOther.php" enctype="multipart/form-data" >
And now it is time to get the data and process:
<?php
$data = json_decode($_POST['myJSON']);
foreach ($data as $key => $value) {
echo " Name : $value->name <hr>";
echo " Path : $value->path <hr>";
echo " ID : $value->ID <hr>";
}
?>
I hope this helps, if you have further questions, don't hesitate to ask.
This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 3 years ago.
how to make a form submit without reloading the page i know that i have to use ajax but how can I do this?
html file:
<form name='myform' method="post" action="send.php">
<span class="close-btn" id="close">✖</span>
<p>Введите свои контактные данные</p>
<p>Мы Вам перезвоним</p>
<input type="text" name="name" placeholder="Имя" maxlength="30">
<p class="Error" id="Error">Это поле обязательное для заполнения</p>
<p class="ErrorTwo" id="ErrorTwo">Некорректный ввод</p>
<input type="tel" name="phone" placeholder="Телефон" maxlength="13">
<p class="Error" id="telError">Это поле обязательное для заполнения</p>
<p class="ErrorTwo" id="telErrorTwo">Некорректный ввод</p>
<input type="submit" value="Отправить заявку" name="save" id="save" disabled>
<p>Данные не передаються третьим лицам</p>
</form>
php:
<?php
$ToEmail = 'myemail#gmail.com';
$EmailSubject = 'форма обратной связи';
$mailheader = "From: ".$_POST["email"]."\r\n";
$MESSAGE_BODY = "Имя: ".$_POST["name"]."";
$MESSAGE_BODY .= "Телефон: ".$_POST["phone"]."";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
js:
/-----------------------------validation----------------------------------------/
//validation name
document.myform.name.onchange= function() {
var name = document.myform.name.value;
if (name === "") {
document.myform.name.removeAttribute("class", "ready");
document.myform.name.style.border = "1px solid #da3637";
document.getElementById("Error").style.display = "block";
document.getElementById("ErrorTwo").style.display = "none";
} else {
document.myform.name.style.border = "1px solid #509d12";
document.getElementById("Error").style.display = "none";
var pattern = new RegExp("^[a-z]+$", "i");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.myform.name.style.border = "1px solid #da3637";
document.getElementById("ErrorTwo").style.display = "block";
document.myform.name.removeAttribute("class", "ready");
} else {
document.getElementById("ErrorTwo").style.display = "none";
document.myform.name.style.border = "1px solid #509d12";
document.myform.name.setAttribute("class", "ready");
}
}
};
//validation phone
document.myform.phone.onchange = function() {
var name = document.myform.phone.value;
if (name === "") {
document.myform.phone.removeAttribute("class", "ready");
document.myform.phone.style.border = "1px solid #da3637";
document.getElementById("telError").style.display = "block";
document.getElementById("telErrorTwo").style.display = "none";
} else {
document.myform.phone.style.border = "1px solid #509d12";
document.getElementById("telError").style.display = "none";
var pattern = new RegExp("^\\d+$");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.myform.phone.style.border = "1px solid #da3637";
document.getElementById("telErrorTwo").style.display = "block";
} else {
document.getElementById("telErrorTwo").style.display = "none";
document.myform.phone.style.border = "1px solid #509d12";
document.myform.phone.setAttribute("class", "ready");
}
}
};
//filling the form
document.myform.onchange = function() {
var a = document.myform.name.getAttribute("class");
var c = document.myform.phone.getAttribute("class");
if (a === "ready" && c === "ready") {
document.getElementById("save").removeAttribute("disabled");
document.getElementById("save").style.cursor = "pointer";
document.getElementById("save").style.opacity = "1";
}
};
Use AJAX. I'd recommend enconding your form as JSON:
In HTML:
<form name='myForm' onsubmit='event.preventDefault(); sendForm("myForm");'>...</form>
In Js:
function sendForm(formName){
var http = new XMLHttpRequest();
http.open("POST","YourPage.php");
http.send(JSON.encodeForm(document.forms[formName]));
http.onreadystatechange = function(){
if(http.readyState == 4 && http.status == 200){
console.log(http.responseText); //PHP page's response handling
}
}
}
JSON.encodeForm = function(form){
var array = {};
for (key in form) {
var item=form[key];
if(form.hasOwnProperty(key) && item == "[object HTMLInputElement]"){
array[item.name]=item.value;
}
}
return JSON.stringify(array);
}
Then, in your PHP page:
$input = json_decode(file_get_contents("php://input") , true);
echo "Saved";
In my opinion better option is to validate data in the server-side file (some.php) and return response to client-side file.
php code will look like this:
$var = $_POST['some'];
if($var (bla bla bla))
{ echo 'ok.'; } else { echo 'Error'; }
response in your js file is echo message from your php file.
jsfiddle
EDIT (added input mask info):
if you need to validate your inputs in client-side file just use some input mask library (for example jquery input mask). This will be much easier way than creating own validation script.
I have a PHP program that takes in a image name and loads the image and displays the name and the image on the page.
The variable in javascrip is written as
var latest_image_name = '<?=$post_img_name?>';
The PHP code is
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
the html output, is being rendered as
<div id="image_list_wrapper">
<label class="lbl_image_name"><?=$file_name?></label>
</div>
And as you can see it seems that PHP has not replaced the tag with the posted image name.
The code works on the original server that it was developed on, it does not work when i migrated it to another server, i have tried two other servers both Centos 6.4 with apache and PHP installed. I am not sure what the setup was for the original server that it as does work on.
the full code is seen below
<?php
header('Refresh: 5; URL=display.php');
print_r($_POST['post_img_name']);
$target_directory = "uploaded_images";
if(!file_exists($target_directory)){
mkdir($target_directory);
}
if(isset($_POST['del_image'])) {
$del_image_name = $_POST['del_img_name'];
if(file_exists($target_directory."/".$del_image_name.".jpg")){
unlink($target_directory."/".$del_image_name.".jpg");
}
if(is_dir_empty($target_directory)){
die("Last image delete. No images exist now.");
}
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}else if(isset($_POST['post_img_name'])){
$post_img_name=$_POST['post_img_name'];
$post_img_temp_name = $_FILES['post_img_file']['tmp_name'];
}else{
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$files_assoc_array = array();
$already_exists = "false";
if($total_number_of_files != 0){
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if ($filename==$post_img_name) {
$already_exists = "true";
}
}
}
if(!isset($_POST['del_image']) && isset($_POST['post_img_name'])){
$target_file = "$target_directory"."/".$post_img_name.".jpg";
$source_file = $post_img_temp_name;
if($already_exists == "true"){
unlink($target_file);
}
move_uploaded_file($source_file, $target_file);
}
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if(!$file_info->isDot()){
$files_assoc_array[$filename] = $target_directory."/".$file_info->getFilename();
}
}
$files_assoc_array_keys = array_keys($files_assoc_array);
function get_latest_file_name($target_directory){
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$timestamps_array = array();
if($total_number_of_files!=0){
foreach($files_array as $file){
if(!$file->isDot()){
$timestamps_array[filemtime($target_directory."/".$file)] = $file->getFilename();
}
}
}
$max_timestamp = max(array_keys($timestamps_array));
return $timestamps_array[$max_timestamp];
}
function is_dir_empty($dir) {
if (!is_readable($dir))
return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
var files_array_text = '<?php echo implode(", ", $files_assoc_array)?>';
var files_array_keys_text = '<?php echo implode(", ", $files_assoc_array_keys)?>';
var files_array = files_array_text.split(", ");
var files_array_keys = files_array_keys_text.split(", ");
var files_assoc_array = createAssociativeArray(files_array_keys, files_array);
var latest_image_name = '<?=$post_img_name?>';
display_image(latest_image_name);
$('.lbl_image_name').click(function(){
$('#img_loading').show();
$('#img_display').hide();
var image_name = $(this).text();
$('.active').removeClass('active');
$(this).addClass('active');
display_image(image_name);
});
function createAssociativeArray(arr1, arr2) {
var arr = {};
for(var i = 0, ii = arr1.length; i<ii; i++) {
arr[arr1[i]] = arr2[i];
}
return arr;
}
function display_image(image_name){
var image_path = files_assoc_array[image_name];
$('#img_display').attr('src', image_path);
$('#img_display').load(image_path, function(){
$('#img_loading').hide();
$('#img_display').show();
})
}
});
</script>
</head>
<body>
<div id="container">
<div id="image_list_wrapper">
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
</div>
<div class="separator"></div>
<div id="image_display_wrapper">
<div id="img_loading_wrapper">
<img src="images/loading.gif" id="img_loading"/>
</div>
<img src="" id="img_display"/>
</div>
<div style="clear: both">
</div>
</div>
Go Back
</body>
</html>
As arbitter has pointed out my server did not support <?= ... ?> it worked after i changed to <?php print $variable_name ?>