PHP.SU

Программирование на PHP, MySQL и другие веб-технологии
PHP.SU Портал     На главную страницу форума Главная     Помощь Помощь     Поиск Поиск     Поиск Яндекс Поиск Яндекс     Вакансии  Пользователи Пользователи

Страниц (2): [1] 2 »

> Найдено сообщений: 21
eboome Отправлено: 17 Сентября, 2014 - 13:30:53 • Тема: как вытащить графики с Google Analytics • Форум: Графика в PHP

Ответов: 1
Просмотров: 1104
использовал вот это https://ga-dev-tools[dot]appspot[dot]com[dot][dot][dot]demos/embed-api/ всё отлично
eboome Отправлено: 15 Сентября, 2014 - 22:32:47 • Тема: как вытащить графики с Google Analytics • Форум: Графика в PHP

Ответов: 1
Просмотров: 1104
Скажите, пожалуста, ка можно добавить на страницу графики из Google Analytics. Код отслеживания уже установлен на сайте. Пробовал GaDash 1.0 но постоянно ошибка login required!
eboome Отправлено: 15 Сентября, 2014 - 13:33:38 • Тема: Google analytics. ошибка google is not defined • Форум: JavaScript & VBScript

Ответов: 1
Просмотров: 1912
здраствуйте! Хочу прикрутись Аналитику к сайту в админке. Использую GAdash 1.0.
вот моя ХТМЛ:
CODE (html):
скопировать код в буфер обмена
  1.  
  2. <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  3.     <script src="https://apis.google.com/js/client.js?onload=gadashInit"></script>
  4.    
  5.    
  6.     <script language="javascript" type="text/javascript" src="http://mysite.com/templates/tmpl_hopelife/js/gadash-1.0.js"></script>
  7.    
  8.    <!-- Add Google Analytics authorization button -->
  9.   <button id="authorize-button" style="visibility: hidden">
  10.         Authorize Analytics</button>
  11.   <!-- Div element where the Line Chart will be placed -->
  12.   <div id='line-chart-example'></div>
  13.    <script>
  14.     // Configure these parameters before you start.
  15.     var API_KEY = ****************************';
  16.     var CLIENT_ID = '*******************************';
  17.     var TABLE_ID = '************';
  18.     // Format of table ID is ga:xxx where xxx is the profile ID.
  19.     gadash.configKeys({
  20.       'apiKey': API_KEY,
  21.       'clientId': CLIENT_ID
  22.     });
  23.     // Create a new Chart that queries visitors for the last 30 days and plots
  24.     // visualizes in a line chart.
  25.     var chart1 = new gadash.Chart({
  26.       'type': 'LineChart',
  27.       'divContainer': 'line-chart-example',
  28.       'last-n-days':30,
  29.       'query': {
  30.         'ids': TABLE_ID,
  31.         'metrics': 'ga:visitors',
  32.         'dimensions': 'ga:date'
  33.       },
  34.       'chartOptions': {
  35.         height:600,
  36.         title: 'Visits',
  37.         hAxis: {title:'Date'},
  38.         vAxis: {title:'Visits'},
  39.         curveType: 'function'
  40.       }
  41.     }).render();
  42.   </script>


