image upload using javascript? - javascript

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);
}

Related

Div Cleared When Page Fully Loads

I am using a JavaScript & Ajax to make a php call to return data from my database. The call returns the data as it should, but when the page fully loads the <div> tags value is cleared.
What do I need to change in my syntax so that the div tag retains the value echo from the php file? I checked the Console and it is only showing page load info and nothing related to this issue (at least not that I saw).
<form id="form1" method="post">
<div id="results"> </div>
<div style="padding-top: 10px;"><input type="submit" value="Submit" onclick="MakeQuery()" /></div>
<script type="text/javascript">
var xhttp;
function MakeQuery()
{
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function(){ if (xhttp.readyState == 4 && xhttp.status==200)
{ document.getElementById("results").innerHTML = xhttp.responseText; } }
xhttp.open("GET", "SQLQuery.php", true);
xhttp.send();
}
</script>
</form>
I think you need to prevent the actual form submit before using AJAX:
var xhttp;
function MakeQuery(event) {
event.preventDefault(); // Cancel form submit, use AJAX
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("results").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "SQLQuery.php", true);
xhttp.send();
}

How to submit form without reloading page, without jQuery?

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

How can I print PHP POST data using AJAX? (no jQuery)

So basically I've got this HTML.
<form method="post" id="myform" onsubmit="getData()">
<fieldset>
<legend>Form</legend>
<label>Color: <input type='text' id="color" name='color'></label>
<label><input type="submit"></label>
</fieldset>
</form>
<div id="showoutput">
</div>
This PHP:
<?php
$color = $_POST['color'];
if($color != "")
{
$color = htmlentities($color, ENT_QUOTES);
print "<p>The color is $color</p>";
}
else
{
print "<p>Fill out form!</p>";
}
?>
And this JS:
window.onload = getData;
var req = new XMLHttpRequest();
function getData()
{
var poststr = "color=" + encodeURI( document.getElementById("color").value );
req.open("POST", "lab11-1.php", true);
req.onreadystatechange = useResponse;
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(poststr);
}
function useResponse()
{
if(req.readyState == 4)
{
if(req.status == 200)
{
document.getElementById('showoutput').innerHTML = req.responseText;
}
}
}
I'm trying to be able to input a color in the form, hit submit, and use AJAX to print the PHP to the "showoutput" div in my HTML. I've tried everything I can think of and haven't been able to figure it out.
I think this is not correct.
Ajax don't need form submit function,
I did do like this, I think you want it.
<form method="post" id="myform">
<fieldset>
<legend>Form</legend>
<label>Color: <input type='text' id="color" name='color'></label>
<label><input type="button" onclick="getData()" value="submit"></label>
</fieldset>
</form>
<div id="showoutput">
</div>
<script>
window.onload = getData;
var req = new XMLHttpRequest();
function getData()
{
var poststr = "color=" + encodeURI( document.getElementById("color").value );
req.open("POST", "test.php", true);
req.onreadystatechange = useResponse;
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(poststr);
}
function useResponse()
{
if(req.readyState == 4)
{
if(req.status == 200)
{
document.getElementById('showoutput').innerHTML = req.responseText;
}
}
}
</script>

Send a FILE with AJAX, plain Javascript: nothing is send. POST data is empty

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>

To display json on web browser

We want to display json of Google search results on browser called from servlet using Google API. The handleSearchResult is not displaying the responseText on browser.
Also the servlet is not mapping the querywords from the text box of html to Google API search url(servlet). Thanks
home.html
<html>
<head>
<script type="text/javascript">
var request;
function handleSearchResult(){
alert("hanldeRes");
//query.text = resp.items.name;
alert(request.responseText);
//var resp = eval('('+responseText+')');
//alert(resp.items.title);
}
function createHttpRequest()
{
alert("insideCreateRequest");
if(typeof XMLHttpRequest != "undefined") {
request = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
request = new ActiveXObject("Msxml2.XMLHTTP");
if(!request) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if(request) {
request.onreadystatechange = handleSearchResult();
request.open("GET","http://localhost:8080/WebSearchOptimization/SearchService",true);
request.send(null);
}
else {
alert("error on Page createHttpRequest");
}
return false;
}
function home_onclick()
{
alert("passingRequest");
createHttpRequest();
}
</script>
</head>
<body>
<br><br>
<form method="get" name="form">
<input type="text" id="query" name="query">
<input type="button" value="Search" id="search" onclick="home_onclick()">
<div></div>
</form>
</body>
</html>
I have made some modification on your code.Hope this will help.
function handleSearchResult(){
if (request.readyState==4 && request.status==200)
{
alert(request.responseText);
}
}
function createHttpRequest()
{
//....
if(request) {
request.onreadystatechange = handleSearchResult;
var q = encodeURI( document.getElementById("query").value );
request.open("GET","http://localhost:8080/WebSearchOptimization/SearchService?"+q,true);
request.send(null);
}
//.....
}

Categories