Jquery Ajax multiple tag search - javascript

Hi everyone i have one problem with my ajax tag search system. Following code working fine just one searching tag. But if i search multiple tag then it is not working. What i need to do here? What i am missing anyone can help me here ?
For example: When i write #innovation the the ajax will showing #innovation but when i search multiple tag like #innovation asking #stackoverflow then it is not searching #stackoverflow
$(document).ready(function() {
var start=/#/ig;
var word=/#(\w+)/ig;
$("#contentbox").live("keyup",function() {
var content=$(this).text();
var go= content.match(start);
var name= content.match(word);
var dataString = 'searchword='+ name;
if(go!==null && go.length!==0) {
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
if(name!==null && name.length!==0) {
$.ajax({
type: "POST",
url: "boxsearch.php",
data: dataString,
cache: false,
success: function(html) {
$("#msgbox").hide();
$("#display").html(html).show();
}
});
}
}
return false;
});
});
I think the problem is the following line :
var start=/#/ig;
var word=/#(\w+)/ig;

There's a million different ways to crack this nut. One of the methods I used in the past was to send the whole input as a single attribute on the service call, and then pass it into db call (via PHP) using the REGEX feature of MySQL. Using that feature, it searched for any combination of value 1, or value 2 or value 1 and value 2, etc.
But let's attack it from the front end as you're doing. You have an input coming in as a combination of "#word1 #word2". So rather than doing regex summersaults to find the beginning and the end, how about simplifying things and doing a string.split() on the "#" character. You can take the resulting array of values, loop to create your service call string (don't forget to trim blank spaces) and send the call off.

The problem is definetely coming from your regex. The second you write a second word in your textarea (I'm assuming you're using a textarea), the if condition fails.
I'm not regex expert, however I have a js solution:
var keywords = $(this).val().split(' ').trim();
Get all the keywords this way, then loop through each one and check if it's a correct tag.
var obj = [];
keywords.forEach(function (content) {
var go = content.match(start);
var name = content.match(word);
//check to see if the searchword is valid.
//If it is we add it to the list and continue the loop.
//If not we ignore it and continue the loop.
//If you want to stop the loop when one searchword is wrong add "return false;"
if(go !== null && go.length > 0 && name !== null && name.length > 0 ){
obj.push(name);
}
});
if(obj.length > 0){
var dataString = JSON.stringify(obj);
//do ajax call here
}
I'm also assuming you're sending all your searchwords at once to your php file.
EDIT: Pushing all valid keywords into an array obj that will be later parsed as a JSON string.

Related

Not work indexOf() for array that is from ajax text file data

jQuery version 1.4.4
aaa.txt
includes just 3row
01000
01001
01139
$.ajax({
url: "aaa.txt",
success: function(result){
console.log(result);
var rArr = result.split("\n");
var ee = rArr.indexOf("01001");
console.log(ee);
}
});
return -1.
I guess it should return 1. All the type are the string.
I can't understand why this situation happens.
var rArr = result.split(" ");// in this line you are spliting
var ee = rArr.indexOf("01001");// so if it is array you can not use indexOf it will work on sring.
var ee = rArr[index].indexOf("01001");//index should be according to your need
You should check your file and see it is actually using which linefeed. For example, if your file is from written by Windows Notepad, then it uses \r\n and so your .split() yields ["01000\r","01001\r","01139"] and so .indexOf() returns -1, as "01001"!=="01001\r".
I had to look at the source code of your question to determine this, but you end each line of the input data with a space.
"01001 " !== "01001"
You need to either:
Remove the space from the input file
Match it in the test
Remove it (with trim) from each member of the array (with map).

Javascript name field masking (Using regular expression)

i need to mask a name and i want it in Script.
i have a list format data.
Following is my jsp which put data in a variable.
<c:forEach value="${test}" var="v"/>
<c:set var = "nametest" value="${v.name}"
i only need names to be shown on the screen. so i made a variable only contains names. The problem is my script function doesn't look like
contain my data correctly.
Following is my script.
function maskingName(nametest){
var a = "${nametest}"
if (a === undefined || a ===''){
return '';
}
var pattern = /.$/;
return a.replace(pattern,"*");
}
after running it, i only get the last name (there are 10 names and it shows the only the last one)without masking.
My question is
1. how can i use List format in my script function?
2. why does the regular expression not working?
Thank you!
I have written a small java code that might help you understand better
static String maskingName(String nametest) {
if (nametest == null || nametest == "") {
return "";
}
String pStr = ".$" // ".*$";
Pattern pattern = Pattern.compile(pStr);
return pattern.matcher(nametest).replaceAll("***");
}
For input '12345' or '345345', the output will be '1234***' or '34534***'
Replacing pStr=".*$" will give output ******

Using url parameters for a page link

What I'm about to ask may sound stupid but I've been trying to figure it out for a few days now. I want to generate a link to a site:
example.github.io/Example/Example
That has a variable or something at the end of it
example.github.io/Example/ExampleVariable
and then read that variable as the page loads. In a perfect world it would look something like this:
http://Example.github.io/Example/Example<script>function(){}</script>
I also need to make sure that the page the user actually goes to or at least ends up on is the original link: i.e.
example.github.io/Example/Example
Any help would be greatly appreciated.
Also if anyone is wondering. Yes it is on github if that applies. I barely know PHP so that's not the best. It's for a ToDo list manager app I've made. There is a load function so users can share lists. The Load string (variable I'm trying to read) looks like this: /LoadNAME#THEME#Item A,Item B,ect.
If you're using github pages you could use URL parameters. In that case the url would look something like this: http://mypage.github.io/test/?myparam=value
Then you could query that with javascript and execute something based on that url parameters the url contains.
Alternatively, you can use this hash # old trick then after it use slashes
example.github.io/Example/#/var1/var2/var3
then using the window.location.href with couple split() uses will provide you
with an array of parameters.
/* URL in address bar:
http://localhost/test/js-url-parameters/#/str1/str2/str3/
*/
var docURL = window.location.href,
params = [];
// filter out the website origin "example.github.io" in the OP example
docURL = docURL.replace(window.location.origin, '');
// if /#/ found then we have URL parameters
// grabbing the parameters part of the URL
if (docURL.indexOf('/#/') > -1) {
docURL = docURL.split('/#/')[1];
if (docURL != '') {
// omit the last forward slash if exist
if (docURL[docURL.length - 1] == '/') {
docURL = docURL.substring(0, docURL.length - 1);
}
// split the URL final string o get an object with all params
params = docURL.split('/');
console.log(params);
}
} else {
console.log('No URL parameters found');
}
/* Output:
["str1", "str2", "str3"]
*/
UPDATE:
The above outputs all variables as string, so to retrieve numeric values you need to parseInt -or parseFloat() depending on your case.
For example, if for this URL:
http://localhost/test/js-url-parameters/#/str1/22/str3/
The above code will output ["str1", "22", "str3"], while we suppose to have 22 as integer, to fix this just add this:
// for each elements in params, if it is Not a Number (NaN) we return
// it as it is, else it's a nubmer so we parseInt it then return it
for(var i in params){
params[i] = isNaN(parseInt(params[i])) ? params[i] : parseInt(params[i]);
}
the above snippets go rights after the params = docURL.split('/'); line.
Now the URL:
http://localhost/test/js-url-parameters/#/str1/22/str3/ outputs ["str1", 22, "str3"], as you see now 22 is a number rather than a string.