вот GAdash 1.0 скачан с сервера Гугла:
CODE (javascript):
скопировать код в буфер обмена
  1.  
  2. // Copyright 2012 Google Inc. All Rights Reserved.
  3.  
  4. /* Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  * http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16.  
  17. /**
  18.  * @author
  19.  * Shan Aminzadeh, shan.aminzadeh@gmail.com
  20.  * Arya Bondarian, aryabond@gmail.com
  21.  * Albert Gau, agau@uci.edu
  22.  * Travis Lai, travisrlai@gmail.com
  23.  * Daniel Nguyen, danielnuwin@gmail.com
  24.  * Nick Mihailovski, api.nickm@gmail.com
  25.  *
  26.  * @fileoverview
  27.  * This library is designed to create an easier way to build a custom
  28.  * Google Analytics Dashboard by visualizing data from Google Analytics
  29.  * API with the Google Chart Tools.
  30.  */
  31.  
  32.  
  33. // Loads the core chart and table from the Google Visualization.
  34. google.load('visualization', '1', {'packages': ['corechart', 'table']});
  35.  
  36.  
  37. // Create namespace for this library if not already created.
  38. var gadash = gadash || {};
  39.  
  40.  
  41. // Namespace for util object. Contains lots of library utilities.
  42. gadash.util = gadash.util || {};
  43.  
  44. // Boolean that checks to see if gapi client is loaded.
  45. gadash.isLoaded = false;
  46.  
  47. /**
  48.  * Refers to the Google Analytics API scope that the user will need
  49.  * authentication for.
  50.  * @const {String}
  51.  */
  52. gadash.SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';
  53.  
  54.  
  55. /**
  56.  * List of functions that are queued for execution. This is only used
  57.  * until all the libraries have fully loaded.
  58.  * @type {Array}
  59.  */
  60. gadash.commandQueue = [];
  61.  
  62.  
  63. /**
  64.  * Callback executed once the Google APIs Javascript client library has loaded.
  65.  * The function name is specified in the onload query parameter of URL to load
  66.  * this library. After 1 millisecond, checkAuth is called.
  67.  */
  68. window.gadashInit = function() {
  69.   gapi.client.setApiKey(gadash.apiKey);
  70.   window.setTimeout(gadash.checkAuth, 1);
  71. };
  72.  
  73.  
  74. /**
  75.  * Sets the API key and Client ID passed by the user.
  76.  * This information can be found in your Google API Console.
  77.  * @param {Object} settings - Contains the API Key and Client ID variables.
  78.  */
  79. gadash.configKeys = function(settings) {
  80.   gadash.apiKey = settings.apiKey;
  81.   gadash.clientId = settings.clientId;
  82. };
  83.  
  84.  
  85. /**
  86.  * Uses the OAuth2.0 clientId to query the Google Accounts service
  87.  * to see if the user has authorized. Once complete, handleAuthResults is
  88.  * called.
  89.  */
  90. gadash.checkAuth = function() {
  91.   gapi.auth.authorize({
  92.     client_id: gadash.clientId,
  93.     scope: gadash.SCOPE,
  94.     immediate: true}, gadash.handleAuthResult);
  95. };
  96.  
  97.  
  98. /**
  99.  * Handler that is called once the script has checked to see if the user has
  100.  * authorized access to their Google Analytics data. If the user has authorized
  101.  * access, the analytics api library is loaded and the handleAuthorized
  102.  * function is executed. If the user has not authorized access to their data,
  103.  * the handleUnauthorized function is executed.
  104.  * @param {Object} authResult The result object returned form the authorization
  105.  *     service that determine whether the user has currently authorized access
  106.  *     to their data. If it exists, the user has authorized access.
  107.  */
  108. gadash.handleAuthResult = function(authResult) {
  109.   if (authResult) {
  110.     gapi.client.setApiVersions({'analytics': 'v3'});
  111.     gapi.client.load('analytics', 'v3', gadash.handleAuthorized);
  112.   } else {
  113.     gadash.handleUnAuthorized();
  114.   }
  115. };
  116.  
  117.  
  118. /**
  119.  * Updates the UI once the user has authorized this script to access their
  120.  * data by hiding the authorize button. Also, runs executeCommandQueue
  121.  * function to render all charts in the commandQueue. The execution of the
  122.  * command queue only happens once.
  123.  */
  124. gadash.handleAuthorized = function() {
  125.   var authorizeButton = document.getElementById('authorize-button');
  126.   authorizeButton.style.visibility = 'hidden';
  127.  
  128.   gadash.isLoaded = true;
  129.   gadash.executeCommandQueue();
  130. };
  131.  
  132.  
  133. /**
  134.  * Updates the UI if a user has not yet authorized this script to access
  135.  * their Google Analytics data. This function changes the visibility of
  136.  * some elements on the screen. It also adds the handleAuthClick
  137.  * click handler to the authorize-button.
  138.  */
  139. gadash.handleUnAuthorized = function() {
  140.   var authorizeButton = document.getElementById('authorize-button');
  141.   authorizeButton.style.visibility = '';
  142.   authorizeButton.onclick = gadash.handleAuthClick;
  143. };
  144.  
  145.  
  146. /**
  147.  * Checks to see if user is authenticated, calls handleAuthResult
  148.  * @return {boolean} false.
  149.  * @param {Object} event - event when button is clicked.
  150.  */
  151. gadash.handleAuthClick = function(event) {
  152.   gapi.auth.authorize({
  153.     client_id: gadash.clientId,
  154.     scope: gadash.SCOPE,
  155.     immediate: false}, gadash.handleAuthResult);
  156.   return false;
  157. };
  158.  
  159.  
  160. /**
  161.  * Iterates through all commands on the commandQueue and executes them.
  162.  */
  163. gadash.executeCommandQueue = function() {
  164.   for (var i = 0, command; command = gadash.commandQueue[i]; ++i) {
  165.     command();
  166.   }
  167. };
  168.  
  169.  
  170. /**
  171.  * A Chart object is the primary object in this library.
  172.  * A Chart accepts an optional configuration object that contains all the
  173.  * parameters of the chart. Also changes start and end date of
  174.  * the query, if last-n-days is set in the config.
  175.  * @param {?Object} config - Contains all configuration variables
  176.  *     of a Chart object. This parameter is passed by value, and a deep
  177.  *     copy is made. Once set, the original object can be modified and
  178.  *     it will not affect this object.
  179.  * @return {Object} this Returns a reference to the newly instantiated
  180.  *     Chart instance. Useful for chaining methods together.
  181.  * @constructor
  182.  */
  183. gadash.Chart = function(opt_config) {
  184.   /**
  185.    * The main configuration object.
  186.    * @type {Object}
  187.    */
  188.   this.config = {};
  189.  
  190.   if (opt_config) {
  191.     gadash.util.extend(opt_config, this.config);
  192.   }
  193.  
  194.   return this;
  195. };
  196.  
  197.  
  198. /**
  199.  * Extends the values in the chart's config object with the keys in
  200.  * the config parameters. If a key in config already exists in the chart,
  201.  * and the value is not an object, the new value overwrites the old.
  202.  * @param {Object} config The config object to set inside this object.
  203.  * @return {Object} The current instance of the Chart object. Useful
  204.  *     for chaining methods.
  205.  */
  206. gadash.Chart.prototype.set = function(config) {
  207.   gadash.util.extend(config, this.config);
  208.   return this;
  209. };
  210.  
  211.  
  212. /**
  213.  * First checks to see if the GA library is loaded. If it is then the
  214.  * chart can be rendered right away. Otherwise, other operations are queued,
  215.  * so the render command is pushed to the command queue to be executed in
  216.  * the same order as originally called.
  217.  * @this Points to the current chart instance.
  218.  * @return {Object} The current instance of this chart object. Useful for
  219.  *     chaining methods.
  220.  */
  221. gadash.Chart.prototype.render = function() {
  222.  
  223.   // If the client library has loaded.
  224.   if (gadash.isLoaded) {
  225.     this.renderFunction();
  226.   } else {
  227.     var renderFunction = gadash.util.bindMethod(this, this.renderFunction);
  228.     gadash.commandQueue.push(renderFunction);
  229.   }
  230.  
  231.   return this;
  232. };
  233.  
  234.  
  235. /**
  236.  * Makes a request to the Google Analytics API.
  237.  * Updates the start and end date if last-n-days
  238.  * has been set. The function also creates and executes a Google Analytics
  239.  * API request using the Chart objects callback method. The callback
  240.  * is bound to the Chart instance so a reference back to this chart is
  241.  * maintained within the callback.
  242.  */
  243. gadash.Chart.prototype.renderFunction = function() {
  244.  
  245.   // Update the start and end dates based on last n days.
  246.   if (this.config['last-n-days']) {
  247.     this.config.query['end-date'] = gadash.util.lastNdays(0);
  248.     this.config.query['start-date'] =
  249.         gadash.util.lastNdays(this.config['last-n-days']);
  250.   }
  251.   var request = gapi.client.analytics.data.ga.get(this.config.query);
  252.   request.execute(gadash.util.bindMethod(this, this.callback));
  253. }
  254.  
  255.  
  256.  
  257. /**
  258.  * Callback function that is called after a GA query is executed.
  259.  * First, the function checks to see if there are any errors on the
  260.  * response. Then check to see if a onSuccess function was declared
  261.  * in the config. If present, call onSuccess by first binding it to
  262.  * this (ie this chart object instance). If not defined, just use
  263.  * the default callback. The entire JSON response from the API
  264.  * is passed to either defined or default callback.
  265.  * @param {Object} response - Google Analytics API JSON response.
  266.  */
  267. gadash.Chart.prototype.callback = function(response) {
  268.   if (response.error) {
  269.     this.defaultOnError(response.error.code + ' ' + response.error.message);
  270.   } else {
  271.  
  272.     if (this.config.onSuccess) {
  273.       gadash.util.bindMethod(this, this.config.onSuccess)(response);
  274.     } else {
  275.       this.defaultOnSuccess(response);
  276.     }
  277.   }
  278. };
  279.  
  280.  
  281. /**
  282.  * Checks to see if onError parameter is set in config. If it is,
  283.  * use the user defined error function else check to see if an error
  284.  * div is created. If not, create an error div. Print error message
  285.  * to the error div.
  286.  * @param {String} message - error message to print.
  287.  */
  288. gadash.Chart.prototype.defaultOnError = function(message) {
  289.  
  290.   // If onError param exists, use that as error handling function.
  291.   if (this.config.onError) {
  292.     this.config.onError(message);
  293.   } else {
  294.  
  295.     var errorDiv = document.getElementById('errors');
  296.  
  297.     // Create error div if not already made.
  298.     if (!errorDiv) {
  299.       errorDiv = document.createElement('div');
  300.       errorDiv.style.color = 'red';
  301.       errorDiv.setAttribute('id', 'errors');
  302.       errorDiv.innerHTML = 'ERRORS:' + '<br />';
  303.       document.body.appendChild(errorDiv);
  304.     }
  305.  
  306.     // Prints chart divContainer and message to error div.
  307.     errorDiv.innerHTML += this.config.divContainer + ' error: ' +
  308.         message + '<br />';
  309.   }
  310. };
  311.  
  312.  
  313. /**
  314.  * Default callback for creating Google Charts with a response. First, the
  315.  * response is put into a DataTable object Second, the corresponding chart
  316.  * is returned. The two are then combined to draw a chart that is populated
  317.  * with the GA data.
  318.  * @param {Object} resp - A Google Analytics API JSON response.
  319.  */
  320. gadash.Chart.prototype.defaultOnSuccess = function(resp) {
  321.   var dataTable = gadash.util.getDataTable(resp, this.config.type);
  322.   var chart = gadash.util.getChart(this.config.divContainer, this.config.type);
  323.   gadash.util.draw(chart, dataTable, this.config.chartOptions);
  324. };
  325.  
  326.  
  327. /**
  328.  * Creates a DataTable object using a GA response.
  329.  * @param {Object} resp - A Google Analytics response.
  330.  * @param {?String} opt_chartType - The chart type. Provides a hint on
  331.  *     how to parse the API results into a data table.
  332.  * @return {Object} data - A Google DataTable object populated
  333.  *     with the GA response data.
  334.  */
  335. gadash.util.getDataTable = function(resp, opt_chartType) {
  336.  
  337.   var chartType = opt_chartType || false;
  338.  
  339.   var data = new google.visualization.DataTable();
  340.   var numOfColumns = resp.columnHeaders.length;
  341.   var numOfRows;
  342.  
  343.   // Throw an error if there are no rows returned.
  344.   if (resp.rows && resp.rows.length) {
  345.     numOfRows = resp.rows.length;
  346.   } else {
  347.     this.defaultOnError('No rows returned for that query.');
  348.   }
  349.  
  350.   /*
  351.    * Looks at the resp column headers to set names and types for each column.
  352.    * Since bar and column chart don't support date object, set type as string
  353.    * rather than a Date.
  354.    */
  355.   for (var i = 0; i < numOfColumns; i++) {
  356.     var dataType = resp.columnHeaders[i].dataType;
  357.     var name = resp.columnHeaders[i].name;
  358.  
  359.     if (name == 'ga:date' &&
  360.         !(chartType == 'ColumnChart' || chartType == 'BarChart')) {
  361.  
  362.       dataType = 'date';
  363.     } else if (dataType == 'STRING') {
  364.       dataType = 'string';
  365.     } else {
  366.       dataType = 'number';
  367.     }
  368.     data.addColumn(dataType, gadash.util.formatGAString(name));
  369.   }
  370.  
  371.   /*
  372.    * Populates the rows by using the resp.rows array. If the type
  373.    * is an int then parse the INT. If it is a percent, then round
  374.    * to last two decimal places and store as INT.
  375.    */
  376.   for (var i = 0; i < numOfRows; i++) {
  377.     var arrayMetrics = [];
  378.     for (var j = 0; j < numOfColumns; j++) {
  379.       var name = resp.columnHeaders[j].name;
  380.       var dataType = resp.columnHeaders[j].dataType;
  381.  
  382.       if (name == 'ga:date' &&
  383.           !(chartType == 'ColumnChart' || chartType == 'BarChart')) {
  384.  
  385.         arrayMetrics.push(gadash.util.stringToDate(resp.rows[i][j]));
  386.       } else if (dataType == 'INTEGER') {
  387.         arrayMetrics.push(parseInt(resp.rows[i][j]));
  388.       } else if (dataType == 'CURRENCY' ) {
  389.         arrayMetrics.push(parseFloat(resp.rows[i][j]));
  390.       } else if (dataType == 'PERCENT' || dataType == 'TIME' ||
  391.           dataType == 'FLOAT') {
  392.         arrayMetrics.push(Math.round((resp.rows[i][j]) * 100) / 100);
  393.       } else {
  394.         arrayMetrics.push(resp.rows[i][j]);
  395.       }
  396.     }
  397.     data.addRow(arrayMetrics);
  398.   }
  399.  
  400.   /*
  401.    * Iterates through each column in the data table and formats
  402.    * any column that has a CURRENCY datatype to two decimal places
  403.    * and a '$' before the amount.
  404.    */
  405.   for (var i = 0; i < numOfColumns; i++) {
  406.     var dataType = resp.columnHeaders[i].dataType;
  407.     if (dataType == 'CURRENCY') {
  408.       var formatter = new google.visualization.NumberFormat(
  409.           {fractionDigits: 2});
  410.       formatter.format(data, i);
  411.     }
  412.   }
  413.  
  414.   return data;
  415. };
  416.  
  417.  
  418. /**
  419.  * Checks to see if the type of chart in the config is valid.
  420.  * If it is, get its chart instance, else return a Table instance.
  421.  * @param {String} id The ID of the HTML element in which to render
  422.  *     the chart.
  423.  * @param {String} chartType The type of the Chart to render.
  424.  * @return {Object} visualization - returns the Chart instance.
  425.  */
  426. gadash.util.getChart = function(id, chartType) {
  427.   var elem = document.getElementById(id);
  428.  
  429.   if (google.visualization[chartType]) {
  430.     return new google.visualization[chartType](elem);
  431.   }
  432.  
  433.   return new google.visualization.Table(elem);
  434. };
  435.  
  436.  
  437. /**
  438.  * Draws a chart to its declared div using a DataTable.
  439.  * @param {Object} chart - The Chart instance you wish to draw the data into.
  440.  * @param {Object} dataTable - The Google DataTable object holding
  441.  *     the response data.
  442.  * @param {Object} options - The optional configuration parameters to pass
  443.  *     into the chart.
  444.  */
  445. gadash.util.draw = function(chart, dataTable, chartOptions) {
  446.   chart.draw(dataTable, chartOptions);
  447. };
  448.  
  449.  
  450. /**
  451.  * Binds a method to its object.
  452.  * @param {Object} object The main object to bind to.
  453.  * @param {Object} method The method to bind to the object.
  454.  * @return {function} the function passed in boound to the object parameter.
  455.  */
  456. gadash.util.bindMethod = function(object, method) {
  457.   return function() {
  458.     return method.apply(object, arguments);
  459.   };
  460. };
  461.  
  462.  
  463. /**
  464.  * Utility method to return the lastNdays from today in the format yyyy-MM-dd.
  465.  * @param {Number} n The number of days in the past from tpday that we should
  466.  *     return a date. Value of 0 returns today.
  467.  * @return {String} date - The adjusted date value represented as a String.
  468.  */
  469. gadash.util.lastNdays = function(n) {
  470.   var today = new Date();
  471.   var before = new Date();
  472.   before.setDate(today.getDate() - n);
  473.  
  474.   var year = before.getFullYear();
  475.  
  476.   var month = before.getMonth() + 1;
  477.   if (month < 10) {
  478.     month = '0' + month;
  479.   }
  480.  
  481.   var day = before.getDate();
  482.   if (day < 10) {
  483.     day = '0' + day;
  484.   }
  485.  
  486.   return [year, month, day].join('-');
  487. };
  488.  
  489.  
  490. /**
  491.  * Utility method to return Date from a String in the format yyyy-MM-dd.
  492.  * This function is used for a Chart that has a Time Series.
  493.  * @param {String} date - The String representation of the date.
  494.  * @return {Date} date - Corresponding JS Date object.
  495.  */
  496. gadash.util.stringToDate = function(date) {
  497.   var year = date.substring(0, 4);
  498.   var month = date.substring(4, 6);
  499.   var day = date.substring(6, 8);
  500.  
  501.   if (month < 10) {
  502.     month = month.substring(1, 2);
  503.   }
  504.  
  505.   month = month - 1;
  506.  
  507.   if (day < 10) {
  508.     day = day.substring(1, 2);
  509.   }
  510.  
  511.   var dateObj = new Date(year, month, day);
  512.   return dateObj;
  513. };
  514.  
  515.  
  516. /**
  517.  * Formats the Google Metrics and Dimensions into readable strings
  518.  * Strips away the 'ga' and capitalizes first letter. Also puts a space
  519.  * between any lowercase and capital letters.
  520.  * ie: "ga:percentNewVisits" ---> "Percent New Visits"
  521.  * @param {String} gaString - the String name of Metric/Dimension from GA.
  522.  * @return {String} newString - Metric/Dimension formatted nicely.
  523.  */
  524. gadash.util.formatGAString = function(gaString) {
  525.   var newString = gaString.substring(3);
  526.   newString = newString.charAt(0).toUpperCase() + newString.slice(1);
  527.  
  528.   // Check for a capital letter in the string. If found,
  529.   // put a space between that char and the char before it.
  530.   for (var i = 1; i < newString.length; i++) {
  531.     if (newString.charAt(i) == newString.charAt(i).toUpperCase()) {
  532.       var left = newString.substring(0, i);
  533.       var right = newString.substring(i, newString.length);
  534.       newString = [left, right].join(' ');
  535.       i++;
  536.     }
  537.   }
  538.  
  539.   return newString;
  540. };
  541.  
  542.  
  543. /**
  544.  * Recursively copies the values in the from object into the to object.
  545.  * If a key in from object already exists, and has child values,
  546.  * the child values are copied over. So:
  547.  *     extend({'a': {'b': 2}}, {'a': {'c': 1}}) will result in:
  548.  *     {'a': {'b': 2, 'c': 1}}
  549.  * Once run, modifying the from object will not impact the to object.
  550.  * NOTE: Arrays will write over each other.
  551.  * NOTE: This is unsafe in that circular references are not checked. Calling
  552.  * this method with a circular reference could cause an infinite loop.
  553.  * @param {Object} from The object to copy values from.
  554.  * @param {Object} to The object to copy values into.
  555.  */
  556. gadash.util.extend = function(from, to) {
  557.   for (var key in from) {
  558.     var type = gadash.util.getType(from[key]);
  559.     if (type == 'object') {
  560.       to[key] = to[key] || {};
  561.       gadash.util.extend(from[key], to[key]);
  562.     } else {
  563.       to[key] = from[key];
  564.     }
  565.   }
  566. }
  567.  
  568.  
  569. /**
  570.  * Returns the native type (class property) of this object.
  571.  * General idea grabbed from here: http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
  572.  * Per ECMA-262:
  573.  *
  574.  *     15.2.4.2 Object.prototype.toString ( )
  575.  *     When the toString method is called, the following steps are taken:
  576.  *     1. Get the [[Class]] property of this object.
  577.  *     2. Compute a string value by concatenating the three
  578.  *        strings "[object ", | Result(1), and "]".
  579.  *     3. Return Result(2).
  580.  *
  581.  * @param {Object} value Any type.
  582.  * @returns {String} The lower class property of the object. Undefined if value
  583.  *     is undefined or null.
  584.  */
  585. gadash.util.getType = function(value) {
  586.   var classStringName = Object.prototype.toString.call(value);
  587.   return ({
  588.     '[object Boolean]': 'boolean',
  589.     '[object Number]': 'number',
  590.     '[object String]': 'string',
  591.     '[object Array]': 'array',
  592.     '[object Date]': 'date',
  593.     '[object RegExp]': 'regex',
  594.     '[object Object]' : 'object'
  595.   })[classStringName];
  596. }
  597.  
  598.  

