I am making a messaging system and I have recently implemented a file uploader, and my javascript functions aren't working, if I press the input file button then press cancel, the next time I upload a file it does it 3 times. It's as if since I don't upload anything, they just sit there and then the function stack. Here is my input :
<input type="file" id="file" onclick="bro()"name="file" value="FILE UPLOAD" style="opacity: 0;z-index: 100000; bottom: 17.5px; position: fixed; right: 10px;">
And here is my javascript function
function bro() {
document.querySelector('#file').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("file", file);
var xhr = new XMLHttpRequest();
var group_id = document.getElementById('group_id').value;
var fullurl = '../backend/sendvideosandimages.php?id=' + group_id;
xhr.open('POST', fullurl, true);
xhr.onload = function() {
if (this.status == 200) {
};
};
xhr.send(fd);
}, true);
};
The problem is, I can't just put the function because I use an ajax request thing to display the input. To explain more since I am making a messaging system I have a sidebar with group id and group name. I use this function :
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxLoad(page, id, id2){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('mainpage');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = "?id=" + id + "&id2=" + id2;
//alert(page + queryString);
ajaxRequest.open("GET", page + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
The problem is that if I put the event change listener by itself, then it bugs because when the home page loads, the mainpage does not have a input yet. And if I put a script in the mainpage it doesn't execute
It is stacking because of multiple eventListeners . there only should be 1 eventListeners .
Firstly, take document.querySelector('#file').addEventListener out of bro() function.
Whenever you calling function. It is adding new change listeners without removing before one.
thus seems like bro function has no use;
This will work :
document.querySelector('#file').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("file", file);
var xhr = new XMLHttpRequest();
var group_id = document.getElementById('group_id').value;
var fullurl = '../backend/sendvideosandimages.php?id=' + group_id;
xhr.open('POST', fullurl, true);
xhr.onload = function() {
if (this.status == 200) {
};
};
xhr.send(fd);
}, true);
//OR
function bro() {
document.querySelector('#file').removeEventListener('change',(e)=>{console.log('removed listener')})
document.querySelector('#file').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("file", file);
var xhr = new XMLHttpRequest();
var group_id = document.getElementById('group_id').value;
var fullurl = '../backend/sendvideosandimages.php?id=' + group_id;
xhr.open('POST', fullurl, true);
xhr.onload = function() {
if (this.status == 200) {
};
};
xhr.send(fd);
}, true);
}
Remove the change event handler and then try.
You need to remove this:
document.querySelector('#file').addEventListener('change'
Right now you have two events on file upload.
Change event.
Click event.
When you click it adds a change event hence multiple uploads.
Here either you can remove change event code or remove the event listener every time you click.
Try these fixes and see if it works.
Related
I've been struggling for hours with following code without success. In my html I have several inputs (type=text, type=date and selects), and a button calling a js function: onclick=SendNewData().
The JS function is something like the following:
function SendNewData() {
var MyData1=document.getElementById("id1").value;
var MyData2=document.getElementById("id2").value;
var MyData3=document.getElementById("id3").value;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST', 'Handler.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("FormNuevaCom").innerHTML = xmlhttp.responseText;
}
}
var data = new FormData;
data.append('DATA1', MyData1);
data.append('DATA2', MyData2);
data.append('DATA3', MyData3);
xhr.send(data);
}
and the Handler.php is something like the following:
if(isset($_POST['DATA1'])) {
$MyVar=$_POST['DATA1'];
echo "Hi there! ".$MyVar." received...";
}
I canĀ“t get any response. Anyone can spot the problem?
I have a javascript which call a server and get a JSON data which contains some config to enable/disable redirecting to another link. I need to delay the redirection by a few seconds, but it seems that setTimeout() is not getting called in my method. Even if I change redirect() as an anonymous function and pass it in setTimeout it is still not getting called.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
xhr.onreadystatechange = function() {
function redirect(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
document.write("<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>");
document.write("<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>");
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);
// set global object for using it inside the settimeout function
var redirect;
and then inside the xhr.onreadystatechange = function() {
redirect = function(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
setTimeout('redirect()',3000);
Thanks for all the suggestions. I have improved it as per suggestion by talsibony, and I further found out also that document.write() removes all my content, which makes it unable to find the redirect global variable. So I have instead changed it to add a div element and set the innerHTML. Here is the fixed code in case if someone encountered similar issue.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
var redirect;
xhr.onreadystatechange = function() {
redirect = function(){
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
var div = document.createElement("div");
document.body.insertBefore(div, document.body.firstChild);
div.innerHTML += "<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>";
div.innerHTML += "<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>";
div.innerHTML += "<h1><font color='red'>Remember to save the new URL to your favorites</font></h1>";
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);
I want to upload a file trough a XMLHttpRequest. i have looked everywhere for examples and found quite a few. But i cant figer out what it is i am doing wrong. This is my code. The function is triggerd when a button is pressed. It not wrapped in from tags
function upl_kost() {
var url = "proces_data.php?ref=upload_kost";
var hr;
var file = document.getElementById("file_kost");
var formData = new FormData();
formData.append("upload", file.files[0]);
if (window.XMLHttpRequest) {
hr=new XMLHttpRequest();
} else {
hr=new ActiveXObject("Microsoft.XMLHTTP");
}
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "multipart/form-data");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
alert(return_data);
}
}
hr.send(formData);
}
and this function catches it.
if($_GET['ref'] == 'upload_kost') {
var_dump($_FILES);
}
My problem is that the $_FILES stays empty. When i look at the file.files variable in the js its loaded with the data from the file that i am trying to upload.
Thanks!
Reduce your JavaScript down to minimum required for this, then add in some helpful messages you can look in your console for
function upl_kost() {
var xhr = new XMLHttpRequest(),
url = 'proces_data.php?ref=upload_kost',
fd = new FormData(),
elm = document.getElementById('file_kost');
// debug <input>
if (!elm)
console.warn('Element not found');
else if (!(elm instanceof HTMLInputElement))
console.warn('Element not an <input>');
else if (!elm.files || elm.files.length === 0)
console.warn('<input> has no files');
else
console.info('<input> looks okay');
// end debug <input>
fd.append('upload', elm.files[0]);
xhr.addEventListener('load', function () {
console.log('Response:', this.responseText);
});
xhr.open('POST', url);
xhr.send(fd);
}
If you're still having a problem, it may be server-side, e.g. are you performing a redirect before trying to access $_FILES?
Your problem is that you're setting the content type of the request
hr.setRequestHeader("Content-type", "multipart/form-data");
If you ever saw a multipart/formdata post you'll notice the content type header has a boundary
Content-Type: multipart/form-data; boundary=----webko2354645675756
which is missing from your code.
If you do not set the content type header the browser will correctly set it and the required boundary. This will allow the server to properly parse the request body.
I've the following js code to upload image to imgur using Auth.
<script type="text/javascript">
window.ondragover = function(e) {e.preventDefault()}
window.ondrop = function(e) {e.preventDefault(); upload(e.dataTransfer.files[0]); }
function upload(file) {
if (!file || !file.type.match(/image.*/)) return;
document.body.className = "uploading";
var fd = new FormData();
fd.append("image", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.imgur.com/3/image.json");
xhr.onload = function() {
var code = '[img]' + JSON.parse(xhr.responseText).data.link + '[/img]';
var editor = eval('opener.' + 'clickableEditor');
editor.performInsert(code);
javascript:window.close()
}
xhr.setRequestHeader('Authorization', '39-letter-client-secret-code');
xhr.send(fd);
}
</script>
It doesn't uploads image to the imgur, but it returns data "undefined". Can you please mention me if I'm missing something here?
I've seen an issue in this line;
xhr.setRequestHeader('Authorization', '39-letter-client-secret-code');
I've changed it to;
xhr.setRequestHeader('Authorization', 'Client-ID 15-letter-Client-ID');
and it works. Sorry to bother you.
I want to replicate some functionality from Digg.com whereby when you post a new address it automatically scans the url and finds the page title.
I am programming in classic ASP and VBScript and using javascript. Anyone know a script to make this happen..?
Many thanks in advance..
Paul
This is somewhat of a rudimentary example. You should probably include some data verification.
The ASP page should be called something like getPageTitle.asp
<%
Response.Buffer = True
Dim strURL, objXMLHTTP, objXML, strContents
Dim objRegExp, strHTML, strPattern, colMatches, strTitle
strURL = Request.Form("url")
Set objXMLHTTP = Server.CreateObject ("Microsoft.XMLHTTP")
'Or if this doesn't work then try :
'Set objXMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXMLHTTP.Open "GET", strURL, False
objXMLHTTP.Send
strContents = objXMLHTTP.ResponseText
Set objXMLHTTP = Nothing
Set objRegExp = New RegExp
strPattern = "<title>(.*?)<\/title>"
objRegExp.Pattern = strPattern
objRegExp.IgnoreCase = True
objRegExp.Global = True
Set colMatches = objRegExp.Execute(strContents)
If colMatches.Count > 0 then
strTitle = objMatches(0).Value
Else
strTitle = ""
End If
Set objRegExp = Nothing
Response.write(strTitle)
%>
This is a basic JavaScript POST implementation. You could spruce this up a bit with any JS framework you like.
var script = "http://www.example.com/getPageTitle.asp"
var page2check = "http://www.example.com/somePageToCheck.html"
function getXMLHttpRequestObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = new getXMLHttpRequestObject();
var parameters = "url="+page2check;
http.open("POST", script, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters .length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4) {
alert(http.responseText);
}
}
http.send(parameters);
var pageTitle = http.ResponseText
I hope this helps.
Send url from clientside to serverside using javascript(ajax).
Load html page by it's url using asp on serverside.
Parse html page, extract title.
Send title to clientside.