send image file to a php file via ajax - javascript

I am new to this.All i am trying to do is upload a image and send it to server to insert in a database.As a start i am limited to echoing the file name which i will send.But i kept on failing to do so.Getting some noisy or undesirable output which makes no sence.Can't figure out the mistakes in this code.It would be great if someone help me with this problem.Thanks!
html and ajax:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>file upload</title>
<!-- Make sure the path to CKEditor is correct. -->
<style>
#mydiv{
position: relative;
overflow: hidden;
width:80px;
height:30px;
background:crimson;
color:white;
text-align:center;
padding:auto;
border-radius:4px ;
border:1px solid black;
font-size:22px;
}
#files{
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
</style>
</head>
<body>
<form action='file.php' id='myform' method='POST' enctype='multipart/form-data' style='width:80px;height:70px;border:2px solid skyblue;'>
<div id='mydiv'>upload
<input type="file" id="files" name="files" multiple />
</div>
<span id='txtHint'></span>
</form>
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files;
var formData = new FormData();
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
formData.append('image_name',f,f.name);
var name =f.name;
console.log(name);
if (name='') {
document.getElementById("txtHint").innerHTML ='fill the name field';
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "file2.php", true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(formData);
}
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
php file:
echo $_FILES['image_name'];

To retrieve the upload file name just do:
echo $_FILES['image_name']['name']
EDIT : According to the name of your html input
echo $_FILES['files']['name']

What about to use BlueImp ? BlueImp is the best i think, and you can easily include on your projects
https://github.com/blueimp/jQuery-File-Upload

Related

calling a html function inside script in external js file

I have written a javascript function inside script tag of html file...
<!DOCTYPE html>
<html>
<head>
<title> Sample Application </title>
</head>
<body>
<h1 style="text-align: left">Test</h1>
<div id="conversation" style="width: 600px; height: 400px; border: 1px solid #ccc; background-color: #eee; padding: 4px; overflow: scroll"></div>
<form id="chatform" style="margin-top: 10px" onsubmit="return pushChat();">
<input type="text" id="wisdom" size="80" value="" placeholder="Type your issue">
</form>
<script type="text/javascript">
// set the focus to the input box
document.getElementById("wisdom").focus();
function pushChat() {
// if there is text to be sent...
var wisdomText = document.getElementById('wisdom');
if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) {
// disable input to show we're sending it
var wisdom = wisdomText.value.trim();
wisdomText.value = '';
wisdomText.locked = false;
showRequest(wisdom);
// send it to the Lex runtime
botaction(wisdom);
}
// we always cancel form submission
return false;
}
function botaction(action){
console.log("action: " + JSON.stringify(action));
switch (action.intentName) {
case "details":
var Id = action.userid;
var arguments = [Id];
verify(arguments);
break;
default:
console.log('No action found.');
console.log('executing the default action based on response');
break;
}
}
function verify(arguments){
}
</script>
</body>
</html>
i need to move the function verify(arguments) to an external js file.i have to move that because i am calling a nodejs child process which requires a module to be included.
How can i move the function to a external js file and subsequently call verify function from html file.
Make three files as such. It will solve your issue.
index.html
<!DOCTYPE html>
<html>
<head>
<title> Sample Application </title>
<!-- insert these two lines -->
<script type="text/javascript" src="verify.js" ></script>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
<h1 style="text-align: left">Test</h1>
<div id="conversation" style="width: 600px; height: 400px; border: 1px solid #ccc; background-color: #eee; padding: 4px; overflow: scroll">
</div>
<form id="chatform" style="margin-top: 10px" onsubmit="return pushChat();">
<input type="text" id="wisdom" size="80" value="" placeholder="Type your issue">
</form>
</body>
</html>
verify.js
function verify() {
}
other.js
document.getElementById("wisdom").focus();
function pushChat() {
// if there is text to be sent...
var wisdomText = document.getElementById('wisdom');
if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) {
// disable input to show we're sending it
var wisdom = wisdomText.value.trim();
wisdomText.value = '';
wisdomText.locked = false;
showRequest(wisdom);
// send it to the Lex runtime
botaction(wisdom);
}
// we always cancel form submission
return false;
}
function botaction(action){
console.log("action: " + JSON.stringify(action));
switch (action.intentName) {
case "details":
var Id = action.userid;
var arguments = [Id];
verify(arguments);
break;
default:
console.log('No action found.');
console.log('executing the default action based on response');
break;
}
}
You can just copy paste the function to a .js file (ex:verifys.js) and include the .js file in the HTML using