но всё время ошибка: google is not defined на строке google.load('visualization', '1', {'packages': ['corechart', 'table']}); в файле gadash-1.0.js Скажите как победить?
eboome Отправлено: 04 Сентября, 2014 - 21:40:00 • Тема: Как работает вызов функции в PHP5 • Форум: Вопросы новичков

Ответов: 2
Просмотров: 131
Представим - у нас есть 2 файла, в первом набор пользовательских функций, во втором, собственно, их и вызывают. Суть вопроса: при первом вызове любой функции, читается весь файл с набором функций, но если одна и та же функция вызывается несколько раз, тогда как? Каждый раз читать весь файл, или в памяти сохраняется функция?
eboome Отправлено: 03 Сентября, 2014 - 12:54:53 • Тема: как передать результат выполения Ajax в віпадаючий список. • Форум: Вопросы новичков

Ответов: 6
Просмотров: 411
короч мучался долго, так и не решив етого задания. Сделал через jquery autocomplete. Спасибо Viper!
eboome Отправлено: 01 Сентября, 2014 - 16:18:57 • Тема: как передать результат выполения Ajax в віпадаючий список. • Форум: Вопросы новичков

Ответов: 6
Просмотров: 411
вернул json:
PHP:
скопировать код в буфер обмена
  1.  function getUserNick($searchdata)
  2.     {
  3.        
  4.         $result = $this->getAll($sQuery = "SELECT NickName from Profiles WHERE NickName LIKE '%{$searchdata}%' limit 10");
  5.      
  6.        
  7.          foreach ($result as $i=>$k){
  8.           $result_arr[$i]['nn'] = $k['NickName'];
  9.                  }
  10.           echo  json_encode($result_arr);    
  11.              
  12.        
  13.     }