Jquery Test if a url already contain a parameter

I know there are a lot of questions about this, but I didnt found exactly what I needed
This is the js I have
$j('.showCategory li a').each(function() {
var catId = $j(this).attr("data-id");
this.href += (/\?/.test(this.href) ? '&' : '?') + 'filter_category='+ catId;
});
This works great as it generate my url with the param I want. The problem is that if I click multiple times (this filter is available on all pages), it's adding the same parameter over and over, generating an url like this:
http://www.blabla.com/search?search=cat&filter_duration=short&filter_duration=medium&filter_duration=long
I tried fixing that by adding a condition like
$j('.showCategory li a').each(function() {
if(this.href.indexOf('filter_category') == -1) {
var catId = $j(this).attr("data-id");
this.href += (/\?/.test(this.href) ? '&' : '?') + 'filter_category='+ catId;
} else {
????
}
});
But in that case, it's not adding any parameter, but it's not replacing the value. How can I solve this please?
Use this pattern to do an in-place replacement with a regular expression:
} else {
this.href = this.href.replace(/filter_duration=(.+?)(&|$.*)()/, "filter_duration=" + catId + "$2"
}
This uses capture groups to find an existing filter_duration element query parameter, and replaces the existing value in place with a new value (in this case catId). This should work regardless of whether it is the last query parameter in the string or not.
That said, I wouldn't regard this solution as optimal, and you would probably be better off with storing the values that you want in your url in a client side javascript object, and then rebuild the url each time from scratch whenever anyone changes a category. That way you won't have to worry about difficult to test cases where something goes wrong with a replacement and the client getting into a bad state.

Passing value to JS function through URL on window load

my page http://www.dinomuhic.com/2010/index.php loads the Showreel at the start of the page using an onLoad call in body like this:
<body onLoad="sndReq('96')">
96 is the ID of the showreel in the SQL Library.
The JS function "sndReq" is an AJAX call using JQuery which opens the requested item and displays it in the main window.
Now my question: What if I want to send a link to a client which opens a specific item directly so he does not have to navigate through the site?
Something like http://www.dinomuhic.com/2010/index.php?sndReq=234 (which of course doesn't work now and just opens the showreel, probably because the onLoad in the body tag overrides it)
How can I implement this? I want to be able to open specific items by URL but if nothing is passed through the URL it should always open item 96.
Thank you in advance. I'm sure its pretty easy I just can't see it.
Cletus
You need to parse the query string. I find the easiest way to deal with the query string is to do the following. First, you need to extract the query string from the URL:
var queryStr = window.location.search; // will give you ?sndReq=234
Then, you can strip out the ? and split each query string parameter into an array:
var paramPairs = queryStr.substr(1).split('&');
Now you can build a hash table object of the name/value pairs making up the query string:
var params = {};
for (var i = 0; i < paramPairs.length; i++) {
var parts = paramPairs[i].split('=');
params[parts[0]] = parts[1];
}
In your onload, you can now use the parameter thusly:
sndReq(params.sndReq);
Make sure that the code is run within a script in the head of your document so that it's computed before the onload is executed.
if you are using jQuery, why not use the DOM-ready handler instead of onload ? on that note, if it's just an ajax request, you don't even need to wait for DOM-ready. if you parse the query, you should be able to pass that in to your existing function.
// Wait for DOM-ready, may not be needed if you are just
// making a request, up to you to decide :)
$(function() {
// window.location.search represents the query string for
// current URL, including the leading '?', so strip it off.
var query = window.location.search.replace(/^\?/, "");
// If there is no query, default to '96'
if ( !query ) {
query = '96';
}
// Call existing function, passing the query value
sndReq( query );
});
hope that helps! cheers.
You can use RegExp to accomplish this, read the url parameters and pass them to ajax.
this simple script will read the current url and pass through regex to filter for paramters you specify.
EG: ThisReq = gip('sndReq'); pulls sndReq and value from the url.
<script language="javascript">
function gip(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
sndReq('96');
else
return results[1];
}
// parameter pulled from url.
ThisReq = gip('sndReq');
// executes function sndReq();
sndReq(''+ThisReq+'');
</script>

Categories

Resources