Object in jquery using json response - php

I want to create an object in jquery using a json response that is return from my controller
var cellContents = {'29-08-2018': '20','18-08-2018': '60'};
This is the desired format that i want and below given is my json response
{"status":1,"result":[{"followup_datee":"17-08-2018","date":[{"fcount":"1"}]},{"followup_datee":"18-08-2018","date":[{"fcount":"1"}]}]}
i tried some code to make the format that i want but it failed this is the code that i tried
var arr2 = [];
//var cellContents = JSON.parse(data.result);
for(var i=0; i<data.result.length; i++){
var arr = [];
for(var j=0; j<data.result[i].date.length; j++)
{
arr.push(parseInt(data.result[i].date[j].fcount));
}
var test = [data.result[i].followup_datee];
arr2.push(test.concat(arr));
}
var jsonString = JSON.stringify(arr2);
console.log(jsonString);
after i tried this code i got some response in the console like this
[["17-08-2018",1],["18-08-2018",1]]
This is the controller that i am using in php
public function getLeadcount()
{
$status = 1;
$arr = [];
$sess = $this->session->userdata('user_id');
$result = $this->mdl_lead_registration->getLeaddate($sess);
if(!empty($result))
{
$status = 1;
foreach($result as $res)
{
$res->{'date'} = '';
$res->date = $this->mdl_lead_registration->getLeadcount($sess,$res->followup_datee);
}
}
echo json_encode(array("status" => $status,"result" => $result));
}
I think you all understand my problem . Any sort of help is appreciable.

Use the following code:
var data = {"status":1,"result":[{"followup_datee":"17-08-2018","date":[{"fcount":"1"}]},{"followup_datee":"18-08-2018","date":[{"fcount":"1"}]}]};
var obj = {};
for (var i = 0; i < data.result.length; i++){
obj[data.result[i].followup_datee] = parseInt(data.result[i].date[0].fcount);
// Here you change the property.
// In js you can access to an object's property like an array,
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors.
// If you want to use the count as a string, use instead:
// obj[data.result[i].followup_datee] = data.result[i].date[0].fcount;
}
console.log(obj);

Related

can't set variable in JavaScript based on json id from php

I have a simple array from a php file (the reason for not using a json file is cause this info comes from a mysql database)
$array[0] = array('id' => 1,'price' => '325');
$array[1] = array('id' => 2,'price' => '486');
header('Content-type: application/json');
echo json_encode($array);
and it echos as:
[{"id":1,"price":"325"},{"id":2,"price":"486"}]
now what I want to do is take the id and add it to a variable called counterval so that JavaScript will read it as
counterval1 = 325;
counterval2 = 486;
but I can't seem to get it to read that way. Here is the script at the current moment.
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval + data[i].id = data[i].price;
console.log (counterval2);
});
$('#results').html(counterval2);
});
var counterval1 = 0;
var counterval2 = 0;
any help on this would be greatly appreciated.
you can't do that... but you can do this...
var counterval = [];
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval[data[i].id] = data[i].price;
console.log (counterval[2]);
});
$('#results').html(counterval[2]);
});
counterval[1] = 0;
counterval[2] = 0;
See my comment on your post. If you really want the vars to look like you explained:
eval("counterval" + data[i].id + " = data[i]..price");
alert(counterval1);

Creating a Javascript version of a PHP multidimensional associated array