немножко изменил ajax:

CODE (javascript):
скопировать код в буфер обмена
  1.  
  2.     function getUserByNick()
  3.     {
  4.         var searchchef = $("input[name=searchchef]").val();
  5.       $.ajax({
  6.         type: "POST",
  7.         url: "m/recipes/GetUserNickName",
  8.         dataType: "json",
  9.         data: {"searchchef": searchchef},
  10.         cache: false,                                
  11.         success: function(res){
  12.         var select = $('select'),
  13.            list = '';
  14.  
  15.           $.each(res, function(i, val){
  16.            list += '<option value="'+ val['nn'] +'">'+ val['nn'] +'</option>';
  17.             });
  18.  
  19.               select.append(list);
  20.            
  21.               }
  22.           });
  23.       return false;
  24.     }
  25. $('input[name=searchchef]').keyup(function(){
  26.     getUserByNick();
  27. });


Но вопрос как прикрутить етот список к форме?
CODE (html):
скопировать код в буфер обмена
  1.  
  2. <p><span>by chef</span></p>
  3. <input name="searchchef" type="text" id="__searchchef__">
eboome Отправлено: 01 Сентября, 2014 - 14:32:51 • Тема: как передать результат выполения Ajax в віпадаючий список. • Форум: Вопросы новичков

