I'm trying to use Ajax with Zend framework. I followed this tutorial and it works. I used following code to fetch the data:
$('#button').click(function() {
$.ajax({
url: './ajax/review/format/json',
dataType: 'json',
success: function(json_data){
alert('....');
}
});
});
The data parsed was like below:
Array ( [reviews] => Array ( [0] => Array ( [reviewid] => 3 [userid] => 1 [locationid]
=> 3 ) [1] => Array ( [reviewid] => 2 [userid] => 2 [locationid] => 2 ) [2] => Array (
[reviewid] => 1 [userid] => 1 [locationid] => 1 ) ) )
The Json I got was something like following:
{
"data": {
"reviews": [
{
"reviewid": 3,
"userid": 1,
"locationid": 3
},
{
"reviewid": 2,
"userid": 2,
"locationid": 2
}
]
}
}
I don't know where the "data" field comes from. I guess it relates to the way Zend parse data from controller to view, e.g. $this->view->data = array(...)
Hope I explained clearly, please help me to remove the extra "data" field.
I prefer to use JSON action helper to post data - like this:
// in controller
$this->_helper->json($dataToSend);
It will remove layout, disable view rendering and send proper headers.
Edit: You can also assign a variable to the view that has the key you desire - eg:
$this->view->reviews = $data;
It will remove the "data" from JSON you don't want...
You can not remove the data field if Zend does not provide a configuration for that. But you can look into that view's code and try either inheriting from it and changing functionality or writing you own view, such that it JSONifies data object itself.
Other way is to put all of your data attributes in the model directly instead of data object. But then there must be some kind of error object inside your model that would conflict.
Related
I am retrieving a single row of data from several joined tabled using first(), this includes a json column called properties. I am able to display all the non json data as expected in my blade template.
However for the json column called properties I am pulling my hair out, spend endless hours googling, looking on her but to no avail.
Appreciate if someone could point out the blindingly obvious (as I'm sure it will be)
I have tried also and reached a point where I can access anything in the root of the object but nothing that is nested.
So pretty version of dd($quote->properties) returns;
"{
"mode": 1,
"service": 1,
"rates": {
"DAP": 825.22
},
"detail": {
"weights": {
"actual": 111.00,
"volume": 0,
"chargeable": 111.00
}
}
}"
I Appreciate the leading and trailing "s are only added to render in the browser and don't exist in the actual column.
Using {{ json_decode($quote->properties,true)['mode'] }}
Result = 1 which is as desired output.
However {{ json_decode($quote->properties,true)['rates']['DAP'] }}
Result = Undefined index: DAP
Desired = 825.22
{{ var_dump(json_decode($quote->properties,true)) }}
array (size=4)
'mode' => int 1
'service' => int 1
'rates' =>
array (size=1)
'DAP' => float 825.22
'detail' =>
array (size=1)
'weights' =>
array (size=3)
'actual' => string '111.00' (length=6)
'volume' => int 0
'chargeable' => string '111.00' (length=6)
Thanks all, I have no idea why working....
Perhaps I had a typo and re-adding fixed or cleared view cache??
Thank you all for responding.
I'm trying to make a classified text, and I'm having problem turning
(class1 (subclass1) (subclass2 item1 item2))
To
(class1 (subclass1 item1) (subclass2 item1 item2))
I have no idea to turn text above to below one, without caching subclass1 in memory. I'm using Perl on Linux, so any solution using shell script or Perl is welcome.
Edit: I've tried using grep, saving whole subclass1 in a variable, then modify and exporting it to the list; but the list may get larger and that way will use a lot of memory.
I have no idea to turn text above to below one
The general approach:
Parse the text.
You appear to have lists of space-separated lists and atoms. If so, the result could look like the following:
{
type => 'list',
value => [
{
type => 'atom',
value => 'class1',
},
{
type => 'list',
value => [
{
type => 'atom',
value => 'subclass1',
},
]
},
{
type => 'list',
value => [
{
type => 'atom',
value => 'subclass2',
},
{
type => 'atom',
value => 'item1',
},
{
type => 'atom',
value => 'item2',
},
],
}
],
}
It's possible that something far simpler could be generated, but you were light on details about the format.
Extract the necessary information from the tree.
You were light on details about the data format, but it could be as simple as the following if the above data structure was created by the parser:
my $item = $tree->{value}[2]{value}[1]{value};
Perform the required modifications.
You were light on details about the data format, but it could be as simple as the following if the above data structure was created by the parser:
my $new_atom = { type => 'atom', value => $item };
push #{ $tree->{value}[1]{value} }, $new_atom;
Serialize the data structure.
For the above data structure, you could use the following:
sub serialize {
my ($node) = #_;
return $node->{type} eq 'list'
? "(".join(" ", map { serialize($_) } #{ $node->{value} }).")"
: $node->{value};
}
Other approaches could be available depending on the specifics.
I've got a working Mongo query that I need to translate into Ruby:
var reducer = function(current, result){
result.loginsCount++;
result.lastLoginTs = Math.max(result.lastLoginTs, current.timeStamp);
}
var finalizer = function(result){
result.lastLoginDate = new Date(result.lastLoginTs).toISOString().split('T')[0];
}
db.audit_log.group({
key : {user : true},
cond : {events : { $elemMatch : { action : 'LOGIN_SUCCESS'}}},
initial : {lastLoginTs : -1, loginsCount : 0},
reduce : reducer,
finalize : finalizer
})
I'm hitting several sticking points getting this to work in Ruby. I'm not really all that familiar with Mongo, and I'm not sure what to pass as arguments to the method calls. This is my best guess, after connecting to the database and a collection called audit_log:
audit_log.group({
"key" => {"user" => "true"},
"cond" => {"events" => { "$elemMatch" => { "action" => "LOGIN_SUCCESS"}}},
"initial" => {"lastLoginTs" => -1, "loginsCount" => 0},
"reduce" => "function(current, result){result.loginsCount += 1}",
"finalize" => "function(result){ result.lastLoginDate = new Date(result.lastLoginTs).toISOString().split('T')[0]; }
})
Or something like that. I've tried using a simpler aggregate operation using the Mongo docs, but I couldn't get that working, either. I was only able to get really simple queries to return results. Are those keys (key, cond, initial, etc.) even necessary, or is that only for JavaScript?
This is how the function finally took shape using the 1.10.0 Mongo gem:
#db.collection("audit_log").group(
[:user, :events],
{'events' => { '$elemMatch' => { 'action' => 'LOGIN_SUCCESS' }}},
{ 'lastLoginTs' => -1, 'loginsCount' => 0 },
"function(current, result){ result.loginsCount++; result.lastLoginTs = Math.max(result.lastLoginTs, current.timeStamp);}",
"function(result){ result.lastLoginDate = new Date(result.lastLoginTs).toISOString().split('T')[0];}"
)
With the Mongo Driver, you leave off the keys: "key", "cond", "initial", "reduce", "finalize" and simply pass in the respective values.
I've linked to two approaches taken by other SO users here and here.
I use Mandrill plugin for Codeigniter.
I created HTML template through Mandrill account, named fess1 with merge tag FNAME, after I published it.
Example:
...
<p>
<span>Hi *|FNAME|*,<br></span>
</p>
....
Now I try to send mail from codeigniter like:
private function sendMailMandrill($owner_name,$business_name,$owner_email){
$message = array('dest_mail' => $owner_email);
$message['to'] = array(array('email' => 'mim#wefi.com'));
$mergeVars[] = array(
'rcpt' => array(array('email' => 'mim#wefi.com')),
'vars' => array(
array(
'name' => 'FNAME',
'content' => 'Fessy'
)
)
);
$message['merge'] = true;
$template_name = 'fess1';
$template_content = array( // I don't know what I need to provide here, left it empty
array(
'name' => 'example name',
'content' => 'example content'
)
);
$message['merge_vars'] = $mergeVars;
return $this->mandrill->messages_send_template($template_name, $template_content, $message);
}
The result:
I get the mail, based on fess1 template, but with the tag *|FNAME|*.
Sounds like Mandrill didn't recognize the merge tag.
I used mandrill->messages_send_template but since my template stored into Mandrill account I have no clue what I need to provide for $template_content.
So I wrote dummy info there.
Did I miss something?
Thank you,
[EDIT]
From logs this is what I send:
{
"template_name": "fess1",
"template_content": [
{
"name": "example name",
"content": "example content"
}
],
"message": {
"owner_name": "עידו",
"business_name": "פלאפל מוסקו",
"dest_mail": "maxim#wifi.com",
"to": [
{
"email": "maxim#wifi.com"
}
],
"merge": "true",
"merge_vars": [
{
"rcpt": [
{
"email": "maxim#wifi.com"
}
],
"vars": [
{
"name": "FNAME",
"content": "Fessy"
}
]
}
]
},
"key": "xxxxxxxxxxxxxxxx"
}
You can provide blank information for the template_content parameter. That parameter allows you to use mc:edit regions in your template. It is a required parameter, but a blank array will suffice if all of the content is in your template in Mandrill.
As for whether the merge_vars were recognized, the first thing we recommend is inspecting the API Logs for your account (Settings > API Logs) since that will show you the JSON that Mandrill received. You can then compare that to the expected JSON format from the Mandrill API docs: https://mandrillapp.com/api/docs/messages.JSON.html#method=send-template
It looks like your arrays may not be nested as expected. Once you view the JSON that's being generated as compared with the expected format, you can also view the PHP documentation for the Mandrill PHP client. It may not be identical to the CodeIgniter plugin, but should give you an idea of how the merge_vars parameter would be structured in PHP: https://mandrillapp.com/api/docs/messages.php.html
In mergeVars you created array instead key:value. Change it to:
'rcpt' => 'mim#wefi.com',
When I was developing in Laravel4 Beta3, I used to get JSON POST data from a service using Input::json() function, But when I updated to Laravel4 Beta4, I am getting following error:
Notice: Undefined property: Symfony\Component\HttpFoundation\ParameterBag::$productName in /Applications/MAMP/htdocs/commonDBAPI/app/controllers/UserController.php line 47
Does any one have any idea, what could be the reason.
Thanks,
You can access just the JSON using Input::json()->all().
JSON input is also merged into Input::all() (and Input::get('key', 'default')) so you can use the same interface to get Query string data, Form data and a JSON payload.
The documentation does not yet reflect all changes because Laravel 4 is still in beta and the focus is on getting the code right, the documentation will be updated ready for the public release.
How is JSON merged with Input::all()?
Consider the following JSON:
{
'name': 'Phill Sparks',
'location': 'England',
'skills': [
'PHP',
'MySQL',
'Laravel'
],
'jobs': [
{
'org': 'Laravel',
'role': 'Quality Team',
'since': 2012
}
]
}
When merged into Laravel's input the JSON is decoded, and the top-level keys become top-level keys in the input. For example:
Input::get('name'); // string
Input::get('skills'); // array
Input::get('jobs.0'); // object
Input::all(); // Full structure of JSON, plus other input
Yup they changed it to return a ParameterBag object switch your code to Input::json()->all()
For :
{
"name":"Olivier",
"title":"Just a try"
}
Try this :
$input = Input::json()->all();
return $input['name'];