I have a set of data that is not normalized. I do the normalization in PHP it it works just fine.
The dataset looks like this (screenshot bellow), it is a lot larger tho. I am only interested in orginizing the category and the type. With those two orginized I can make good tables and menu's.
Problem
Now the problem is, I am switching to an AJAX system, and the data no longer comes into PHP. Instead it comes directly into the page using node.js/mongodb. Is there a way I can do something like this:
<script type="text/javascript">
// Array containing all the objects from the server
// looks like this
var data = [Object, Object, Object];
var artikelen = [];
for(var i=0; i<data.length; i++){
artikelen[data[i].categorie][data[i].type][] = data[i];
}
</script>
// ----------------
OLD SITUATION
//-----------------
In PHP I did this:
$sql = "SELECT *
FROM mydb
WHERE merk = 'webecos'
ORDER BY categorie, type, code";
$result = $wpdb->get_results( $sql );
foreach($result as $row){
$artikelen[$row->categorie][$row->type][] = $row;
}
Now I can make good sorted tables / menu with nested loops. The code I used is this.
<ul id="inkoop_menu">
<?php foreach ( $artikelen as $categorie => $row ): ?>
<li>
<a class="inkoop_button" data-menu="categorie" href="#">
<?=$categorie; ?>
</a>
<ul>
<?php foreach ( $row as $type => $artikel ): ?>
<li>
<a class="inkoop_button" data-menu="type" href="#">
<?=$type; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
</ul>
Edit
Maybe this is a but better to understand. The array I am after looks like this:
array['categorie-name']['type-name'][x] = whole object;
I'm not really sure I totally follow you, but do you mean something like this?
var data = [Object, Object, Object];
var artikelen = [];
for(var i=0; i<data.length; i++){
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Array();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Array();
artikelen[data[i].category][data[i].type].push(data[i]);
}
More complete example: (also note I put category instead of categorie, change if needed).
<script language="javascript" type="text/javascript">
var obj1 = new Object();
obj1.category = 1;
obj1.type = 2;
obj1.id = 1;
var obj2 = new Object();
obj2.category = 1;
obj2.type = 2;
obj2.id = 2;
var obj3 = new Object();
obj3.category = 2;
obj3.type = 4;
obj3.id = 3;
// Array containing all the objects from the server
// looks like this
var data = [obj1, obj2, obj3];
var artikelen = [];
for(var i=0; i<data.length; i++){
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Array();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Array();
artikelen[data[i].category][data[i].type].push(data[i]);
}
alert( artikelen[1][2] ); // expected [object], [object]
alert( artikelen[1][2][0].type ); // expected 2
</script>
Key things to take away from this approach:
Check if array at key exists
If not, create it
.push can be used on a javascript array to add an item to an array
Using a string as a type for an object:
var obj1 = new Object();
obj1.category = 1;
obj1.type = "hello hello";
obj1.id = 1;
var obj2 = new Object();
obj2.category = 1;
obj2.type = 2;
obj2.id = 2;
var obj3 = new Object();
obj3.category = 2;
obj3.type = 4;
obj3.id = 3;
// Array containing all the objects from the server
// looks like this
var data = [obj1, obj2, obj3];
var artikelen = [];
for(var i=0; i<data.length; i++){
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Array();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Array();
artikelen[data[i].category][data[i].type].push(data[i]);
}
alert( artikelen[1][2] ); // expected [object], [object]
alert( artikelen[1]["hello hello"][0].type ); // expected "hello hello"
EDIT
I gave it some more, thought and after reading this, it turns out that arrays in Javascript are not well suited to be used as associative arrays (like in PHP). In actuality, you are just adding attributes to an object. So making it an object instead is better. For example, the following:
var obj1 = new Object();
obj1.category = 1;
obj1.type = "hello hello";
obj1.id = 1;
var obj2 = new Object();
obj2.category = 1;
obj2.type = 2;
obj2.id = 2;
var obj3 = new Object();
obj3.category = 2;
obj3.type = 4;
obj3.id = 3;
// Array containing all the objects from the server
// looks like this
var data = [obj1, obj2, obj3];
var artikelen = [];
for(var i=0; i<data.length; i++){
if( !artikelen[data[i].category])
artikelen[data[i].category] = new Object();
if( !artikelen[data[i].category][data[i].type] )
artikelen[data[i].category][data[i].type] = new Object();
artikelen[data[i].category][data[i].type] = (data[i]);
}
console.dir( artikelen ); // if using a debugger with console, gives detailed info
Also, if using a debugger, such as Firebug in Firefox, you can see detailed info with the console.dir function.
Are you still able to work with PHP? If so, you can always bring the data from the server in the JSON format and let the client (in your case, the javascript language) read it and interpret it.

assigning a $_GET variable to a JS variable