Ответов: 6
Просмотров: 411
Viper пишет:
Вам выпадающий список построить на основе массива?
Если да, то в success:

CODE (javascript):
скопировать код в буфер обмена
  1. var select = $('select'),
  2.         list = '';
  3.  
  4. $.each(res, function(i, val){
  5.         list += '<option value="'+ val +'">'+ val +'</option>';
  6. });
  7.  
  8. select.append(list);


А если вам нужно прям как в Jquery autocomplete то не проще ли его использовать?


что то так не получаетьсяНедовольство, огорчение

вот моя функция:
PHP:
скопировать код в буфер обмена
  1. function getUserNick($searchdata)
  2.     {
  3.        
  4.         $result = $this->getAll($sQuery = "SELECT NickName from Profiles WHERE NickName LIKE '%{$searchdata}%' limit 10");
  5.      
  6.         $result_arr = array();
  7.          foreach ($result as $k){
  8.           $result_arr['NickName'][] = $k['NickName'];
  9.                  }
  10.                  
  11.                $res = $result_arr['NickName'];
  12.                 print_r($res);
  13. //              
  14.        
  15.     }


Она возвращает такой массив:
PHP:
скопировать код в буфер обмена
  1. (
  2.     [0] => Earls_Organic_Produce
  3.     [1] => Metro_Denver_Farmers_Market
  4.     [2] => Richard_Perot
  5.     [3] => robert
  6. )


