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.
Related
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"];
How do I convert the php code below into javascript? I google it and found something to do with st.replace(/,/g,"\n") but how to apply it to the variable? I have low knowledge about javascript and trying to learn it.
$items = explode("\n", $model);
The answer is:
items = model.split("\n")
No, you are searching for [String].split("\n") which returns an Array. The replace you found would be similiar to implode("\n", explode(",", $model)).
The basically equivalent code is:
var model = 'some string...';
var items = model.split('\n');
var yourArray = [];
var yourString = 'a,b,c,d,e';
yourArray = yourString.split(',');
I am uploading a file using PHP and want to return the file name and the file status to javascript. In PHP I create the json object by:
$value = array('result' => $result, 'fileName' => $_FILES['myfile']['name']);
print_r ($value);
$uploadData = json_encode($value);
This creates the json object. I then send it to a function in javascript and recieve it as a variable called fileStatus.
alert (fileStatus);
It displays
{"result":"success","fileName":"cake"}
which should be good. But when I try and do
fileStatus.result or fileStatus.fileName
I get an error saying that they are undefined. Please help I'm really stuck on this. Thanks.
The fileStatus is just a string at this point, so it does not have properties such as result and fileName. You need to parse the string into a JSON object, using a method such as Firefox's native JSON.parse or jQuery's jQuery.parseJSON.
Example:
var fileStatusObj = jQuery.parseJSON(fileStatus);
If the alert displays {"result":"success","fileName":"cake"} then you probably still have to turn the string into a JSON object. Depending on the browsers you are developing for you can use the native JSON support or the JSON.org implementation to turn your string into an object. From there on it should work as expected.
When you are setting the variable, do not put quotes around it. Just set the variable like this:
var fileStatus = <?php echo $uploadData; ?>;
or:
var fileStatus = <?=$uploadData?>;
Do not do this:
var fileStatus = '<?php echo $uploadData; ?>';
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.
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).