Ok so what i want to be able to do is to perform a suggestive style search using the contents of an array instead of a doing a mySQL database query on every keyup.
So imagine a javascript object or array that is full of people's names:
var array = (jack,tom,john,sarah,barry,...etc);
I want to then query the contents of this array based on what the user has typed into the input box so far. So if they have typed 'j',both jack and john will be pulled out of the array.
I know this is possible via php mysql and ajax calls, but for reason of optimization I would like to be able to query the js array instead.
Hope someone can help me with this!
W.
as the name suggests, this finds elements of an array starting with the given string s.
Array.prototype.findElementsStartingWith = function(s) {
var r = [];
for(var i = 0; i < this.length; i++)
if(this[i].toString().indexOf(s) === 0)
r.push(this[i]);
return r;
}
// example
a = ["foo", "bar", "fooba", "quu", "foooba"];
console.log(a.findElementsStartingWith("fo"))
the rest is basically the same as in ajax-based scripts.
http://wwwo.google.com?q=autosuggest+using+javascript
AJAX calls fetch the contents from another serverside script files. You already have your data in the JS. Read a AJAX tutorial doing this. Then, just remove the parts where AJAX calls are made and replace it with your array's contents, and you're good to go.
I ended up using the following function to build my AJAX free instant search bar:
Example JS object being searched:
var $members = {
"123":{firstname:"wilson", lastname:"page", email:"wilpage#blueyonder.co.uk"},
"124":{firstname:"jamie", lastname:"wright", email:"jamie#blueyonder.co.uk"}
}
Example of function to search JS object:
$membersTab.find('.searchWrap input').keyup(function(){
var $term = $(this).val(),
$faces = $membersTab.find('.member'),
$matches = [];
if($term.length > 0){
$faces.hide();
$.each($members,function(uID,details){
$.each(details,function(detail,value){
if(value.indexOf($term) === 0){//if string matches term and starts at the first character
$faces.filter('[uID='+uID+']').show();
}
});
});
}else{
$faces.show();
}
});
It shows and hides users in a list if they partially match the entered search term.
Hope this helps someone out as I was clueless as to how to do this at first!
W.
Related
I am using dump($value) function. I have an associative array with lots of entries in it. I need to see the values right away without having to click the expansion button when dumped. I can use var_dump() to see it right away but I like it more using dump because it is modern and interactive. Below is the snapshot of dump function:
the simple tip is: CTRL+click.
Here's the JavaScript you can put after the dump():
var compacted = document.querySelectorAll('.sf-dump-compact');
for (var i = 0; i < compacted.length; i++) {
compacted[i].className = 'sf-dump-expanded';
}
Credits go to Curtis Blackwell
you can use
echo '<pre>';
print_r($results);
echo '</pre>';
or more easy way is just
var_dump($results);
Here's a quick format tool, no need to use laravel: (Source)
$pretty = function($v='',$c=" ",$in=-1,$k=null)use(&$pretty){$r='';if(in_array(gettype($v),array('object','array'))){$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").'<br>';foreach($v as $sk=>$vl){$r.=$pretty($vl,$c,$in+1,$sk).'<br>';}}else{$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").(is_null($v)?'<NULL>':"<strong>$v</strong>");}return$r;};
echo $pretty($array);
Here's a screenshot of sample output, as well. (Bonus points for figuring out what the data is)
Inject this script in Browser with help of the temper monkey chrome extension and add the script for that web page where you want to do that...
let all_dumps = document.getElementsByClassName('sf-dump-note');
for(let i = 1 ; i < all_dumps.length ; i ++ ) {
all_dumps[i].click();
}
I would like make a script that automatically insert in a Array the Google+ ID's fetched from
the SocialGraphs Api but i can't understand the type of this result,here's the example of the result: http://pastebin.com/wfBAtjH7
If can be help,i've seen the method for isolate the ID's done in Javascript:
var oids = [];
var reobg = new RegExp("\\d{21}","g"); // only interested in user ID so prepare regexp
oids = resp.match(reobg); // get an array of ids
if (!oids == null){ // if something stringify it
oids = oids.join(",");
}
For get in a variable all the text,i've used this code:
$gplus = file_get_contents('https://plus.google.com/u/0/_/socialgraph/lookup/visible/?o=[null,null,"103227580967788703328"]&rt=j');
Where 103227580967788703328 is an example Google Plus ID.
Thanks in advance.
Kind Regards.
Luca.
Try and cycle through the input with this regex:
\[\[,,"(\d+)"\]
and grab the first group each time.
Try this \[(.*),(.*),"(.*)"\] this is may help U.
I am trying to use jQuery Autocomplete Plugin in my PHP web application.
I have a JSON file on the server that has the data for the search. It looks like this:
{
"_E161": {
"keggId":"rn:R05223",
"abbrev":"ADOCBLS",
"name":"Adenosylcobalamin 5'-phosphate synthase",
"equation":"agdpcbi[c] + rdmbzi[c] -> h[c] + adocbl[c] + gmp[c] ",
},
"_E163": {
....
}
}
I would like to go through this JSON file (has 3500 entries) with PHP script that gets search term from the jQuery autocomplete plugin. Then return the entries that contain search term back to client side to populate autocomplete.
What would be a better way to implement this? My first guess is to loop through the JSON file and use strpos() But I suspect that might be slow?
You can make use on preg_grep (Return array entries that match the pattern),
// sanitize, and perform some processing to ensure is a valid regex pattern
$pattern = ...;
$json = json_decode( ... );
$arr = array();
foreach ($json as $key=>$arr)
{
$arr[$key] = $arr['name'];
}
$matches = preg_grep("/$pattern/i", $arr);
// $matches will hold the matches
// and you refer back to the $json using associate key
I'm working on a DB/web based frontend, and have encountered an issue. First off, I have a form with a drop down menu containing a list of contracts. Upon selection of a contract, I'd like for the jobs associated with that contract (fetched from the MySQL DB) to populate a second drop down menu below the first.
I would have just had all the info in one menu, but an 8000 entry drop down menu is a little unwieldy.
My PHP and HTML are barely passable, but enough for my purposes, however my ECMA experience is limited to a little bit of ActionScript in Flash MX, many moons ago.
I'd like to avoid using third party JS libraries (such as jQuery) if at all possible, and I don't mind writing more code. I just need to know whether this is doable, and a little shove in the right direction.
I'll shut up now, heres the form to fetch the contract ID (and the associated client), and the incomplete job menu.
<select name='idcontract' onchange=''>
<!--fetch/display contracts/clients-->
<?php
include 'sqldb.php';
$cntqres = mysqli_query($dbc, 'SELECT * FROM contract');
while ($cntrow = mysqli_fetch_array($cntqres))
{
$cliqres = mysqli_query($dbc, "SELECT * FROM client WHERE idclient = '$cntrow[idclient]'");
while ($clirow = mysqli_fetch_array($cliqres))
{
echo "<option value='$cntrow[idcontract]'>$cntrow[idcontract] $clirow[name]</option>";
}
}
?>
</select>
<select name='idjob'>
<option value='NULL'>Please select a contract</option>
<!--here goes the magical piece of code I don't know how to write-->
</select>
Any help would be much appreciated.
Edit:
Here's the PHP called by FeatherAJAX:
<?php
include 'sqldb.php';
$cnt = mysqli_real_escape_string($dbc, $_GET['cnt']);
$sql = "SELECT * FROM job WHERE idcontract='$cnt' ORDER BY job.idjob";
$jqres = mysqli_query($dbc, $sql);
$i = 1;
while (($jrow = mysqli_fetch_array($jqres)) && ($i < count($jrow)))
{
echo "idjob=><option value='$jrow[idjob]' id='$jrow[idjob]'>Job-$i $jrow[part_desc]</option>";
$i++;
}
?>
First off, you may want to rewrite the chunk of code that produces the contract options. Looping through query results and performing another query for each record is inefficient. Based on your queries, you might be able to use this code, which does a single query and then generate the options based on that. (I had to use made-up column names in the ORDER clause. In general, you should always sort your recordset so that results are in a determinate order -- even if you don't care what that order is.
<select name="idcontract" id="idcontract">
<!--fetch/display contracts/clients-->
<?php
include 'sqldb.php';
$clients = mysqli_query($dbc, '
SELECT ct.idcontract, ct.idclient, cl.name
FROM contract ct LEFT OUTER JOIN client cl ON ct.idclient = cl.idclient
ORDER BY ct.contractname, cl.clientname
');
while ($client = mysqli_fetch_array($clients)) {
echo "<option value=\"{$client[idcontract]}\">{$client[idcontract} {$client[name]}</option>";
}
?>
</select>
<select name="idjob" id="idjob">
<option value="NULL">Please select a contract</option>
</select>
To your question, the code you're looking for actually doesn't go where that comment is. What you need is an event handler that responds to the user picking an option in the first SELECT; it should then grab the value of that option and request from the server a set of key-value pairs to stuff into the second SELECT.
Something like this:
document.getElementById('idcontract').onchange = function(event) {
// grab currently selected value
var sValue = null;
for(var i = 0, imax = this.childNodes.length; i < imax; i++) {
var eOption = this.childNodes[i]; // shorthand
if(eOption.selected) {
sValue = eOption.value;
break;
}
}
if(!sValue) return;
// get the sub-options for this value
getSubOptions(sValue, function(XHR) {
// this code runs once the response comes back from the server
var aPairs = [];
var nlJobs = XHR.getElementsByTagName('jobs'); // assumptions #1 & #2: response is XML, includes <job> tag for each job
// extract key-value pairs from XML
for(var i = 0, imax = nlJobs.length; i < imax; i++) {
var xJob = nlJobs[i]; // shorthand
/*
assumption #3: <job> tag has "id" property
assumption #4: job name appears inside <job> tag
assumption #4.5: you've got an abstraction layer that normalizes XML node interfaces so that "text" and "textContent" are folded into "textContent"
*/
aPairs.push({ 'key': xJob.getAttribute('id'), 'value': xJob.textContent });
}
// given array of key-value pairs, rebuild select box
var eJobs = document.getElementById('idjob');
setOptions(eJobs, aPairs);
});
}
function setOptions(eNode, aPairs) {
if(!eNode || !eNode.nodeName || eNode.nodeName.toUpperCase() !== 'SELECT') return false;
// empty SELECT of all options
while(eNode.firstChild) {
eNode.removeChild(eNode.firstChild);
}
// build up new nodes
var eOpt = null;
for(var i = 0, imax = aPairs.length; i < imax; i++) {
eOpt = document.createElement('OPTION');
eOpt.value = aPairs[i].key;
eOpt.appendChild(document.createTextNode(aPairs[i].value));
eNode.appendChild(eOpt);
}
return true;
}
Of course, this is missing an important piece: you need some kind of AJAX abstraction layer. You don't need to get that from a framework, and a good library for this can be less than 50 lines of code (e.g. see PPK's ajax script on quirksmode.org), but you absolutely need something. That layer will provide two benefits: (1) cross-browser compatibility; (2) syntactic sugar.
For example, the code above doesn't include the definition of getSubOptions. That's because the logic will vary based on the interface provided by your AJAX abstraction. The idea, though, is that you'll perform a GET request against a script you write that accepts arguments and returns data satisfying that request. In the code above, I pretended that the script you write will return properly-formed XML data, with a MIME type identifying it as such. Alternatively, you could use JSON (or JSONP), straight text (e.g. CSV-style data), or even raw HTML that you'll just insert into the page.
The benefit of using a full framework is that they all provide convenient ways of doing DOM manipulation (i.e. syntactic sugar again).
The bottom line: you can absolutely do this with a homegrown approach (and I'm proud to say I've done it myself). But it will take longer -- not just because it's less convenient, but also because you'll have to re-invent the wheel === finding and fixing bugs in your code instead of leveraging well-tested core components from some library.
EDIT: If you want to use JSON as a data interchange format instead of XML, you'd modify the response handler being passed to getSubOptions like so:
getSubOptions(sValue, function(XHR) {
// this code runs once the response comes back from the server
var aPairs = eval(XHR.responseText); // assumes JSON defines an array of key-value pairs
// given array of key-value pairs, rebuild select box
var eJobs = document.getElementById('idjob');
setOptions(eJobs, aPairs);
});
And here's a sample of what that JSON might look like:
[ { key: '1234', value: 'Job #1' },
{ key: '2345', value: 'Job #2' },
...
];
In this example, the JSON structure conveniently mirrors the property names expected by setOptions; that said, key and value seem pretty inoffensive.
If you're set on using JSON for data, you may want to look into JSONP as a more secure alternative. It's real similar, but the design pattern is a little different from the anonymous callback technique above.
EDIT 2: Modified sample code for the responder:
<?php
include 'sqldb.php';
$cnt = mysqli_real_escape_string($dbc, $_GET['cnt']);
$sql = "SELECT * FROM job WHERE idcontract='$cnt' ORDER BY job.idjob";
$jqres = mysqli_query($dbc, $sql);
$i = 1;
// prepare the response
header('Content-Type: text/html');
while (($jrow = mysqli_fetch_array($jqres)) && ($i < count($jrow))) {
echo "<option value=\"$jrow[idjob]\" id=\"$jrow[idjob]\">Job-$i ${htmlentities(jrow[part_desc])}</option>";
$i++;
}
?>
First off, I do not want what is in the URL query. I want what PHP see's in the$_GET array.
This is because the URL query will not show all the params if mod_rewrite has been used to make pretty URLs
So is there a way to get the query string that would match exactly what is in the php $_GET array?
--
I came up with a way myself using PHP and JavaScript like so:
function query_string()
{
<?php
function assoc_array_to_string ($arr)
{
$a = array();
foreach($arr as $key => $value)
{
$str = $key.'='.$value;
$a[] = $str;
}
return implode("&",$a);
}
?>
return '<?=urlencode(assoc_array_to_string($_GET))?>';
}
...but I need to do this with just javascript if possible because I can't put PHP code in a .js file.
Won't JavaScript "only see" the query string? How would client-side script know about any rewrite rules?
The only way I can think of is to use PHP -- echo it into a variable in an inline script in your main page rather than the JS file.
In your page <head>:
<script type="text/javascript">
var phpQueryParams = <?php print json_encode($_GET); ?>
</script>
Assuming at least PHP 5.2, otherwise use an external package
The query string is found in window.location.search, but that's the raw query string. So if you run something like this:
(function () {
QueryStr = {}
QueryStr.raw = window.location.search.substr(1);
var pairStrs = QueryStr.raw.split('&');
QueryStr.val = {}
for(var i=0,z=pairStrs.length; i < z; i++) {
var pair = pairStrs[i].split('=');
QueryStr.val[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
})();
You'd have something very much like $_GET in QueryStr.val.
Of course, you mention that you've mixed things up a bit using mod_rewrite, which is cool, but since we don't know your rewrite scheme, we can't help specifically with that.
However... you know your rewrite scheme, and you could probably modify the code I gave above to operate on some other part of window.location. My bet is that you'd want to split window.location.pathname on the / character instead of &.