I have scanned the web for largest substring implementations to use in my xmlhttp request, however I found that only 1 has worked, in other cases the responsetext hasn't been treated as a string no matter what I have written:
txt = txt + ""; // or
txt = new string(txt);)
This function works, but it is terrible slow. I am just wondering if you code gurus out there could help me improve this algorithm.
The site that I'm calling a xmlhttprequest is looking like this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /</title>
</head>
<body>
<h1>Index of /</h1>
<ul><li> Parent Directory</li>
<li> random/</li>
<li> random_1/</li>
<li> random/</li>
<li> random_1/</li>
<li> random/</li>
<li> random_1/</li>
</ul>
</body></html>
In other words you can strip of all the html tags for better speed, I will just search for the plain text in the html text document.
You can watch the script in action here at tdsoft.se
<html>
<head>
<script type="text/javascript">
var txt;
var buildName = "";
var xmlhttp;
function lcs(a, b) {
var aSub = a.substr(0, a.length-1);
var bSub = b.substr(0, b.length-1);
if (a.length == 0 || b.length == 0) {
return "";
} else if (a.charAt(a.length-1) == b.charAt(b.length-1)) {
return lcs(aSub, bSub) + a.charAt(a.length-1);
} else {
var x = lcs(a, bSub);
var y = lcs(aSub, b);
return (x.length > y.length) ? x : y;
}
}
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("http://tdsoft.se/testni.html",handleXML);
}
var checkState = function(xmlhttp, callback) {
try{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback();
}
else {
// Check back again 1 sec later
setTimeout(checkState, 1000);
}
}
catch(err){
setTimeout(checkState, 1000);
}
};
function handleXML()
{
checkState(xmlhttp, function() {
txt=xmlhttp.responseText;
buildName = "random";
txt = txt.replace(/<[^>]*>/g, "");
var myvar = "";
myvar = lcs(txt, "random");
document.write(myvar);
});
}
</script>
</head>
<body onLoad="myFunction()">
</body>
</html>
Seems like you would want to take a different approach at this.
I'm not exactly sure the point of what you are trying to do but it seems like something like this would be what you want:
You request a Document
Parse the links in the document and store them in an object keyed by their ids with values being their text
Change your lookup function to go after the link list
Here's a code example (using jQuery for simplicity):
//untested!
var links = {};
function successFunction(data) {
var aTags = data.find('a');
aTags.each(function() {
var $this = $(this);
links[$this.attr('href')] = $this.text();
});
}
function lookup(id) {
return links[id] || '';
}
$.ajax({
url: 'requestPage.htm',
success: successFunction
});
EDIT:
If you want to do this non-jquery you can just replace the following things:
$.ajax to your XMLHttpRequest method
data.find('a') to getElementsByTagName
.each(function(){...}) to var i = aTags.length; while(i--) { links[aTags[i].href] = aTags[i].innerHTML; }
Related
I have another question: Is there any way to change input autocomplete value dynamically with javascript?
Example:
<input id="myInput"
placeholder="Write something here..."
onchange="changeAutocompleteValue(event)">
<script>
function changeAutocompleteValue(event)
{
var list = ["first", "second", "third"];
event.list = list;
}
</script>
Google example:
Am I able to do it with plain JS? Any suggestion will be great :).
I found
javascript : Auto complete javascript text field
if use existing library then
typeahead.js
typeahead.js / example
function loadXMLDoc(_target, _type,_func) {
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 ) {
if(xmlhttp.status == 200){
data = JSON.parse(xmlhttp.responseText);
_func(data);
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open(_type, _target, true);
xmlhttp.send();
}
function ontxtChange(){
var dcc = document.getElementById('autocc');
var dc = document.getElementById('autoc');
dcc.innerHTML = ' ';
var i = 0;
var target = "https://api.github.com/users/mralexgray/repos"
//
if(dc.value.length > 0){
loadXMLDoc(target,'GET',function(data){
data.forEach(function(x){
if(i < 10){
if(x.name.toLowerCase().indexOf(dc.value.trim()) != -1){
dcc.innerHTML += '<p class="accItem">' + x.name.toLowerCase() + '</p>';
i++;
}
}
});
});
}
}
.accItem{
background-color:#333;
color:#fff;
width:200px;
}
#autocc{
width:200px;
}
<body>
<input type="text" id="autoc" onkeypress="ontxtChange()" > example : "am"
<div id="autocc">
</div>
</body>
suggestion--
condition in call ajax (slow with big data)
condition in send/receive data with ajax
hope help you this way...
It is possible, but you will need to write much more code. Your best option to use existing library that handles this for you:
Documentation: https://github.com/devbridge/jQuery-Autocomplete
Demo: http://devbridge.github.io/jQuery-Autocomplete/
I am creating a simple ajax call that retrieves the content of a specified url and writes it to the page. The problem I am having is that it replaces the entire body contents with this information
here is the JS:
(function(){
var mb = window.mb = {};
function get_ad(url, parameters){
var result = "";
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.5.0"];
for (var i = avers.length -1; i >= 0; i--) {
try {
http_request = new ActiveXObject(avers[i]);
if (http_request){
break;
}
} catch(e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
gen_output(http_request.responseText);
} else {
alert('Error');
}
}
}
http_request.open('GET', url + parameters, true);
http_request.send(null);
}
function gen_output(ad_content){
document.write("<div id=\"mb_ad\">");
document.write(ad_content);
document.write("</div>");
}
get_ad("http://localhost/test/test.html", "");
})();
and here is the html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
i am text before <br/>
<script type="text/javascript" src="mb.js"></script>
<br />
i am text after
</body>
</html>
using firebug to inspect, i do not see the text before or the text after, just the <div id="mb_ad"> and the content from the test.html page. If i remove the ajax call and just do 3 document.writes the text before and the text after will display properly. jQuery is not an option, I have to do this without the help of a large library as size and speed are of the essence.
You can't use document.write once the document has completed loading. If you do, the browser will open a new document that replaces the current.
Use the innerHTML property to put HTML code inside an element:
function gen_output(ad_content){
document.getElementById('mb_ad').innerHTML = ad_content;
}
Put the element before the script, so that you are sure that it exists when the callback function is called:
i am text before
<div id="mb_ad"></div>
i am text after
<script type="text/javascript" src="mb.js"></script>
It doesn't matter much where you place the script, as nothing will be written to the document where it is.
in case you cant control the remote script you might be able to write something like so:
<script>
var tmp = document.write;
document.write = function () {
document.getElementById('someId').innerHTML = [].concat.apply([], arguments).join('');
};
</script>
<script .....>
document.write = tmp;
Well it is a nasty hack but it seems to work...
var div = document.createElement('div');
div.id = 'mb_ad';
div.innerHTML = ad_content;
Now, you can append this node wherever you want it to be.
you can use <script>document.body.innerHTML+="//Your HTML Code Here";</script>
Same Leon Fedotov answer but more jQuery
{
var old_write = document.write;
var $zone = $('.zone.zone_' + name);
// redefine document.write in this closure
document.write = function () {
$zone.append([].concat.apply([], arguments).join(''));
};
// OA_output[name] contains dangerous document.write
$zone.html(OA_output[name]);
document.write = old_write;
}
I had the same problem with the following code :
$html[] = '<script>
if($("#mf_dialogs").length == 0) {
document.write("<div id=\"mf_dialogs\"></div>");
}
</script>';
The following code replaces document.write efficiently :
$html = '<div id="dialogHolder"></div>
<script>
if($("#mf_dialogs").length == 0) {
document.getElementById("dialogHolder").innerHTML="<div id=\"mf_dialogs\"></div>";
}
</script>';
The way you can emulate document.write somewhat is the following code:
<script>
(function(script) {
var parent = script.parentNode;
var node = document.createTextNode('Surprise!');
parent.replaceChild(node, script);
})(document.currentScript);
</script>
This way you can put arbitrary HTML in place of a script element. If you have a simpler case, like you can wrap a script in another tag, you can do even simpler version.
<script>
document.currentScript.parentElement.innerHTML = 'Surprise!';
</script>
Can someone please advise me on how my Ajax div can get an address bar variable. The usual way just doesn't work.
My address bar currently looks like this:
http://localhost/social3/browse/?locationName=Cambridge
Obviously, the word I'm trying to access here is 'Cambridge'. Usually, I would use a little php and do this:
$searchResult = $_POST['locationName'];
echo $searchResult;
But because I'm in an Ajax div, I can't seem to get to the variable.
Do I need to add some JavaScript wizardry to my Ajax coding? (I have little knowledge of this)
My Ajax:
<script>
window.onload = function () {
var everyone = document.getElementById('everyone'),
searching = document.getElementById('searching'),
searchingSubmit = document.getElementById('searchingSubmit');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
everyone.className = 'filterOptionActive';
searching.className = 'filterOption';
}
searching.onclick = function() {
loadXMLDoc('indexSearching');
searching.className = 'filterOptionActive';
everyone.className = 'filterOption';
}
searchingSubmit.onclick = function() {
loadXMLDoc('indexSearchingSubmit');
}
function loadXMLDoc(pageName)
{
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)
{
document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
}
}
function get_query(){
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
xmlhttp.send();
}
}
</script>
<!-- ends ajax script -->
If your url contains the variable, you should use $_GET["key"] instead of $_POST
alternatively, you can use $_REQUEST["key"] to handle both cases.
Hi I have the following code
<html>
<head>
<script type="text/javascript">
var xmlhttp;
var allSearchResults = [];
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction(paramm)
{
loadXMLDoc("ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var txt=xmlhttp.responseText;
if (txt.match(paramm)!= -1){
//store all instances in allSearchResults array Here
}
else{
document.getElementById("myDiv").innerHTML = paramm;
}
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction('CXS101289')">Change Content</button>
</body>
</html>
ajax_info.txt
CXS101289_5_R1A06_100628150914
CXS101289_5_R1A06_100628343414
CXS10rfe_5_R1A06_100628150955
CXS101349_5_R1A06_100628150432
CXS154f89_5_R1A06_100628150914
CXS101289_5_R1A06_10062456914
CXS101369_5_R1A06_100628150914
CXS15679_5_R1A06_100628150914
So I want to search this file for the "CXS101289". So after I have run this method, the "allsearchResults" array shall contain ["CXS101289_5_R1A06_100628343414","CXS101289_5_R1A06_100628343414","CXS101289_5_R1A06_10062456914"]
Any smart idea on how to implement this?
This should do what you're looking for
result = txt.match(new RegExp("\\b" + param + "\\S*", "g"));
for example after
param = "x";
txt = "x_1 y_2 z_3 x_4 yx_5 z_6 x_7";
result = txt.match(new RegExp("\\b" + param + "\\S*", "g"))
result is ["x_1", "x_4", "x_7"]
Note that if param is going to contain charaters that have a special meaning for a regular expression (for example * or + or ]) then you have to escape them by prepending a backslash.
The initial \b is needed to be sure that your search key is only accepted at the beginning of an item.
function findMatched(text, keyword) {
var arr = text.split('\n');
var result = [];
for(var i = 0, len = arr.length; i < len; i++) {
if(arr[i].match(keyword)) {
result.push(arr[i]);
}
}
return result;
}
//...and in your code
if (txt.match(paramm)!= -1){
allSearchResults = findMatched(txt, paramm);
}
It is the only way I can see it solve. But maybe you already taught of this and where asking something else.
I am creating a simple ajax call that retrieves the content of a specified url and writes it to the page. The problem I am having is that it replaces the entire body contents with this information
here is the JS:
(function(){
var mb = window.mb = {};
function get_ad(url, parameters){
var result = "";
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.5.0"];
for (var i = avers.length -1; i >= 0; i--) {
try {
http_request = new ActiveXObject(avers[i]);
if (http_request){
break;
}
} catch(e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
gen_output(http_request.responseText);
} else {
alert('Error');
}
}
}
http_request.open('GET', url + parameters, true);
http_request.send(null);
}
function gen_output(ad_content){
document.write("<div id=\"mb_ad\">");
document.write(ad_content);
document.write("</div>");
}
get_ad("http://localhost/test/test.html", "");
})();
and here is the html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
i am text before <br/>
<script type="text/javascript" src="mb.js"></script>
<br />
i am text after
</body>
</html>
using firebug to inspect, i do not see the text before or the text after, just the <div id="mb_ad"> and the content from the test.html page. If i remove the ajax call and just do 3 document.writes the text before and the text after will display properly. jQuery is not an option, I have to do this without the help of a large library as size and speed are of the essence.
You can't use document.write once the document has completed loading. If you do, the browser will open a new document that replaces the current.
Use the innerHTML property to put HTML code inside an element:
function gen_output(ad_content){
document.getElementById('mb_ad').innerHTML = ad_content;
}
Put the element before the script, so that you are sure that it exists when the callback function is called:
i am text before
<div id="mb_ad"></div>
i am text after
<script type="text/javascript" src="mb.js"></script>
It doesn't matter much where you place the script, as nothing will be written to the document where it is.
in case you cant control the remote script you might be able to write something like so:
<script>
var tmp = document.write;
document.write = function () {
document.getElementById('someId').innerHTML = [].concat.apply([], arguments).join('');
};
</script>
<script .....>
document.write = tmp;
Well it is a nasty hack but it seems to work...
var div = document.createElement('div');
div.id = 'mb_ad';
div.innerHTML = ad_content;
Now, you can append this node wherever you want it to be.
you can use <script>document.body.innerHTML+="//Your HTML Code Here";</script>
Same Leon Fedotov answer but more jQuery
{
var old_write = document.write;
var $zone = $('.zone.zone_' + name);
// redefine document.write in this closure
document.write = function () {
$zone.append([].concat.apply([], arguments).join(''));
};
// OA_output[name] contains dangerous document.write
$zone.html(OA_output[name]);
document.write = old_write;
}
I had the same problem with the following code :
$html[] = '<script>
if($("#mf_dialogs").length == 0) {
document.write("<div id=\"mf_dialogs\"></div>");
}
</script>';
The following code replaces document.write efficiently :
$html = '<div id="dialogHolder"></div>
<script>
if($("#mf_dialogs").length == 0) {
document.getElementById("dialogHolder").innerHTML="<div id=\"mf_dialogs\"></div>";
}
</script>';
The way you can emulate document.write somewhat is the following code:
<script>
(function(script) {
var parent = script.parentNode;
var node = document.createTextNode('Surprise!');
parent.replaceChild(node, script);
})(document.currentScript);
</script>
This way you can put arbitrary HTML in place of a script element. If you have a simpler case, like you can wrap a script in another tag, you can do even simpler version.
<script>
document.currentScript.parentElement.innerHTML = 'Surprise!';
</script>