get select options from php in x editable - php

I am using x editable for inline editing.
JQUERY
$('#status').editable({
value: 2,
source: [
{value: 1, text: 'Active'},
{value: 2, text: 'Blocked'},
{value: 3, text: 'Deleted'}
]
});
This one is running fine. But the problem is, I want to get source options from php. For that I have an array.
PHP
$php_array = Array ( [MOBILE_TOPUP] => MOBILE_TOPUP
[PICKUP] =>PICKUP
[DELIVERY] => DELIVERY
[BANK_DEPOSIT] => BANK_DEPOSIT )
I tried with by passing below variable in source but it's not working:
var json_array = <?=json_encode($php_array)?>;
How can I achieve this? Do I need to change array structure in PHP? Thanks for any help!

Yes, you have to change array structure as below :
$php_array = Array (
array('value' => 1, 'text' => 'Active'),
array('value' => 2, 'text' => 'Blocked'),
array('value' => 3, 'text' => 'Deleted'),
);
var json_array = '<?=json_encode($php_array)?>';

You shouldn't use PHP inside JS, better to make an ajax call. This feature is built into x-editable if you use the source option with a string like so:
$('#status').editable({
value: 2,
source: 'mypage.php'
});

Related

json_encode( json_encode (array) )

I'm trying to create a PHP script to generate JSON data for a jqplot bubble chart. The jqplot sample code requires data in the format
var arr = [
[45, 92, 1067, {label:"Alfa Romeo", color:'skyblue'}],
etc.
];
My script is along the lines of
while ...
array_push(
$arrBubble,
array(
11,
123,
1236,
json_encode(
array('label' => $car, 'color' => 'skyblue')
)
);
}
echo json_encode($arrBubble);
The problem is that the result is
[ [11, 123, 1236, "{\"label\":"VW", \"color\":\"skyblue\"}"] ]
The double json_encode has encoded the object(?) as a literal string.
What's the best way to work around this?
There is no reason to explicitly have a json_encode for one of the values inside the array. When you're using json_encode, it'll convert each level of the array as you expect.
var_dump(json_encode([
11,
123,
1236,
['label' => $car, 'color' => 'skyblue']
]));
Outputs the structure you want:
string(48) "[11,123,1236,{"label":"VW","color":"skyblue"}]"

POSTing a multidimensional array from Python

I'm trying to POST an array to a RESTful PHP API. The idea is to allow (n>0) records, each containing a remote_id, a dimension_id and a metric.
Here's my client Python:
data = urllib.urlencode([
("remote_id", 1),
("dimension_id", 1),
("metric",metric1),
("remote_id", 1),
("dimension_id", 2),
("metric",metric2)
])
response = urllib2.urlopen(url=url, data=data)
And here's my serverside PHP
<?php
print_r($_POST);
?>
This returns, predictably:
Array
(
[remote_id] => 1
[dimension_id] => 2
[metric] => 16
)
It looks to me like I'm overwriting every instance of remote_id, dimension_id and metric with the final values, which is unsurprising since they're all keyed with identical names.
What's the proper way to do this? I can see a horrible method with unique keys (1_remote_id, 1_dimension_id, 1_metric + 2_remote_id, 2_dimension_id, 2_metric) but that doesn't scale very well.
I guess I'm after something like this PHP, but in Python:
<?php
$observations = array();
$observations[] = [
"remote_id" => "a1",
"metric_id" => "foo",
"metric" => 1
];
$observations[] = [
"remote_id" => "a1",
"metric_id" => "bar",
"metric" => 2
];
?>
Appreciate any tips!
Sam
Don't quote me on this (I haven't done any PHP in a LOOONG time), but this may just work:
data = urllib.urlencode([
("remote_id[]", 1),
("dimension_id[]", 1),
("metric[]",metric1),
("remote_id[]", 1),
("dimension_id[]", 2),
("metric[]",metric2)
])
I would give it a try anyway.

How conversion of data from JSON to php format happen

