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.
Related
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.
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 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 am trying to send some parameters through xmlHttpRequest.send(params) written in a JS file to my servlet where I try to get the parameters by req.getParameter("some_Parameter"); it returns null on the servlet. though if i send the parameters by appending them in url it works fine. but when the url will be large it will break the code. so please someone help me out.
Thanks in advance.
function doHttpPost(theFormName, completeActivity)
{
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
var xmlMessage = buildPOST(theFormName, completeActivity);
var responseTxt;
try {
xmlhttp.Open(document.forms[theFormName].method, document.forms[theFormName].action+'?'+xmlMessage, false);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
responseTxt = xmlhttp.responseText;
}
}
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
enableDisableLinks(true);
setPointer();
xmlhttp.Send();
if(xmlhttp.Status != 200) {
alert("Post to server failed");
}
} catch (e) {
responseTxt = "Exception while posting form data: Error No: " + e.number + ", Message: " + e.description;
}
resetPointer();
enableDisableLinks(false);
var expectedTxt = "Form Data had been successfully posted to the database."
if(responseTxt.toString() == expectedTxt.toString()) {
// MNP: New requirement from Jeanne, should not refresh CM page, commenting it off for now
//if(completeActivity) {
// if (typeof (ViewCaseDetailBtn) != 'undefined') {
// ViewCaseDetailBtn.click();
// }
//}
return true;
} else {
alert (responseTxt);
}
return false;
}
BUGS
//IE only - shooting yourself in the
// Not all IE versions use ActiveX!
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); foot.
//JavaScript case sensitive, open !== Open
xmlhttp.Open(document.fo...
//JavaScript case sensitive, send !== Send
xmlhttp.Send();
//JavaScript case sensitive, status !== Status
xmlhttp.Status
AND if you are using synchronous, it does not call the onreadystatechange.
If you are using POST, the value needs to be in send("valuestosendup") not on the querystring.
This code shows why you should really use a framework to make Ajax calls and to not roll your own.
I'm new to javascript/ajax and a bit stuck right now.
The assignment is to use only javascript/ajax.
I'm supposed to make a login-form, and when typing in the right password it will display a "secret message". Currently this message is an alert-box.
This is in the script for validating the form input:
var riktigPassord = 'password';
var passord = window.document.passordSkjema.passord.value;
if (passord == riktigPassord ) {
alert("Dette er en hemmelig beskjed");
window.document.passordSkjema.passord.focus();
return true;
}
else {
alert("Innlogging mislyktes. Passord er feil!");
window.document.passordSkjema.passord.focus();
return false;
}
}//slutt på funksjonen her
And this is the code for the form:
<form name="passordSkjema" action="#" method="post"
onSubmit="return validerPassord();">
Passord: <input type="text" name="passord"><br>
<input type="submit" name="knapp">
</form>
I'm supposed to get the password from a txt-file. (still using only javascript)
and in my case, the txt-filename is "password.txt".
I've never done this before, but I think I know how to make a XHR-object... xD
// New XMLHttpRequest-object
function newXHRobjekt() {
try {
XHRobjekt = new XMLHttpRequest(); // Firefox, Opera, ...
} catch(err1) {
try {
XHRobjekt = new ActiveXObject("Microsoft.XMLHTTP"); // Noen IE
} catch(err2) {
try {
XHRobjekt = new ActiveXObject("Msxml2.XMLHTTP"); // Noen IE
} catch(err3) {
XHRobjekt = false;
}
}
}
return XHRobjekt;
}
So.. My question is. How do I use a XHR-object to get use the functions above to check the password-input against password.txt. the file only contains the password (for instance only "12345"). and also I would like to know how to get the "secret message" from another txt-file.
I'm aware that this isn't secure at all, but it's a part of understanding javascript/Ajax, in my classes.
Thanks!
add the following code to the onload event of the body.
var passwordLoaded = false;
var password = "";
var secretMessageLoaded = false;
var secretMessage = "";
var xhr = newXHRobjekt();
xhr.open("GET", "password.txt");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
password = xhr.responseText;
passwordLoaded = true;
}
}
xhr.send(null);
xhr = newXHRobjekt();
xhr.open("GET", "secret_message.txt");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
secretMessage = xhr.responseText;
secretMessageLoaded = true;
}
}
xhr.send(null);
If both passwordLoaded and secretMessageLoaded are set to true you can use the variables password and secretMessage.
Like many of the Javascript APIs XHR object too have an async interface. So you will need to define callback functions to handle the responses:
xmlhttp.open("POST", "http://example.com",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText)
}
}
xmlhttp.send('my request data');
Search for example on the net. I found a post, a bit old but seem to have good examples.