вот ajax запрос
CODE (javascript):
скопировать код в буфер обмена
  1.  
  2. function getUserByNick()
  3.     {
  4.         var searchchef = $("input[name=searchchef]").val();
  5.       $.ajax({
  6.         type: "POST",
  7.         url: "m/recipes/GetUserNickName",
  8.         data: {"searchchef": searchchef},
  9.         cache: false,                                
  10.         success: function(res){
  11.             console.log(res);
  12.            var select = $('select'),
  13.            list = '';
  14.  
  15.           $.each(res, function(i, val){
  16.            list += '<option value="'+ val +'">'+ val +'</option>';
  17.             });
  18.  
  19.               select.append(list);
  20.            
  21.               }
  22.           });
  23.       return false;
  24.     }
  25. $('input[name=searchchef]').keyup(function(){
  26.     getUserByNick();
  27. });


у меня ошибка js:
CODE (javascript):
скопировать код в буфер обмена
  1. Uncaught TypeError: Cannot use 'in' operator to search for '242' in Array
  2.  
eboome Отправлено: 01 Сентября, 2014 - 13:47:11 • Тема: как превратить многомерный массив в одномерный • Форум: Вопросы новичков

Ответов: 14
Просмотров: 505
а как сделать так:
PHP:
скопировать код в буфер обмена
  1. ['Admin', 'Aleksey', 'Angie', 'anotheruser', 'Brittany']