I am passing data to my php script using jQuery's .ajax method. I am passing a very complex JSON object as data. At server side I receive data in $_POST variable all converted to php format.
How this conversion happen? Does it happen at the client side or the server side? Which modules associated in this process. Any source to understand complete process in depth.
Client request:
var data = {
foo: 123,
bar: 456,
rows: [
{
column1 : 'hello',
column2 : 'hola',
column3 : 'bonjour',
},
{
column1 : 'goodbye',
column2 : 'hasta luego',
column3 : 'au revoir',
},
],
test1:{
test2: {
test3: 'baz'
}
}
};
$.ajax({
type: 'post',
cache: false,
url: './ajax/',
data: data
});
At Server Side My '$_POST' var:
Array
(
[foo] => 123
[bar] => 456
[rows] => Array
(
[0] => Array
(
[column1] => hello
[column2] => hola
[column3] => bonjour
)
[1] => Array
(
[column1] => goodbye
[column2] => hasta luego
[column3] => au revoir
)
)
[test1] => Array
(
[test2] => Array
(
[test3] => baz
)
)
)
This code snippet is taken from here.
Jquery is converting the data into HTTP format. http://en.wikipedia.org/wiki/POST_%28HTTP%29
This link shows how arrays are encoded: http://php.net/manual/en/function.http-build-query.php
You can use PHP itself to generate the HTTP format. I converted your array to PHP format:
$data = array( 'foo' => 123,
'bar' => 456,
'rows' => array( 0 => array( 'column1' => 'hello',
'column2' => 'hola',
'column3' => 'bonjour'),
1 => array( 'column1' => 'hello',
'column2' => 'hola',
'column3' => 'bonjour')),
'test1' => array('test2' => array('test3' => 'baz')) );
Then you can generate the HTTP as follows:
echo http_build_query($data);
I got the following result:
foo=123&bar=456&rows%5B0%5D%5Bcolumn1%5D=hello&rows%5B0%5D%5Bcolumn2%5D=hola&rows%5B0%5D%5Bcolumn3%5D=bonjour&rows%5B1%5D%5Bcolumn1%5D=hello&rows%5B1%5D%5Bcolumn2%5D=hola&rows%5B1%5D%5Bcolumn3%5D=bonjour&test1%5Btest2%5D%5Btest3%5D=baz
JSON is a universal data exchange format (to all languages that support its specification that is). The JSON data is encoded from a memory object to a JSON-formatted string by the language that is sending it, and decoded (from string to object) by the language that receives it.
An important point when talking about jQuery and JavaScript is that the syntax for a JSON looks similar to JavaScript, but it is actually more strict than the syntax for a regular JavaScript Object (see: What are the differences between JSON and JavaScript object?). For example, the JavaScript object literal you have posted above is not valid JSON, becuase both the keys and values are not surrounded by quotes. Additionally, there is technically no such thing as a JSON Object. A glob of JSON data is acutally just a String written in a subset of JavaScript's Object Notation.
So, PHP's json_encode($object) function and jQuery's encodeJSON([Object]) function will transform a memory object in their respective languages into a string that both languages (and others of course) can accept as data. The json_decode($string) and parseJSON([String]) functions in PHP and jQuery, respectively, take a JSON string and commit it to memory as an object.
jQuery encodes the object data as a key value pairs, for example if we have:
var data = {
foo: 123,
bar: 456,
rows: [
{
column1 : 'hello',
column2 : 'bonjour',
},
{
column1 : 'goodbye',
column2 : 'au revoir',
},
]
};
jquery will encode that object to the following string
foo=123&bar456&rows[][column1]=hello&rows[][column2]=bonjour&rows[][column1]=goodbye&rows[][column2]=au+revoir
and PHP will convert that string in to an array and assign it to the $_GET or $_POST array depending of the request.

Creating data for jqPlot using PHP

I am using http://www.jqplot.com/tests/pie-donut-charts.php which needs to have data given to it in the following format:
//JavaScript
var data = [
['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14],
['Out of home', 16],['Commuting', 7], ['Orientation', 9]
];
The data is generated serverside with PHP. I am manually creating the string as follows:
//PHP
$string.='["'.$row['name'].'",'.$row['count'].'],';
I would rather just create an array, and use json_encode() or something similar to create the data. Any suggestions how I would do so?
$array = array(
array(
"Heavy Industry",
12
),
array(
"Retail",
9
)
);
$json = json_encode($array);
var_dump($json); // "[["Heavy Industry",12],["Retail",9]]"

Pass array to javascript as array not JSON from PHP

First this is not a duplicate questions. I've looked through some similar problem and most of the answer is what I am using right now.
Here is the problem set up,
on PHP side
$array = array('name' => 'a', 'data' => array('0'=>15,'0.25'=>'18','0.35'=>19,'1' =>20));
echo json_encode($array);
on the JS side
data = $.parseJSON(data); // data is the return from the php script
above
As you can see the $array['data'] is an associative array with numeric number as its key and sorted in order. While parsing into JSON, javascript altered the order of that array and sorted 0 and 1 as numeric key and put them to the head of the object.
I know this is standard behavior for certain browser such as chrome, and IE9.
I've read somewhere that people suggest stick with array strictly if I want to maintain the order of the array.
But my question is how do you feed back an array from PHP to javascript as an array instead of using json object? Or is there other solution to this kind of problem . Thanks for the input in advance.
Thanks for the input in advance
Use an array to maintain order, and then an object to create the map. There are two ways. I would suggest:
$array = array('name' => 'a', 'data' =>
array(
array('key' => 0, 'value' => 15),
array('key' => 0.25, 'value' => 18),
array('key' => 0.35, 'value' => 19),
array('key' => 1, 'value' => 20),
)
);
echo json_encode($array);
Which will give you the JSON:
{
"name": "a",
"data": [
{"key": 0, "value": 15},
{"key": 0.25, "value": 18},
{"key": 0.35, "value": 19},
{"key": 1, "value": 20}
]
}
Then you will have order but to look up a certain key will be more difficult. If you want that to be easy you can return a mapping object as well like this:
$array = array('name' => 'a', 'data' =>
array(
"0" => 15,
"0.25" => 18,
"0.35" => 19,
"1" => 20,
),
'order' => array("0", "0.25", "0.35", "1")
);
echo json_encode($array);
Which will give you:
{
"name": "a",
"data": {
"0": 15,
"0.25": 18,
"0.35": 19,
"1": 20
},
"order": ["0", "0.25", "0.35", "1"]
}
One of these two methods of returning your data should prove to be the most useful for your specific use case.
Actually, it's PHP that takes the "0" and "1" keys and makes them numeric keys. This has nothing to do with your JavaScript.
There isn't any real way to work around this, but ideally your code should not rely on such things as "what order the keys of an object are in". It may be a better idea, just from what I see here, to separate the data into an array of keys and an array of values, then zip them back together on the JS side.
I'd suggest another field for storing order.
$array = array('name' => 'a',
'data' => array('0'=>15,'0.25'=>'18','0.35'=>19,'1' =>20),
'order'=> '0,0.25,0.35,1'
);
echo json_encode($array);

Categories