multiple JSON object response - php
I have a situation where i have a drop down in php file 'A'.and when i select a value from that drop down an ajax call is made and a different php file B is triggered.
In that file,i do db fetch,and form two json objects.these two json objects are required for me to draw 2 different data tables and 2 different charts.
when i echo one json object in 'B' i get that as a response to ajax call in 'A'
I cant even get a response if i echo two json objects in B.
for a single json object response,i can draw datatable and can manipulate json object with javascript and hopefully draw chart
Please advise how to handle this situation
Code from file B
$json = json_encode($tot_categ);
$json_percent = json_encode($tot_que_percent);
$cols_percent = array(
array( 'id' => 't', 'label' => 'Title', 'type' => 'string'),
array( 'id' => 'n', 'label' => 'Neutral(+) ', 'type' => 'string'),
array('id' => 'a', 'label' => 'Agree', 'type' => 'string'),
array('id' => 'ne', 'label' => 'Neutral(-)', 'type' => 'string'),
array('id' => 'd', 'label' => 'Disagree', 'type' => 'string'),
);
$jcols_percent = json_encode($cols_percent);
//JSON format accepted by Google tables
$r_percent= "{cols:".$jcols_percent.','."rows:".$json_percent."}";
//echo (JSON.stringify($r_percent));
// echo $r_percent;
$cols = array(
array( 'id' => 't', 'label' => 'Title', 'type' => 'string'),
array( 'id' => 'l', 'label' => 'Avg ', 'type' => 'string'),
array('id' => 'lb', 'label' => 'High', 'type' => 'string'),
array('id' => 'lo', 'label' => 'Low', 'type' => 'string')
);
$jcols = json_encode($cols);
//JSON format accepted by Google tables
$r = "{cols:".$jcols.','."rows:".$json."}";
//echo(json_decode($r));
echo $r;
$r and $r_percent are my objects
$r_percent when echoed gives
{cols:[{"id":"t","label":"Title","type":"string"},{"id":"n","label":"Neutral(+) ","type":"string"},{"id":"a","label":"Agree","type":"string"},{"id":"ne","label":"Neutral(-)","type":"string"},{"id":"d","label":"Disagree","type":"string"}],rows:[{"c":[{"v":"165q"},{"v":0},{"v":0},{"v":0},{"v":100}]},{"c":[{"v":"160q"},{"v":0},{"v":0},{"v":0},{"v":6}]},{"c":[{"v":"161q"},{"v":0},{"v":0},{"v":0},{"v":10}]},{"c":[{"v":"162q"},{"v":7},{"v":0},{"v":7},{"v":0}]},{"c":[{"v":"163q"},{"v":0},{"v":25},{"v":0},{"v":0}]},{"c":[{"v":"164q"},{"v":0},{"v":100},{"v":0},{"v":0}]}]}
$r when echoed gives
{cols:[{"id":"t","label":"Title","type":"string"},{"id":"l","label":"Avg ","type":"string"},{"id":"lb","label":"High","type":"string"},{"id":"lo","label":"Low","type":"string"}],rows:[{"c":[{"v":"165q"},{"v":1.3333333333333},{"v":"2"},{"v":"1"}]},{"c":[{"v":"160q"},{"v":6},{"v":"10"},{"v":"1"}]},{"c":[{"v":"161q"},{"v":6.6666666666667},{"v":"9"},{"v":"2"}]},{"c":[{"v":"162q"},{"v":7},{"v":"9"},{"v":"3"}]},{"c":[{"v":"163q"},{"v":8},{"v":"9"},{"v":"6"}]},{"c":[{"v":"164q"},{"v":5},{"v":"5"},{"v":"5"}]}]}
when combined
$result = array('objA' => $r_percent, 'objB' => $r );
echo json_encode($result);
updated echoing
{"objA":"{cols:[{\"id\":\"t\",\"label\":\"Title\",\"type\":\"string\"},{\"id\":\"n\",\"label\":\"Neutral(+) \",\"type\":\"string\"},{\"id\":\"a\",\"label\":\"Agree\",\"type\":\"string\"},{\"id\":\"ne\",\"label\":\"Neutral(-)\",\"type\":\"string\"},{\"id\":\"d\",\"label\":\"Disagree\",\"type\":\"string\"}],rows:[{\"c\":[{\"v\":\"165q\"},{\"v\":0},{\"v\":0},{\"v\":0},{\"v\":100}]},{\"c\":[{\"v\":\"160q\"},{\"v\":0},{\"v\":0},{\"v\":0},{\"v\":6}]},{\"c\":[{\"v\":\"161q\"},{\"v\":0},{\"v\":0},{\"v\":0},{\"v\":10}]},{\"c\":[{\"v\":\"162q\"},{\"v\":7},{\"v\":0},{\"v\":7},{\"v\":0}]},{\"c\":[{\"v\":\"163q\"},{\"v\":0},{\"v\":25},{\"v\":0},{\"v\":0}]},{\"c\":[{\"v\":\"164q\"},{\"v\":0},{\"v\":100},{\"v\":0},{\"v\":0}]}]}","objB":"{cols:[{\"id\":\"t\",\"label\":\"Title\",\"type\":\"string\"},{\"id\":\"l\",\"label\":\"Avg \",\"type\":\"string\"},{\"id\":\"lb\",\"label\":\"High\",\"type\":\"string\"},{\"id\":\"lo\",\"label\":\"Low\",\"type\":\"string\"}],rows:[{\"c\":[{\"v\":\"165q\"},{\"v\":1.3333333333333},{\"v\":\"2\"},{\"v\":\"1\"}]},{\"c\":[{\"v\":\"160q\"},{\"v\":6},{\"v\":\"10\"},{\"v\":\"1\"}]},{\"c\":[{\"v\":\"161q\"},{\"v\":6.6666666666667},{\"v\":\"9\"},{\"v\":\"2\"}]},{\"c\":[{\"v\":\"162q\"},{\"v\":7},{\"v\":\"9\"},{\"v\":\"3\"}]},{\"c\":[{\"v\":\"163q\"},{\"v\":8},{\"v\":\"9\"},{\"v\":\"6\"}]},{\"c\":[{\"v\":\"164q\"},{\"v\":5},{\"v\":\"5\"},{\"v\":\"5\"}]}]}"}
Combine both responses in a single object, return that object and use both parts separately again:
PHP side:
$result = array( 'objA' => $objA, 'objB' => $objB );
echo json_encode( $result );
Client side:
// your success callback handler
function handler( data ) {
// execute code for object A
doStuff( data.objA );
// execute code for object B
doOtherStuff( data.objB );
}
Related
How to insert/retrieve images from a record in sugarcrm using REST API
How to insert and retrieve images from a record in suitecrm. I use the following procedure, but no images gets uploaded. I see no_image in the detail view. $contents = file_get_contents('1436568236500.jpg'); $set_entry_list_parameters = array( 'session' => $login_result->id, 'module_name' => 'WBUR_Vehicle', 'name_value_list' => array( array( 'name' => 'id', 'value' => '376e1f17-d797-b629-92cc-558f28228524' ), array( 'name' => 'front_left_image_c', 'value' => base64_encode($contents) ) ) ); $get_entry_list_result = call('set_entry', $set_entry_list_parameters, $url); Also, how do I retrieve the images?
Elastica add documents overrides existing ones
When i try to add new documents to an index type , i loose existing documents which are overwritten by the new added ones . The problem can be related to the id of each added document ?? Here is the code : $elasticaClient = new \Elastica\Client(array( 'host' => $this->container->getParameter('elastic_host'), 'port' => $this->container->getParameter('elastic_port') )); $elasticaIndex = $elasticaClient->getIndex('app'); $elasticaIndex->create( array( 'number_of_shards' => 4, 'number_of_replicas' => 1, 'analysis' => array( 'analyzer' => array( 'indexAnalyzer' => array( 'type' => 'custom', 'tokenizer' => 'standard', 'filter' => array('lowercase', 'mySnowball') ), 'searchAnalyzer' => array( 'type' => 'custom', 'tokenizer' => 'standard', 'filter' => array('standard', 'lowercase', 'mySnowball') ) ), 'filter' => array( 'mySnowball' => array( 'type' => 'snowball', 'language' => 'German' ) ) ) ), true ); $elasticaType = $elasticaIndex->getType('type'); $mapping = new \Elastica\Type\Mapping(); $mapping->setType($elasticaType); $mapping->setParam('index_analyzer', 'indexAnalyzer'); $mapping->setParam('search_analyzer', 'searchAnalyzer'); $mapping->setProperties(array( 'id' => array('type' => 'string'), 'title' => array('type' => 'string'), 'duration' => array('type' => 'string'), 'start' => array('type' => 'string'), 'end' => array('type' => 'string'), )); // Send mapping to type $mapping->send(); $documents = array(); foreach($medias as $media) { $id = uniqid() ; $documents[] = new \Elastica\Document( $id, array( 'id' => $id, 'title' => $media['title'], 'duration' => $media['duration'], 'start' => $media['start'], 'end' => $media['end'], ) ); } $elasticaType->addDocuments($documents); $elasticaType->getIndex()->refresh(); Please i need your help . Thank you
PHP does not recommend using uniqid for this use case. Since you are wanting a random, safe id, let Elasticsearch do it for you. The Elastica Document construct method notes that the id field is optional. So don't pass it and let Elasticsearch issue the id.
Several things $elasticaIndex->create (....) you only have to enter it once. Index is unique after creating the index that you can comment or generate a different index and other things. I leave an example that works. class PersistencyElastic { private $conection; public function __construct() { $this->conection = new \Elastica\Client(['host' => '127.0.0.1', 'port' => 9200]); } public function save($ msg) { // $ msg is an array with whatever you want inside $index = $this->conection->getIndex('googlephotos'); // This is the index I created, it's called googlephotos // $index->create(array (), true); $type = $index->getType('googlephotos'); $type->addDocument(new Document (uniqid ('id _', false), $msg, $type, $index)); $index->refresh(); } }
Basic looping with php to build json
I'm querying the instagram api to return json with this code: $instagramClientID = '9110e8c268384cb79901a96e3a16f588'; $api = 'https://api.instagram.com/v1/tags/zipcar/media/recent?client_id='.$instagramClientID; //api request (edit this to reflect tags) $response = get_curl($api); //change request path to pull different photos So I want to decode the json if($response){ // Decode the response and build an array foreach(json_decode($response)->data as $item){ ... So now I want to reformat the contents of said array into a particular json format (geojson) the code would be roughly this: array( 'type' => 'FeatureCollection', 'features' => array( array( 'type' => 'Feature', 'geometry' => array( 'coordinates' => array(-94.34885, 39.35757), 'type' => 'Point' ), // geometry 'properties' => array( // latitude, longitude, id etc. ) // properties ), // end of first feature array( ... ), // etc. ) // features ) And then use json_encode to return it all into a nice json file to cache on the server. My question...is how to I use the code above to loop through the json? The outer structure of the array/json is static but the interior needs to change.
In this case it's better to build a new data structure instead of replacing the existing one inline. Example: <?php $instagrams = json_decode($response)->data; $features = array(); foreach ( $instagrams as $instagram ) { if ( !$instagram->location ) { // Images aren't required to have a location and this one doesn't have one // Now what? continue; // Skip? } $features[] = array( 'type' => 'Feature', 'geometry' => array( 'coordinates' => array( $instagram->location->longitude, $instagram->location->latitude ), 'type' => 'Point' ), 'properties' => array( 'longitude' => $instagram->location->longitude, 'latitude' => $instagram->location->latitude, // Don't know where title comes from 'title' => null, 'user' => $instagram->user->username, // No idea where id comes from since instagram's id seems to belong in instagram_id 'id' => null, 'image' => $instagram->images->standard_resolution->url, // Assuming description maps to caption 'description' => $instagram->caption ? $instagram->caption->text : null, 'instagram_id' => $instagram->id, ) ); } $results = array( 'type' => 'FeatureCollection', 'features' => $features, ); print_r($results);
How do I save custom node types in Drupal 7
I've created a custom node type in Drupal 7, using the hook_node_info method in the install file: // declare the new node type function foo_node_info ( ) { return array( 'foo' => array( 'name' => t('Foo entry'), 'base' => 'node_content', 'description' => t('For use to store foo entries.'), )); } // END function foo_node_info and I'm trying to save that type in the module file using the following code: // INSERT the stuff node_save(node_submit((object)array( 'type' => 'foo', 'is_new' => true, 'uid' => 1, 'title' => 'Title, blah blah blah', 'url' => 'url here, just pretend', 'body' => '<p>test</p>', ))); My issue, is that the url, and body fields aren't saving. Any idea what I'm doing wrong?
So, after a ton of digging, it turns out that the way I was entering the custom fields in the node_save was wrong. The node_save needs to look like the following: node_save(node_submit((object)array( 'type' => 'foo', 'is_new' => true, 'uid' => 1, 'title' => 'the title', 'url' => array( 'und' => array(array( 'summary' => '', 'value' => 'url value', 'format' => 2, ))), 'body' => array( 'und' => array(array( 'summary' => '', 'value' => 'the body goes here', 'format' => 2, ))), ))); Notice that for the custom fields, the array structure has to match what was previously going on with CCK (pretty much exactly). The first key in the array describing the field value is the language for the content. I've used 'und' here only because that's what I saw going into the database when entering the data through a form.
Drupal: How to Render Results of Form on Same Page as Form
How would I print the results of a form submission on the same page as the form itself? Relevant hook_menu: $items['admin/content/ncbi_subsites/paths'] = array( 'title' => 'Paths', 'description' => 'Paths for a particular subsite', 'page callback' => 'ncbi_subsites_show_path_page', 'access arguments' => array( 'administer site configuration' ), 'type' => MENU_LOCAL_TASK, ); page callback: function ncbi_subsites_show_path_page() { $f = drupal_get_form('_ncbi_subsites_show_paths_form'); return $f; } Form building function: function _ncbi_subsites_show_paths_form() { // bunch of code here $form['subsite'] = array( '#title' => t('Subsites'), '#type' => 'select', '#description' => 'Choose a subsite to get its paths', '#default_value' => 'Choose a subsite', '#options'=> $tmp, ); $form['showthem'] = array( '#type' => 'submit', '#value' => 'Show paths', '#submit' => array( 'ncbi_subsites_show_paths_submit'), ); return $form; } Submit function (skipped validate function for brevity) function ncbi_subsites_show_paths_submit( &$form, &$form_state ) { //dpm ( $form_state ); $subsite_name = $form_state['values']['subsite']; $subsite = new Subsite( $subsite_name ); //y own class that I use internally in this module $paths = $subsite->normalized_paths; // build list $list = theme_item_list( $paths ); } If I print that $list variable, it is exactly what I want, but I am not sure how to get it into the page with the original form page built from 'ncbi_subsites_show_path_page'. Any help is much appreciated!
The key information in the link Nikit posted is $form_state['rebuild']. Here's some info from Drupal 7 documentation that I believe applies the same for Drupal 6... $form_state['rebuild']: Normally, after the entire form processing is completed and submit handlers ran, a form is considered to be done and drupal_redirect_form() will redirect the user to a new page using a GET request (so a browser refresh does not re-submit the form). However, if 'rebuild' has been set to TRUE, then a new copy of the form is immediately built and sent to the browser; instead of a redirect. This is used for multi-step forms, such as wizards and confirmation forms. Also, if a form validation handler has set 'rebuild' to TRUE and a validation error occurred, then the form is rebuilt prior to being returned, enabling form elements to be altered, as appropriate to the particular validation error.
This is a full working example of a page and a list on the same page <?php /* * Implements hook_mennu() */ function test_menu() { $items['test'] = array( 'title' => t('Test'), 'page callback' => 'test_search_page', 'access callback' => True, ); return $items; } function test_search_page(){ $form = drupal_get_form('test_search_form'); return $form; } function test_search_form($form, &$form_state){ $header = array(t('id'), t('name'), t('firstname')); $rows = Null; $form['name'] = array( '#type' => 'textfield', '#title' => t('Name'), '#required' => True, '#default_value' => isset($_GET['name']) ? $_GET['name'] : Null ); $form['submit'] = array( '#type' => 'submit', '#value' => t('submit'), ); if (isset($_GET['name'])){ $rows = get_data(); } $form['table'] = array( '#theme' => 'table', '#header' => $header, '#rows' => $rows, '#empty' => t('Aucun résultat.') ); $form['pager'] = array('#markup' => theme('pager')); /* if (isset($form_state['table'])) { $form['table'] = $form_state['table']; } $form['pager'] = array('#markup' => theme('pager')); */ return $form; } function test_search_form_submit($form, &$form_state){ $form_state['redirect'] = array( // $path 'test', // $options array('query' => array('name' => $form_state['values']['name'])), // $http_response_code 302, ); } //$header = array(t('id'), t('name'), t('firstname')); function get_data(){ $data = array( 0 => array( 'id' => '0', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ), 1 => array( 'id' => '1', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ), 2 => array( 'id' => '2', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ), 3 => array( 'id' => '3', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ), 4 => array( 'id' => '4', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ), 5 => array( 'id' => '5', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ), 6 => array( 'id' => '6', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ), 7 => array( 'id' => '7', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ), 8 => array( 'id' => '8', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ), 9 => array( 'id' => '9', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ), 10 => array( 'id' => '10', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ), 11 => array( 'id' => '11', 'name' => 'pokpokpok', 'firstname' => 'pokpokpok', ) ); $paging = pager_array_splice($data, 2); return $paging; } /* $header = array(t('id'), t('name'), t('firstname')); $form_state['table'] = array( '#theme' => 'table', '#header' => $header, '#rows' => $paging, '#empty' => t('Aucun r?sultat.') ); $form_state['rebuild'] = True;*/ function pager_array_splice($data, $limit = 9, $element = 0) { global $pager_page_array, $pager_total, $pager_total_items; $page = isset($_GET['page']) ? $_GET['page'] : ''; // Convert comma-separated $page to an array, used by other functions. $pager_page_array = explode(',', $page); // We calculate the total of pages as ceil(items / limit). $pager_total_items[$element] = count($data); $pager_total[$element] = ceil($pager_total_items[$element] / $limit); $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1)); return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE); }
Drupal6 node.module and dblog.module do this for admin/content/node and admin/reports/dblog by providing a page callback which includes the rendered form in its output. modules/dblog/dblog.admin.inc dblog_overview() modules/node/node.admin.inc node_admin_nodes() In form submit, updated filter settings are stored in $_SESSION. In the page callback it renders the results based on the filter settings stored in $_SESSION. $_SESSION is just another global here (albeit a persistent one).
For Drupal7 I find that if you use $form_state['rebuild'], then the form variables can be best accessed from the PHP super-global variable $_POST (or $_REQUEST). However, if you use $form_state['redirect'], the solution with $_SESSION is better (instead of using $_GET or $_REQUEST). I find this issue quite tricky even for experts. Maybe Drupal has some more easy and intuitive way that we don't know.
For Drupal 8, if you have a form implementing FormBase I found I needed to set the form to be rebuilt to allow using the form state during render of the form after a successful form submission: public function submitForm(array &$form, FormStateInterface $form_state) { $form_state->setRebuild(TRUE); } By default, the form will submit and process the form, then redirect, then build the form again and at that point you don't have the form state (unless you've passed the form state as part of a query parameter in the redirect).