www.mywebsite.com/?foo=bar
How can I get the value of foo into a Javascript variable?
You don't even need PHP for that. Basically, you can parse window.location.href to get the value of a GET URL parameter into a JavaScript variable.
There is plenty of code online, you can use for example this:
function getUrlParameter( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
To get the value of foo, just call getUrlParameter("foo") in your JavaScript code.
You can parse the window.location.search string for query variables.
https://developer.mozilla.org/en/DOM/window.location
For example
var query = window.location.search.substring(1);
var pairs = query.split('&');
var _get = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
_get[pair[0]] = pair[1];
}
I did some googling and here is a link for you http://www.zrinity.com/developers/code_samples/code.cfm/CodeID/59/JavaScript/Get_Query_String_variables_in_JavaScript
You can try this
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
EDIT
The above will parse the URL and give you the parameters as an associative array. You can also try
function getURLVars(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
In this if you want the value of foo, call this with getUrlVars('foo')

php to js array convert with jquery's ajax

Im trying to convert 5 PHP arrays to 5 js arrays.
I used to transfer php variables to js variables with json like this:
$return['variable'] = $variable;
echo json_encode($return);
And then fetch it as json object on the js side like this:
success : function(data) {
alert(data.variable);
}
now things are a bit more complicated, i need to transfer these 5 php arrays from a php script to my js script as 5 js arrays:
PHP arrays:
$i = 0;
while ($location = mysql_fetch_array($get_locations)) {
$location_full_name[$i] = $location['loc_full_name'];
$location_main_name[$i] = $location['loc_main_name'];
$location_sub_name[$i] = $location['loc_sub_name'];
$location_anchor_id[$i] = $location['loc_anchor_id'];
$location_type[$i] = $location['loc_type'];
$i++;
}
and fill these corresponding arrays:
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
i dont know how to do this. hope i can get some help :)
regards,
alexander
Maybe if you post what returns in "data" so we can help you more (i think). hehe.
I suggest, for your php code, where you set the data into the arrays:
$i = 0;
$rsl = array();
while ($location = mysql_fetch_array($get_locations)) {
$rsl[$i]['full_name'] = $location['loc_full_name'];
$rsl[$i]['main_name'] = $location['loc_main_name'];
$rsl[$i]['sub_name'] = $location['loc_sub_name'];
$rsl[$i]['anchor_id'] = $location['loc_anchor_id'];
$rsl[$i]['type'] = $location['loc_type'];
$i++;
}
echo json_encode($rsl);
So to get this on the javascript
// You could do the same... var location = []...
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
...
dataType: "json",
success : function(data) {
$.each(data, function(index, arr){
location_full_name[index] = arr['full_name'];
...
});
}
For each of your arrays, store the value returned from json_encode. And/or make them one array/object and do the same.
You can utilize the PHP array that is actually an ordered map. Below is an example:
PHP:
<?php
$location_full_name = array("Google, Inc.", "Siku-Siku.com");
$location_type = array("Google headquarter", "Virtual address");
$ret = array("full_name" => $location_full_name, "type" => $location_type);
echo json_encode($ret);
?>
JavaScript (jQuery):
<script type="text/javascript">
$(function() {
$.get("test.php", function(data) {
console.log(data.full_name[1]); // Prints "Siku-Siku.com".
}, "json");
});
</script>

using nested arrays by php http_build_query() and recieve them in flash AS3

i am having this hard time figuring what is needed to do,
i am using URLVariables to send/recieve values between flash and PHP
the problem is, i am unable to access nested arrays ( array inside an array ) with flash
heres an example:
$dgresult = array("total" => $results);
echo http_build_query($dgresult,"flf_");
in flash, all i need to do is to use:
var variables:URLVariables = new URLVariables(e.target.data);
then i can access it with :
variables.total
the problem now is when i have nested arrays:
$dgresult = array("total" => $results);
array_push($dgresult,$another_array);
http_build_query($dgresult,"flf_");
i can still access variables.total
but what about anything that has flf_ ?
how is that possible?
you should try to simply use established formats for complex data, such as JSON. For PHP see here and for AS3 see here. Or ready made solutions such as AMFPHP.
greetz
back2dos
or you can just parse the object
var url:String = 'http://localhost/dump.php';
var params:Object = {
test: 'ok',
nested_1: {
nested_2: {
nested_3: {
nested_4: {
hello: 'mf',
str: '~!##$%^&*()_+'
}
}
}
},
};
var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
parameters = fixParameters(parameters || {});
for (var key:String in parameters) {
variables[key] = parameters[key];
}
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.load(request);
and here is fixParameters method
private function fixParameters(data:Object, parameters:Object = null, prefixes:Array = null):Object {
var setPrefix:Array;
var prefixKey:String;
if (!parameters) {
parameters = {};
}
if (!prefixes) {
prefixes = [];
}
for (var key:String in data) {
setPrefix = prefixes.concat([key]);
if (typeof(data[key]) == 'object') {
parameters = fixParameters(data[key], parameters, setPrefix);
} else {
prefixKey = '';
for (var i:Number = 0; i < setPrefix.length; i++) {
prefixKey += i == 0 ? setPrefix[i] : '[' + setPrefix[i] + ']';
}
parameters[prefixKey] = data[key];
}
}
return parameters;
}

Categories