Ajax form validation with php WITHOUT jQuery

I am learning JavaScript without jQuery.
Right now I am trying to pass some data from an input field to php and than pass a $variable from php to javascript. In jQuery this is easy with $.ajax.
But how do I do this with ONLY JavaScript? Here is my attempt. Right now I only want to pass the $_POST content from the inputfield. I didn't do any validation at this moment.
My plan is to make a validation with php and then pass an error message or more than one. Or in case of success an success message.
But out of my console log I am only getting NULL.
window.onload = function () {
var Input = document.querySelector('input#Input');
var InputButton = document.querySelector('button.formBtn');
InputButton.onclick = function () {
var InputRequest = new XMLHttpRequest();
InputRequest.open("POST", "ajax.php", true);
InputRequest.send();
InputRequest.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(InputRequest.response)
console.log(obj);
}
}
return false;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax Example</title>
<style>
#Input {
width: 200px;
height: 15px;
padding: 10px 0;
text-indent: 5px;
}
#Input:focus {
outline: none;
border: 1px solid lightblue;
}
</style>
</head>
<body>
<form name="form" action="ajax.php" method="post">
<input type="text" id="Input" name="inputTest">
<button type="submit" class="formBtn">Absenden</button>
</form>
<script src="ajax.js"></script>
</body>
</html>
<?php
$inputResponse = $_POST["inputTest"];
echo json_encode($inputResponse)
?>
You are missing a line and need to modify your send() line for sending POST content:
// You need to send the type
InputRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send the post values in the send
InputRequest.send('key=value&key2=value2');
In the case of the send() you have to turn the keys and values to a query string. I think this is why so many use jQuery, it's done all this for you.

How to send an image with a POST using AJAX? [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 6 years ago.
I can send a POST using curl:
curl -X POST -F 'secret=supersecretkey' --form file=#galleta.jpg http://127.0.0.1:5000/
But I donĀ“t know how to do the same using AJAX and jQuery.
Step 1: HTML AND Styling
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>HTML5 File API</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="main">
<h1>Upload Your Images</h1>
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name="images" id="images" multiple />
<button type="submit" id="btn">Upload Files!</button>
</form>
<div id="response"></div>
<ul id="image-list">
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="upload.js"></script>
</body>
</html>
The CSS File
body {
font: 14px/1.5 helvetica-neue, helvetica, arial, san-serif;
padding:10px;
}
h1 {
margin-top:0;
}
#main {
width: 300px;
margin:auto;
background: #ececec;
padding: 20px;
border: 1px solid #ccc;
}
#image-list {
list-style:none;
margin:0;
padding:0;
}
#image-list li {
background: #fff;
border: 1px solid #ccc;
text-align:center;
padding:20px;
margin-bottom:19px;
}
#image-list li img {
width: 258px;
vertical-align: middle;
border:1px solid #474747;
}
Step 2 : The PHP - upload.php
<?php
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
}
}
echo "<h2>Successfully Uploaded Images</h2>";
Step 3 : Javascript
(function () {
var input = document.getElementById("images"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
document.getElementById("btn").style.display = "none";
}
}();
function showUploadedItem (source) {
var list = document.getElementById("image-list"),
li = document.createElement("li"),
img = document.createElement("img");
img.src = source;
li.appendChild(img);
list.appendChild(li);
}
if (input.addEventListener) {
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
document.getElementById("response").innerHTML = "Uploading . . ."
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
}
}
}, false);
}
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("images[]", file);
}
if (formdata) {
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
}
Follow this tutorial explaining how to achieve this.

I'm getting corrupted image when converting base64 image using webcam.js

