How to search a large String - javascript

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.

Related

Retrieving all XML from nodes with Javascript

I'm trying to get the xml from nodes. Let's say I have an XML file:
<?xml version="1.0"?>
<story title="My title here">
<subject key="key1" caption="Intro">
Text here for subject 1. There might be an occasional <html> markup present.
<action tag="actiontag"/>
</subject>
<subject key="key2" caption="Chap1">
Text for chapter 2
<directions>
<dir go="chap5" to="Solving"/>
<dir go="chap12" to="Searching">
<extra1 subtitle="subtitle">You can expect extra text here as well.</extra>
<extra2 subtitle="subtitle2"/>
</dir>
<dir go="chap2,chap5" to="Finding"/>
</directions>
</subject>
<chapters key="chap1" caption="Chapter1">
The text for chapter1 goes here
<newtag>This one has text as well</newtag>
</chapters>
</story>
Now I'm trying to get the whole XML code including nodes and tags into an array of objects. So the result should ideally be:
subjects[0].key=key1
subjects[0].caption=Intro
subjects[0].txt=Text here for subject 1. There might be an occasional <html> markup present.<action tag="actiontag"/>
subjects[1].key=key2
subjects[1].caption=Chap1
subjects[1].txt=Text for chapter 2<directions><dir go="chap5" to="Solving"/><dir go="chap12" to="Searching"><extra1 subtitle="subtitle">You can expect extra text here as well.</extra><extra2 subtitle="subtitle2"/></dir><dir go="chap2,chap5" to="Finding"/></directions>
This 'text' can than later be processed as XML.
Now I've been able to read the XML and access the tags separately. I've been able to traverse through the file and get the text but I can't seem to loop through all the nodes/text/tags and keep it formatted as is.
What I have is:
var xmlDoc;
function loadxml() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "assets/myfile.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
xmlhttp.onloadend = init(xmlDoc);
}
function init(xmlDoc) {
var subjects = [];
var x, i;
x = xmlDoc.getElementsByTagName('subject');
for (i = 0; i < x.length; i++) {
subjects.push({ key: x[i].getAttribute('key'), caption: x[i].getAttribute('caption'), txt: x[i].childNodes[0].nodeValue });
}
//just to check if there's something recorded..
document.getElementById("result").innerHTML = subjects[1].txt;
}
The array of objects is no problem, that works. But how do I change x[i].childNodes[0].nodeValue to hold all the childnodes of [subject] and keep accompanying tags and formatting?
Thanks for your time.
function loadxml() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "assets/myfile.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
responseText = xmlhttp.responseText;
textNodes = responseText.split(/<subject.*>/);
textNodes.shift(); //remove first chunk of text
for (var i = 0; i < textNodes.length; i++) {
textNodes[i] = textNodes[i].replace(/\r?\n|\r/g, ''); //remove line breaks;
textNodes[i] = textNodes[i].replace(/^\s*/, ''); // Replace "> " with ">"
textNodes[i] = textNodes[i].replace(/>\s*/g, '>'); // Replace "> " with ">"
textNodes[i] = textNodes[i].replace(/\s*</g, '<'); // Replace "< " with "<"
}
xmlhttp.onloadend = init(xmlDoc, textNodes);
}
function init(xmlDoc, textNodes) {
var subjects = [];
var x, i;
x = xmlDoc.getElementsByTagName('subject');
for (i = 0; i < x.length; i++) {
subjects.push({ key: x[i].getAttribute('key'), caption: x[i].getAttribute('caption'), txt: textNodes[i] });
}
console.log(subjects);
}

Change input autocomplete value

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/

javascript dynamic content not affected when ajax call

I am new to javascript, am using PHP variable for created link dynamically as given below
$addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart('.#$product_id.',"add")><span class="allitem"
<font color="#A2F3AB">Added</font></span></button>';
This my php variable created by dynamically like below.
Added
Added
Added
I want to change the content of all variable“ added” as“ add” by just one click,Am using ajax function for changing that text as given below..
function clearcart(msg) {
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('cartreturn').innerHTML = xmlhttp.responseText;
document.getElementsByClassName('allitem').innerHTML = "Add";
}
}
xmlhttp.open("GET", "/addcart.php?msg=" + msg, true);
xmlhttp.send();
}
But first link text only affected.. other is not affected how I can solve this problem
document.getElementsByClassName returns a NodeList. You have to iterate over all the elements:
var allItems = getElementsByClassName('allitem');
for (var i = 0; i < allItems.length; i++) {
allItems[i].innerHTML = 'Add';
}
See this question.
You can't do document.getElementsByClassName('allitem').innerHTML.
You can do document.getElementsByClassName('allitem')[0].innerHTML = "Add"
Do you have several elements with the class "allitem"? If you don't, then maybe you should use an id, instead of a class, and then call document.getElementById('allitem').innerHTML = "Add";

Ajax div can't access address bar variable

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.

Need help to improve this largest common substring implementation

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

Categories