Click me
$('.clickme').click(function(event) {
event.preventDefault();
var stringId = $(this).attr("id");
var mId = stringId.substring(2)
....
I can retrieve the value of id using ID of anchor element. I think I should be able to get it directly from href. So how do I retrieve value of id and status from HREF (url query string)?
I am using Jquery.
Thank you for your help.
UPDATE:
Also how do I can get all of the URL value .. i.e. "test.php?id=100&blah=blah"?
This code:
function querySt(ji) {
hu = $(".clickme").attr("href");
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
To use it:
document.write(querySt("id"));
document.write(querySt("status"));
Answer to your 'update':
http://ilovethecode.com/Javascript/Javascript-Tutorials-How_To-Easy/Get_Query_String_Using_Javascript.shtml
var stringId = $(this).attr("id"); // this will return p_100
var stringId = $(this).attr("id").split('_')[1]; // this will return 100
var attr= $(this).attr("href"); // this will return all href attribute value
UPDATE
//href="test.php?id=100&status=pending&time=2009"
var attrFromAnchor= $(this).attr("href").split('?')[1].split('&')[0].split('=')[1]; // returns 100
There are a lot of good solutions here but I figured I'd post my own.
Here's a quick little function I threw together which will parse a query string in the format from either window.location.search or from a provided search string value;
It returns a hash of id value pairs so you could reference it in the form of:
var values = getQueryParams();
values['id']
values['blah']
Here's the code:
/*
This function assumes that the query string provided will
contain a ? character before the query string itself.
It will not work if the ? is not present.
In addition, sites which don't use ? to delimit the start of the query string
(ie. Google) won't work properly with this script.
*/
function getQueryParams( val ) {
//Use the window.location.search if we don't have a val.
var query = val || window.location.search;
query = query.split('?')[1]
var pairs = query.split('&');
var retval = {};
var check = [];
for( var i = 0; i < pairs.length; i++ ) {
check = pairs[i].split('=');
retval[decodeURIComponent(check[0])] = decodeURIComponent(check[1]);
}
return retval;
}
To get the value of the query string from the URL without string parsing you can do:
window.location.search.substr(1)
If you want the name of the page before the ? you still need to do a little string parsing:
var path = window.location.pathname.replace(/^.*\/(.*)$/,'$1');
var query = path + window.location.search;
//If your URL is http://www.myserver.com/some/long/path/big_long%20file.php?some=file&equals=me
//you will get: big_long%20file.php?some=file&equals=me
Hope this helps!
Cheers.
Here's a concise (yet complete) implementation for getting ALL name/value pairs from a query string:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {};
var tokens;
while (tokens = /[?&]?([^=]+)=([^&]*)/g.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);
No need for jQuery, this solution works on all browsers:
function querySt(ji)
{
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
return "";
}
Answers here are outdated now.
See this solution using Vanilla JavaScript (ES5)
var qd = {}; // qd stands for query dict
document.getElementById("p_100")[0].href.split("?")[1].split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v,]})
I like to pretend it's oneliner, but I was told it's not. hmm...Who would split chained function calls on new lines anyways, right?
example:
"test.php?id=100&status=pending&time=2009"
> qd
id: ["100"]
status: ["pending"]
time: ["2009"]
// values can also be obtained like this
> qd.id[0] // "100"
> qd["id"][0] // "100"
*It returns arrays, because it is optimized for multi-valued keys. Look here for dummy solutions (without arrays).
note: To teach old browsers the new .forEach you can inject this polyfill from Mozilla (MDN).
Related
I have an array & I'd like to add data to the array using PHP. I can't add it directly.
How would I do this using array_push?
<script type="text/javascript">
var parks = [{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png"}]
</script>
You can try:
//if your JSON string on server side <--PHP-->
$park = json_decode([{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png"}],true);
$park['key'] = 'someValue';
$newJSON = json_encode($park);
// if your JSON string on client side <--JS-->
var parkObj = JSON.parse(park);
parkObj.key = 'someValue';
console.log(JSON.stringify(parkObj));
//[{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png","key" : "someValue"}]
I found http://www.php.net/manual/en/function.array-merge.php and feel this will do the job for me - thanks for your input.
I'm not sure exactly how to phrase this so I will show an example. I'm gathering input values in javascript and passing to my php page where I am trying to insert those values in a database.
Instead of inserting separate values it is inserting the entire string.
Part of my javascript below:
var form = document.forms[0];
var txtS = form["bulletlabels"];
var len = txtS.length;
var bulletlabels = "";
for(i=0;i<len;i++) {
bulletlabels += '"'+[i]+'_'+(txtS[i].value)+'_label",';
}
when I do an alert(bulletlabels); I get this:
"0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",
On my php page I have:
$bulletlabels = array($_POST['bulletlabels']);
$length = count($bulletlabels);
for ($i = 0; $i < $length; $i++) {
mysqli_query($con,"UPDATE bullets SET bullettitle = '".$bulletlabels[$i]."' WHERE bulletrow = ($i+1)");
}
This inserts the below string into the database on ONE Row which is not the desired effect:
"0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",
But here is the key to my confusion - if I manually type the string in, it inserts onto individual database rows as desired.
This inserts values individually as desired when typed manually:
$bulletlabels = array("0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",);
Does NOT work and inserts the full concatenated string:
$bulletlabels = array($_POST['bulletlabels']);
Hope I explained well enough - arrays elude me.
EDIT:
Fix for the trailing comma:
var delim = "";
for(i=0;i<len;i++) {
bulletlabels += delim+[i]+'_'+(txtS[i].value)+'_label';
delim = ",";
}
Reference link for trailing comma fix:
Can you use a trailing comma in a JSON object?
Try changing the following line:
$bulletlabels = array($_POST['bulletlabels']);
to
$bulletlabels = explode(',', $_POST['bulletlabels']);
Also do not add quotes in your javascript:
bulletlabels += '"'+[i]+'_'+(txtS[i].value)+'_label",';
should be
bulletlabels += [i]+'_'+(txtS[i].value)+'_label,';
Explanation:
Currently, $bulletlabels is an array with one element, and this element is the following string: "0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",. However, you want to have an array with several strings. That's why you need to use the explode function to convert it into a proper array.
Note:
Make sure not to include , in the label names, as it will break with this implementation. If you need to be able to use , too, you should use json functions.
I am trying to pass an array to the browser using php and jquery but I the when I try to use the 'data' returned from php's encode_json, it comes up undefined. I'm just learning php, jquery, and json and so far haven't found very good documentation on alot of this stuff, especially json, even in the books I have. Thanks in advance!
Here is a stripped down version of the jquery I have
$(document).ready(function(){
var jsonResult;//I will want to be able to use the data in other functions
$.getJSON("json.php", function(data){
jsonResult = data;
var str;
var nuts = [203,204,205,207];
str = '<p>' + data[nuts[0]].NutraDesc + '</p>';
$('#stuff').html(str);
}
);
});
This is the php:
include_once 'databasePHP.php';
$json_tst = $db->query( "SELECT def.Nutr_No, NutrDesc, Nutr_Val, Units
FROM nutr_def as def JOIN nut_data as data ON def.Nutr_No = data.Nutr_No
WHERE data.NDB_No = 1001 LIMIT 0, 2");
$food = array();
while($row = $json_tst->fetch(PDO::FETCH_ASSOC))
{
$Nutr_No = $row['Nutr_No'];
$food[$Nutr_No][] = array(
'NutrDesc' => $row['NutrDesc'],
'Nutr_Val' => $row['Nutr_Val'],
'Units' => $row['Units']
);
};
echo json_encode($food);
?>
which returns this json which I checked on jsonlint.com and it said it was valid:
{"203":[{"NutrDesc":"Protein","Nutr_Val":"0.85","Units":"g"}],"204":[{"NutrDesc":"Total lipid (fat)","Nutr_Val":"81.11","Units":"g"}]}
It probably doesn't work because the numbers should be strings. Try to add quotes around the numbers in nuts, like this:
var nuts = ["203","204","205","207"];
The following probably works as well:
str = '<p>' + data[String(nuts[0])].NutraDesc + '</p>';
Also, have you tried adding console.log(data); to the getJSON function to make sure it receives the JSON?
EDIT:
Here is a working JSFiddle from your code:
http://jsfiddle.net/rKLqM/
Things that were wrong:
you weren't parsing the result as JSON (JSON.parse)
NutraDesc was spelled wrong
You didn't convert the numbers to strings
You needed to add [0] to the jsonResult because there's an extra array within it (see the [])
In Javascript object property can be accessed with obj["propName"]
So, change
var nuts = [203,204,205,207];
to
var nuts = ["203","204","205","207"];
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.
Hey all, title may be abit misleading but i didnt know the correct way to write it.
Basically, how can i do the AS3 equivalent of this php code:
return array('x' => 0, 'y' => 0);
The standard way of doing it is like this. The main thing to remember is that 'Object' in AS3 is almost equivalent to PHP's associative array's.
var obj:Object = {x:0, y:0};
trace(obj['x']); // like in PHP
trace(obj.x); // also valid
// AS3 version of foreach in PHP
for(var key:String in obj) {
trace(key +" = " + obj[key]);
}
private var map:Dictionary = new Dictionary();
map["x"] = 0;
map["y"] = 0;
You can do something like this
var myArray:Array = new Array({x:'0'},{y:'1'},{x:'2'});
or
var myArray:Array = new Array({x:'0',y:'1'},{a:'1',b:'2'});