here's my html with javascript using webcam.js. I just followed the https://github.com/jhuckaby/webcamjs on how you will implement it using existing form.
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="../webcam.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
Webcam.snap( function(data_uri) {
var raw_image_data = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
document.getElementById('mydata').value = raw_image_data;
document.getElementById('myform').submit();
} );
</script>
<!-- A button for taking snaps -->
<form id="myform" method="post" action="myscript.php">
<input id="mydata" type="hidden" name="mydata" value=""/>
<input type=button value="Take Snapshot" onClick="take_snapshot()">
<input type="submit" value="submit">
</form>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="'+data_uri+'"/>';
} );
}
</script>
here's the myscript.php to save the image. I successfully save the PATH in the database but I'm getting a corrupted .jpg file (file size always in 7 bytes).
<?php
include 'connect.php';
$encoded_data = $_POST['mydata']; // to get the base 64 code image link
$name = base64_decode($encoded_data); // to convert base 64 code
$name = date('YmdHis');
$newname="images/".$name.".jpg";
$file = file_put_contents( $newname, file_get_contents('php://input') );
if (!$file) {
print "Error occured here";
exit();
}
else
{
$sql="INSERT INTO image (images) VALUES('$newname')";
$result=mysqli_query($con,$sql);
$value=mysqli_insert_id($con);
$_SESSION["myvalue"]=$value;
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $newname;
print "$url\n";
?>
After all the trail and errors i found out you'll need to convert the base64 string to a blob and then attach to a file before sending.
var binaryImg = atob(base64string);
var length = binaryImg.length;
var ab = new ArrayBuffer(length);
var ua = new Uint8Array(ab);
for (var i = 0; i < length; i++) {
ua[i] = binaryImg.charCodeAt(i);
}
var blob = new Blob([ab], {
type: "image/jpeg"
});enter code here
var imgFile = new File([blob], 'photo.jpeg', {type: 'image/jpeg'});
Now you can use the imgFile to send across to a remote server.

Upload all images

I have a upload button on my webpage. Whenever I upload an image it will show a preview of the image(s) that were uploaded. If more than one image is uploaded, the previews of the second image will be shown next to the first and so on.
I need to be able to upload all the shown images into my uploads folder using PHP. How can I do this?
This is my HTML code that will upload the images one by one and show preview:
<html>
<head>
<meta charset=utf-8 />
<title>Image preview</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
var blank = "http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif";
</script>
<style>
img {
height:200px ! important;
width:200px ! important;
}
</style>
<script type="text/javascript">
//<![CDATA[
$(window).load(function() {
$('input[type="file"]').change(function() {
if ($(this).val() !== "") {
var file = $('#file_select')[0].files[0];
console.log(file.size);
//console.log(file.width);
var reader = new FileReader();
var img = new Image();
var _URL = window.URL || window.webkitURL;
reader.readAsDataURL(file);
reader.onload = function(_file) {
// Create a container for image and span X
$imageItem = $('<div style=" float: left; border:5px solid gray; ">').addClass('imageItem');
$(img).appendTo($imageItem);
$('<span>').html('<a href="#" style=" z-index: 1; margin-left: -32px;"><img src="trash.png" title="remove" style=" width: 32px ! important;height: 32px ! important;">
</a>').addClass('remover').appendTo($imageItem);
img.src = _file.target.result;
// Append the container to panel
$('#previewPane').append($imageItem);
//console.log(img.src);
console.log(img.width);
}
}
// Deletegate for dynamically created span, so we don't have to register a
// new event listener each time a new imageContainer is created.
$('#previewPane').on('click', '.remover', function() {
$this = $(this);
$this.parent('.imageItem').remove();
});
});
}); //]]>
</script>
</head>
<body>
<section>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type='file' name="file[]" id="file_select" multiple="multiple" />
<br/> <span id="previewPane"></span>
<input type="submit" value="OK">
</form>
</section>
</body>
</html>
This is my PHP code but currently it is uploading only one image.
<?php
for($i=0; $i<count($_FILES['file']['name']); $i++) {
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "uploads/" . $_FILES['file']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
}
}
}
?>

Categories