I'd like to upload image(s) via JavaScript (Non framework). Does anyone have a basic example of how to this?
I get this error message:
Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0 Array ( )
Here is what I'm working with so far.
<form action="" method="" enctype="" id="uploadImage">
<input type="file" name="image1" id="image1" value="" >
<input type="button" id="submit_button" data-data_enctype="multipart/form-data" data-form_name="uploadImage" data-url="/gallery/images/upload/" data-change_div="getForm" value="Upload" onclick="image(this.id, form.id)"/>
</form>
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var datVar = document.getElementById(id);
var url = datVar.dataset.url;
var change_div = datVar.dataset.change_div;
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById(change_div).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.send('NULL');
You need to pass the data that you want to send to the xmlhttp.send() method. Currently you are passing it 'NULL' so it complains that the data is missing.
Something like
var data = document.getElementById('#uploadImage');
gets the form.
create a FormData object (FormData is only supported in modern browsers)
var formData = new FormData(data);
and then passing formData to the send method should do.
Related
This is the form:
<form id="login_form">
Login<br/>
user: <input id="login_user" name="login_user" type="text" /><br/>
pass: <input id="login_pass" name="login_pass" type="password" /><br/>
<input type="button" value="Submit" onclick="doStuff("login")" />
</form>
this is the js I used:
function doStuff(doWhat){
var sendString = new FormData(document.getElementById("login_form"));
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "?action="+doWhat, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
//do stuff
}
};
xmlhttp.send(sendString);
}
The PHP page only has echo var_dump($_POST);
If I send it like that it returns this, that I have no idea how to use:
D:\wamp64\www\test\index.php:18:
array (size=1)
'------WebKitFormBoundaryubX9lqZJrSEuJwB9
Content-Disposition:_form-data;_name' => string '"login_user"
admin
------WebKitFormBoundaryubX9lqZJrSEuJwB9
Content-Disposition: form-data; name="login_pass"
swordfish
------WebKitFormBoundaryubX9lqZJrSEuJwB9--
' (length=173)
If I try anything else, like using JSON.stringify() on the FormData before sending it or changing the content type from application/x-www-form-urlencoded to multipart/form-data it just returns an empty array. I should not use jQuery for this. Is there a way to send something usable or make the PHP page able to read it?
This is my HTML and javascript.
I'm trying to upload an image using javascript.
I did find some examples using jquery, but was hoping if this function below can be modified to do the same.
The image upload script is a PHP script, which works when the form is posted normally, but when using this function below, it doesn't send the image to the PHP script. $_FILES is empty.
How can I modify this function to send the image as well?
<html><head>
<script type="text/javascript">
function jax( ){
pd = document.getElementById("pd").innerHTML;
i = document.getElementById("i").value;
url= "ajax.php"; //?act=uploadPic&title=" + pd + "&i=" + i;
q="act=uploadPic&title=" + pd + "&i=" + i;
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support ajax. Allow Active scriptting in internet settings."); return false;
}
}
}
ajaxRequest.onreadystatechange= function(){
if(ajaxRequest.readyState == 4){
r =ajaxRequest.responseText;
alert(r);
}
}
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(q);
}//func
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p> Title: <input type="text" name="pd" id="pd" value=" Title here " />
<p> Image: <input type="file" name="i" id="i" />
<p> <button onclick=" jax( ) "> Upload </button>
</form>
</body>
</html>
The PHP script to verify if image is send:
ajax.php
<?php print_r($_FILES); ?>
this is my function,but can't working lower than ie8:
function jax(){
url= "ajax.php?act=uploadPic";
var formData = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
xhr.open('post',url,true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
xhr.addEventListener('progress',function(e){
if (e.lengthComputable) {
console.log(e.loaded+'/'+e.total);
}
},false);
xhr.send(formData);
}
I have form as follows, it require to sent an action to my java Servlet to do an update to the database.
How do I submit the form without the page get reloaded here?
Currently with action="myServlet" it keep direct me to a new page. And if I remove the action to myServlet, the input is not added to my database.
<form name="detailsForm" method="post" action="myServlet"
onsubmit="return submitFormAjax()">
name: <input type="text" name="name" id="name"/> <br/>
<input type="submit" name="add" value="Add" />
</form>
In the view of my Java servlet, request.getParameter will look for the name and proceed to add it into my db.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if (request.getParameter("add") != null) {
try {
Table.insert(name);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
In my JavaScript part, I have a submitFormAjax function
function submitFormAjax()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
alert(xmlhttp.responseText); // Here is the response
}
var id = document.getElementById("name").innerHTML;
xmlhttp.open("POST","/myServlet",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name=" + name);
}
A similar question was asked here
Submit form without reloading page
Basically, do "return false" after invoking the function. Something like this should work:
<form name="detailsForm"
method="post"
action="myServlet"
onsubmit="submitFormAjax();
return false;"
>
This is how I used to implement Ajax in JS without JQuery. As am a PHP and JS guy I cant possibly help you with Java Servlet side but yes heres my little help from JS side. This given example is a working example.See if it helps you.
// HTML side
<form name="detailsForm" method="post" onsubmit="OnSubmit(e)">
// THE JS
function _(x){
return document.getElementById(x);
}
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/json");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function OnSubmit(e) // call this function on submit
{
e.preventDefault();
var username = _("name").value;
if (username == "")
{
alert("Fill out the form first");
}
else
{
var all = {"username":username};
all = JSON.stringify(all);
var url = "Myservlet";
var ajax = ajaxObj("POST", url);
ajax.onreadystatechange = function()
{
if(ajaxReturn(ajax) == true)
{
// The output text sent from your Java side in response
alert( ajax.responseText );
}
}
//ajax.send("user="+username+");
ajax.send(all);
}
}
Thanks
Change the code in form
onsubmit="submitFormAjax(event)"
Change your JS code
function submitFormAjax(e)
{
e.preventDefault();
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
}
......
................
...............
return false; //at last line
I have now got everything to post correctly but this script keeps loading it into a new page. Is it something to do with the way my php file returns it? "echo(json_encode($return_receipt));"
<script>
// Get XML HTTP Type
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxSuccess () {
alert(this.responseText);
}
function ajaxrequest(oFormElement,tagID) {
//Get The Correct XMLHTTP Object
var request = new XMLHttpRequest();
request.onload = ajaxSuccess;
request.open(oFormElement.method, oFormElement.action, true);
//request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(new FormData(oFormElement));
}
</script>
you have two easy options..
1.you can use jquery ajax method... or
2. javascript form submission without loading the page by targetting the form to the hidden inline frame
here i'm using it for image upload image name without hitting submit button and save the data to the database table without reloading the page.. edit it according to your convenience.
function upload(img)//Javascript function
{
var types = /\.jpg|\.gif|\.jpeg/i;
var filename = img.value;
if (filename.search(types) == -1) {
alert("Select only images ( jpg or gif or jpeg format)");
img.form.reset();
return false;
}
img.form.action = 'upload-picture.php';
img.form.target = 'iframe';
img.form.submit();
return true;
}
// here is iframe on the same page
<iframe name="iframe" id="u_iframe" style="display:none;"></iframe>
<input type="file" name="picture" id="picture" onchange="return upload(this);" />
This is my HTML code:
<input type="file" id="file" name="file" />
<input type="button" value="Send the file" onclick="inviaFileAJAX()" />
This is my AJAX function:
function inviaFileAJAX()
{
if(!document.getElementById("file").value)
{
alert("No file selected");
return false;
}
var file = document.getElementById("file");
var formData = new FormData();
formData.append("file", file.files[0]);
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && `xmlhttp.status == 200)`
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "invia_file.php", true);
xmlhttp.setRequestHeader("Content-Type", "multipart/form-data");
xmlhttp.send(formData);
}
If in php i write
var_dump($_POST);
In the alert in the AJAX function:
alert(xmlhttp.responseText);
I get undefined reference because the old:
$_FILES["file"]["name"]
isn't found. The POST array is empty. Where is the problem?
The most common method is a 'fake ajax' method that consists in create a lying iframe in the page and direct the form target to it.
ex:
<form enctype="multipart/form-data" action="upload.php" target="myInvisibleFrame" method="post">
<input type="file" name="myfile"/>
<button type="submit">Upload</button>
</form>
<iframe id="myInvisibleFrame" style="display: none;" onload="alert('complete!');"></iframe>