eboome Отправлено: 29 Августа, 2014 - 18:34:57 • Тема: как передать результат выполения Ajax в віпадаючий список. • Форум: Вопросы новичков

Ответов: 6
Просмотров: 411
Здраствуйте! Есть форма которая используеться для поиска пользователей:
CODE (html):
скопировать код в буфер обмена
  1.  
  2. <p><span>by chef</span></p>
  3. <input name="searchchef" type="text" id="__searchchef__">
  4.  

функцию поиска предоставлять не буду, так как она работает отличноУлыбка

есть аякс:
CODE (javascript):
скопировать код в буфер обмена
  1.  
  2.     function getUserByNick()
  3.     {
  4.         var searchchef = $("input[name=searchchef]").val();
  5.       $.ajax({
  6.         type: "POST",
  7.         url: "m/recipes/GetUserNickName",
  8.         data: {"searchchef": searchchef},
  9.         cache: false,                                
  10.         success: function(res){
  11.            console.log(res);
  12.            
  13.         }
  14.     });
  15.       return false;
  16.     }
  17. $('input[name=searchchef]').keyup(function(){
  18.     getUserByNick();
  19. });


есть функция которая обрабативает аякс:
PHP:
скопировать код в буфер обмена
  1.     function getUserNick($searchdata)
  2.     {
  3.        
  4.         $req = $this->getAll($sQuery = "SELECT NickName from Profiles WHERE NickName LIKE '%{$searchdata}%' limit 10");
  5.     ...  
  6.  

даная функция возвращает масив имен, типу ['andrew','roman','admin'] если я ввожу только букву "а"
Суть вопроса: как сделать так чтоб етот масив передать в выпадающий список, так как в Jquery autocomplete
eboome Отправлено: 29 Августа, 2014 - 16:05:13 • Тема: как превратить многомерный массив в одномерный • Форум: Вопросы новичков

Ответов: 14
Просмотров: 505
спасибо, то что надо!
eboome Отправлено: 29 Августа, 2014 - 15:31:04 • Тема: как превратить многомерный массив в одномерный • Форум: Вопросы новичков

Ответов: 14
Просмотров: 505
я в курсе, мне нужно вот так:
PHP:
скопировать код в буфер обмена
  1.  
  2. [[NickName] => ['Admin', 'Aleksey', 'Angie', 'anotheruser', 'Brittany']]
  3.  
eboome Отправлено: 29 Августа, 2014 - 15:22:17 • Тема: как превратить многомерный массив в одномерный • Форум: Вопросы новичков

Ответов: 14
Просмотров: 505
RickMan пишет:

Уверен, что так...


не думаю, у меня функция в результате исполения запроса возвращает етот массив
PHP:
скопировать код в буфер обмена
  1.  
  2. (
  3.     [0] => Array
  4.         (
  5.             [NickName] => Admin
  6.         )
  7.  
  8.     [1] => Array
  9.         (
  10.             [NickName] => Aleksey
  11.         )
  12.  
  13.     [2] => Array
  14.         (
  15.             [NickName] => Angie
  16.         )
  17.  
  18.     [3] => Array
  19.         (
  20.             [NickName] => anotheruser
  21.         )
  22.  
  23.     [4] => Array
  24.         (
  25.             [NickName] => Brittany
  26.         )
  27.  


Мне нужно достать значения всех NickName и сформировать з них массив,
eboome Отправлено: 29 Августа, 2014 - 15:02:24 • Тема: как превратить многомерный массив в одномерный • Форум: Вопросы новичков

Ответов: 14
Просмотров: 505
Здраствуйте! есть массив:
PHP:
скопировать код в буфер обмена
  1.  
  2. (
  3.     [0] => Array
  4.         (
  5.             [NickName] => Admin
  6.         )
  7.  
  8.     [1] => Array
  9.         (
  10.             [NickName] => Aleksey
  11.         )
  12.  
  13.     [2] => Array
  14.         (
  15.             [NickName] => Angie
  16.         )
  17.  
  18.     [3] => Array
  19.         (
  20.             [NickName] => anotheruser
  21.         )
  22.  
  23.     [4] => Array
  24.         (
  25.             [NickName] => Brittany
  26.         )
  27.  
  28.  

как сделать так что б получилось:
PHP:
скопировать код в буфер обмена
  1.         (
  2.             [NickName] => value
  3.         )

или к каком направлении копать
eboome Отправлено: 18 Августа, 2014 - 15:51:24 • Тема: проблеми с поиском подстроки • Форум: Вопросы новичков

Ответов: 9
Просмотров: 243
Ch_chov пишет:
или preg_split

Спасибо за помощь!
вот мое чудо:
PHP:
скопировать код в буфер обмена
  1.  
  2. function decimalFractionToFraction($decimal_fraction){
  3.  
  4.       $out = explode('.', str_replace(',', '.', $decimal_fraction));
  5.      if ((int)$decimal_fraction<1)
  6.       $out[0]='';
  7.      switch($out[1]) {
  8.       case '25':
  9.        $result= $out[0]. ' 1/4';
  10.        break;
  11.       case '33':
  12.        $result= $out[0]. ' 1/3';
  13.        break;
  14.       case '5':
  15.        $result= $out[0]. ' 1/2';
  16.        break;
  17.       case '75':
  18.        $result= $out[0]. ' 3/4';
  19.        break;
  20.       default:
  21.        $result= $decimal_fraction;
  22.       }
  23.     return $result;
  24.      }
  25.  


Функция для работи с количеством ингредиентов. Если в БД есть 1.5 то мне нужно чтоб отображалось 1 1/2. Суть в том что БД уже была заполнена до меня, и там есть значения как и с "." так и с ",". Еще раз спасибоУлыбка
eboome Отправлено: 18 Августа, 2014 - 14:49:59 • Тема: проблеми с поиском подстроки • Форум: Вопросы новичков

Ответов: 9
Просмотров: 243
esterio пишет:
Точка . в регулярка означает ЛЮБОЙ символ. То что говорил Мелкий
Мелкий пишет:
Потому что ваша регулярка ответит 0 только в одном случае - если строка пустая.

кривизна моих мыслей...
в голову приходить только такой вариант:
PHP:
скопировать код в буфер обмена
  1.  
  2. if (preg_match("/,/i", $decimal_fraction))
  3.  {$out = explode(',',$decimal_fraction);}
  4. else
  5.  {$out = explode('.', $result);}
  6.  

Страниц (2): [1] 2 »
Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB