I need a simple way to search my Json string, using javascript.
Here's my PHP that creates my Json String:
<?php
$allnames = array();
$res = mysql_query("SELECT first,last FROM `tbl_names`");
while ($row = mysql_fetch_array($res)){
$allnames[$i++] = $row['first'].':'.$row['last'];
}
echo $jsonstring = json_encode($allnames);
/*
["john:smith","tony:stark","bruce:banner","clark:kent"]
*/
?>
I intend to put that $jsonstring
into a cookie, so I can reference it on several different pages, saving me from making any future queries.
I'm using the jquery cookie plugin from: https://github.com/carhartl/jquery-cookie
<script type="text/javascript" src="jquery.cookie.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$.cookie("allNames", JSON.stringify(<?=$jsonstring;?>))
});
</script>
So far so good! The cookie exists, and the data is saved, I can see in the browser.
I'm now interesting in searching that cookie's value, for instances of any of those names. And if I find one, I'll have options to perform, depending on my pages.
What I'd like to do is perform an onkeyup event, from a text box on a page:
<input type="text" name="lastname" id="lastname" />
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$("#lastname").keyup(function() {
// search the "allNames" cookie value for lastname
var allNames = $.cookie("allNames"); // gets cookie
var lastname = $(this).val();
// this is not seeming to work:
if( allNames.text().search('stark') != -1){
alert("that name exists");
}else{
alert("name does not exist");
}
});
});
</script>
I'm sure it's an easy task that I'm just not grasping. And maybe json isn't the best way to save cookie data either.
But how would I search a cookie's value? Or can someone advise a better solution?