samedi 27 juin 2015

Adding up values in array

I am trying to count elements in an array separated by one or more zeroes (0) Example: [3,2,1,0,5,4,0,0,8,4]. 3+2+1 , 5+4 , 8+4 Output: [6,9,12] I have written the following function:

function countElementsInArray(){
$array = [1,2,4,0,9,8,4,0,7,1,2,6];

$countArr = [];
$count = 0;
$test = 0;

for($i = 0; $i < count($array); $i++){
    if( $array[$i] != 0 ) {
       $count += $array[$i];
    } 
    //else if($array[$i] == 0 || $array[$i - 1] == 0){
    else{
        $count = 0;
        $test += 1;
    }
    $countArr[$test] = $count;
}
return $countArr;

}

This works fine if I have only one "0" in the array. I can't figure out how to add up the values if I have 2 zeroes. Any idea how to solve this problem?

Laravel Polymorphic many to many relationship issue

I have a Many to Many Polymorphic relationship setup between a few models and everything seems to be working just fine with one slight issue...

If I add the same relation $book->genres()->save($scifi) multiple times, it shows up multiple times in my database. Maybe this is intentional, maybe it's not. If I'm overlooking something, I'd like to have it working the "Laravel" way before I go and start making methods to ensure that only one relationship of that kind is in the DB at a time.

Does load_file() in SIMPLE HTML DOM have timeout settings?

I use SIMPLE HTML DOM for parsing. Some pages take a very long time when i try to get contents. I need to set limit for function load_file() (for example 10 sec) -> go to the next page. Please without socket!

Chrome is requesting HTTPS suddenly and I can't log into admin area

I recently moved a wordpress site from one hostgator account to another. It's now an addon domain. For the last couple days everything was working fine.

Then suddenly Chrome started giving me this error when I tried to reach my admin area: enter image description here

Proceeding didn't help either as I don't have an SSL, so it returns a 404. enter image description here

In fact it doesn't matter what URL hijinks I play, any time I access the admin area it tries to use HTTPS.

This is only on Chrome. It appears that Chrome is requesting an HTTPS address. I've tried commenting out all the https code in wp-login.php but no dice.

I've tried uninstalling Chrome, clearing cookies, etc. No good.

I'm at my wit's end.

PHP included HTML relative path of external JS & CSS

I am trying to use PHP to read, then modify and echo an HTML file.

The included HTML file contains external JS, CSS references - all relative paths

for example...

<script src="js/myJavascript.js"></script>

Problem : The location of the PHP modifier file is not the same as the location of the included HTML file, and therefore the external includes are not loaded. I guess...

The solution of using absolute paths to reference external resources in the HTML file is not ideal to say the least...

What can be done to tell PHP that the path context of the included HTML file is the same as the directory from which it is being included and NOT the directory of the modifier file?

Thanks!

SELECT query with apostrophe

In my database, I have a column named storeName with a value called Joe's Kitchen.

When user enters Joe's Kitchen, I would store it in a variable named storeName and do a select query on it like this: "SELECT * FROM shops WHERE storename='".$storeName."'". Problem now is that the value contains apostrophe, how should I go about this ?

I have tried the method below but it is not working

$storeName = mysqli_real_escape_string($db->getConnection(),$_POST["storeName"]);

.NET web service and php client

I am new to php client interaction with .NET web service. I have looked around and aware of posts like the one below but there are not the answer to my question.

How to make a PHP SOAP client and store the result xml in php variables

http://ift.tt/1eOTCI5

Consume a .Net web service using PHP

A PHP SOAP client (to request and get response) is needed for .NET web service (http://localhost:8080/someexample/myservice.wsdl). The input/request would look like this:

<the_input name="secondyear">
  <authen>
    <Teacher>
     <teacherid>MrX</teacherid> 
     <password>t_pass</password> 
    </Teacher>
    <Student>
     <studentid>kids</studentid> 
     <password>s_pass</password> 
    </Student>
   </authen>
 <parameters>
    <parameter name="maths" value="123" /> 
    <parameter name="physics" value="abc" />
    <parameter name="sports" value="def" /> 
 </parameters>
</the_input>

Here is what i got but not working and i am not sure i am on the right track:

<?php 
 require_once("lib/nusoap.php");
 $url="http://ift.tt/1NkBRuL";
 $client = new SoapClient($url);

 $teacherid='MrX';
 $tpassword='t_pass';
 $studentid='kids';
 $spassword='s_pass';
 $ns = "http://example.com/";

 //Body of the Soap Header.
 $headerbody = array ('Teacher' => array('teacherid' => $teacherid,
                                      'password' => $tpassword ),
                      'Student' => array('stendentid' => $studentid,
                                       'password' => $spassword ));
 //Create Soap Header.
 $header = new SOAPHeader($ns, 'Authen', $headerbody);

 //set the Headers of Soap Client.
 $headerparam=$client->__setSoapHeaders($header);

 $name ='secondyear';
 $service_name = array('the_input'=>$name);

 $result =$client->__SoapCall($service_name,$headerparam)
 print_r ($result);
?>

I read somewhere in order to authenticate to a web service, one should put authentication parameter in php header, so what goes to the php body then or is it needed? is the parameters? parameter has the format of name and value, how do i do that in php array? any relevant example available? as mentioned i've done my research and not clear how to solve this problem.

Postgre user without password and PHP

I have a PostgreSQL database with a user and a database owned by that user. A local program written in C uses that user to manipulate that database without a password. I want to use HTML and PHP to create a web interface to access that database.

I've read conflicting things about PostgreSQL and using it without passwords. I also don't want to interfere with the way the current software is accessing and manipulating the database without a password.

Do I simply add a password for that user to use as log-in information for the PHP queries? Is there a better way to securely access that database through PHP?

When to use RDS service in amazon? I have mysql installed in ec2 instance

I have a dynamic website and I need to migrate to AWS. I am new to AWS and linux. I have a doubt while setting the environment. I have installed Mysql,Phpmyadmin separately.

I have the following questions :

  1. How to connect this installed Mysql with this installed Phpmyadmin ? How to access Phpmyadmin through browser in aws.
  2. Why do we need RDS then? Do I really need RDS instance?

Please help me..

Trying to use Path API but failing to deal with access token

I want to use the Path Api, what is the right URL to get access_token ?http://ift.tt/1eRoGH6

if else condition in htaccess for for admin and frontend in open cart?

i have .htaccess in which i want 301 redirect.So when I add 301 redirect code in .htaccess it works fine but i can not login to my backend.But if I remove this code it works fine.I just want it to work in frontend but now because of this code my I cannot login into backend.

Here is the CODE

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://ift.tt/VAk5HC [L,R=301,NC]

now i want if else condition or something which helps me to solve this error which works only for frontend of my open cart site and admin remains as it is without redirection.

Remove duplicates from PHP array but ignoring one parameter

I have an array comprised of PHP objects as such.

$objects[0] => $object->type => 'President'
               $object->name => 'Joe Blogs'
               $object->address => '123 Harry Street'

$objects[1] => $object->type => 'Secretary'
               $object->name => 'Joe Blogs'
               $object->address => '123 Harry Street'

$objects[2] => $object->type => 'Treasurer'
               $object->name => 'Jane Doe'
               $object->address => '456 Upton Street'

I would like to ignore the 'type' parameter and end up with

$objects[0] => $object->type => 'President'
               $object->name => 'Joe Blogs'
               $object->address => '123 Harry Street'

$objects[2] => $object->type => 'Treasurer'
               $object->name => 'Jane Doe'
               $object->address => '456 Upton Street'

I have tried a few difrent things one of which was to unset the parameter "type using a foreach loop and then trying to reset it but I wasn't sure how to tie the two indexes together to reset them. Another was trying to use the union in the select command but that wasn't working 100% correctly either.

I am just not sure how to best manage the type parameter

group_concat only display's one column?

I have a database structure like so

 Car
 - id   
 - carname
 - image
 - category
 - status

Parts
 - partid
 - partname

CarParts
 - carpartid
 - carid(fk)
 - partid(fk)
 - amountid(fk)

Category
 - id
 - categoryname

Amount
 - amountid
 - amountvalue

and here is my query:

SELECT group_concat(parts.partname) as parts FROM car left join  carparts on car.id = carparts.carpartid 
left join  parts on parts.partid = carparts.carpartid
left join amount on amount.amountid = carparts.amountid where status = 1
group by car.id

but this only display parts and nothing else i want

  • carname
  • image
  • category
  • status

PHP code inside Laravel 5 Blade Template

I have to place some PHP code inside Laravel 5 Blade Template. Like below

@foreach ($farmer->tasks as $task)
    @if ($task->pivot->due_at) < date(now))
        $style = 'alert alert-danger';
    @elseif ($task->pivot->due_at) > date(now))
        $style = 'alert alert-success';
    @else
        $style = '';
    @endif
@endforeach

Which is the actual procedure to place PHP code inside Laravel 5 Blade Template ??

How to use $query->set in a custom .php page?

this is my custom.php file.

require_once("wp-load.php");
global $wpdb;

$query->set('posts_per_page', 50 );           
$query->set('orderby', 'meta_value_num');
$query->set('meta_key', '_thumbs_rating_up');
$query->set('date_query', array( 'after' => '1 month ago' ));   
$query->set('order', 'DESC');   

How can a start this query now?

Server side: Fill form on a webpage

Lets say there's a form on a webpage with URL xyz.com . The form has some text input fields, some drop down selections to be made etc. I need to write a server side script to visit this web page and fill and submit the form. Note that the server doesn't have a browser environment.

What should I do to achieve this? Any techniques in PHP (using cURL) or Python or echoing Java script via PHP ? I'd also have the form field IDs with me.

run function that returns several foreach

I'm developing the script, do a search in an array with one or several keywords, which is the following script:

$url= "http://ift.tt/1JqYyQ7".date('d')."&output=json&groupby=country-adspace&period_group_by=day";


function search($array, $key, $value)
{
    $results = array();

    if (is_array($array)) {
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}


$json = file_get_contents($url);
$arr = json_decode($json, TRUE);



$my_date_arr = search($arr, 'ADSPACE', '41432');

I then returned the key, containing only that number as keyword. and I do another foreach to show only keys containing the characters.

  <?php
foreach ($my_date_arr as $key=>$value) :
  $country = $value['COUNTRY'];
  $clicks = $value['CLICKS'];
  $fecha = $value['DATE'];
  $adspace = $value['ADSPACE'];



?> 
    <td><?= $country; ?></td>
    <td><?= $clicks; ?></td> 
    <td><?=$fecha;?><td>
   <td><?=$adspace;?><td>

  </tr>

  <?php endforeach;?>

it all works perfectly, the problem is I want to make two requests to the same function with a different value for example:

$my_date_arr = search($arr, 'ADSPACE', '41432');
$my_date_arr = search($arr, 'ADSPACE', '41755');

the goal is to look into an array a predetermined value, then return the key that contains the value and thus only make a foreach of what I find in the foreach, but also need is to make several requests in that foreach to I return the entire result in a single request.

Separate multiple meta values with slashes within a $list (wordpress)

I want to list some custom posts (wordpress) and their meta values. Everything works fine so far, but I have to work with empty values too. And I want to use slashes to separate multiple values. So here's what I have so far:

$list = '<div class="clearfix vlist">
         <div class="vlist-content">' ;

while($wpex_query->have_posts()) : $wpex_query->the_post();

global $post;

$list .= '<div class="vlist-item">
          <div class="title">'.get_the_title().'</div>
          <div class="info">'
          .get_post_meta( $post->ID, 'wpex_vita_genre', true ).' / '
          .get_post_meta( $post->ID, 'wpex_vita_director', true ).' / '
          .get_post_meta( $post->ID, 'wpex_vita_role', true ).'</div>
          </div>';
endwhile;

wp_reset_query();

return $list . '</div></div>';

Problem comes within div.info, where I want to display 3 values, separated by slashes (/). Soon as one or two values are empty I get stupid double slashes // because these characters are not conditional. I don't know how to make them appear only when there are values to separate because I can't just put an if statement into my $list. I know I know now you people who know php are just shaking heads or doing facepalms because this for sure is easy pie... could you still tell me how to solve this problem?

Thank you!!

PHP Not Inserting Content in mySQL Database: Text, Images, Anything

So here is my dilemna that I've been reviewing and trying to break through for the last few days. I've created a basic login/register PHP system, which works fine. I've implemented a blog system that displays posts. I've written an add post function which does not post to the database, and it doesn't throw back an error function either.

I don't really understand because my register system works and adds new users, but the 'add blog post' does nothing. I can add from the database and it displays fine, but nothing here.

<?php
    error_reporting(E_ALL & ~E_NOTICE);
    session_start();

    if (isset($_SESSION['id'])) {

        $userId = $_SESSION['id'];
        $username = $_SESSION['username'];
    } else {
        header('Location: login.php');
        die();
    }

    if ($_POST['submit']) { 
        $title = strip_tags($_POST['title']);
        $subtitle = strip_tags($_POST['subtitle']);
        $content = strip_tags($_POST['content']);

        mysqli_query($dbCon, $userREQ3);
        $userREQ3 = " INSERT INTO `logindb`.`blog` 
        (`title`, `subtitle`, `content`) VALUES ('$title','$subtitle','$content')";

    }
?>

<!DOCTYPE html>
 <html>

   <head>

   </head>

   <body>
     Welcome, <?php echo $username; ?>, You are logged in. Your user id is <?php echo $userId; ?>.

    <a href="index.php">Index</a>
    <form action="logout.php">
        <input type="submit" value="Log me out!">
    </form>

    <form method="post" action="admin.php">
        Title: <input type="text" name="title"/><br>
        Subtitle: <input type="text" name="subtitle"/><br>
        <br>
        <br>
        Content: <textarea name="content"></textarea>
        <input type="submit" value="Write Post"/>
    </form>

   </body>
</html>

What software or IDE should I use to design front-end of a website?

I have a knowledge of HTML, CSS and Javascript. It is difficult to design website on Notepad++, and I think Dreamweaver is for beginners. Tell me how professional designers work? How websites like Facebook, Twitter are Designed?

Note: I am not talking about static website. I want to design dynamic website with PHP.

Blogger API : Get number of seen and clicks

I have read Google Developer Documentation but I couldn't find any documentation about get number of click and seen of a blog post. Does anyone know is it possible to get number of seen and click of a blog post through API?

Why isn't my js script loading in WordPress

I am trying to add a bootstrap js script to my WordPress theme the "right" way but i'm not seeing a link to the js file in the head section of the webpage when it loads. Iv'e tried adding it to the header of the WordPress theme the "right" way but no luck. Not i'm trying in the functions.php file and still no luck. Please help!

function buns_bootstrap_run(){


        wp_register_script('bootstrap-js', get_stylesheet_directory() . '/js/bootstrap.min.js', array('jquery'),'3.2.0', false);

        wp_enqueue_script('bootstrap-js');

        }

    add_action('wp_enqueue_script', 'buns_bootstrap_run');

Lumen multiple queues

I am wondering how to setup multiple queues with Lumen?

I have setup the below

\Queue::pushOn('xmlApi','App\Eve\Api\Corp\CorpSheetLimited@fire',['corpID'=>$id['corporationID']]);

now i am attempting to process it with a queue worker below

php artisan queue:work xmlApi --daemon --sleep=3 --tries=3

when i push onto the queue with the below it processes no issues

\Queue::push('App\Eve\Api\Corp\CorpSheetLimited@fire',['corpID'=>$id['corporationID']]);

processing with

php artisan queue:work --daemon --sleep=3 --tries=3

Can you please advise

Image retrieval from mysql database in php not working

I am getting an image from mysql database and trying to show it. I am using the following code. But its not working .What's the mistake i am making?

while ($row=mysql_fetch_array($result,MYSQL_ASSOC)) {
    $photo=$row['photo'];
    $name=$row['firstname'].' '.$row['lastname'];
    $email=$row['email'];
    echo "<tr><td>".'<img src="data:image/jpeg;base64,<?php echo base64_encode( $photo ); ?>" />'.'</td><td>'.$name.'</td><td>'.$email.'</td></tr>';
}

How Get an array by JSon and how i can set this return value to a modal form?

My Ajax code is

$("a#edit").click(function(){
      var id = $(this).closest('tr').attr('id');
        //alert(id);
$.ajax({
        url: 'getdata.php',
        type: "POST",
        dataType:'JSON',
        data: {
            id: id,
        },
        success:function(result){
            alert(result);
        }
      });
    });

My php code is here...

if ($_REQUEST['id'] != "") 
{
     $id=$_REQUEST['id'];
   $sql = "select * from visit_reports WHERE visit_planner_id='$id'";

        $query = sqlsrv_query( $link, $sql);
        while($data = sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC))
            {
              print_r($data);
      }  
  }

In firebug the array i get ..

Array
(
[id] => 1.0000
[visit_planner_id] => 230338
[bi_staff_present_name] => BI staff present name
[bi_staff_trial_function] => BI staff trial function
)

Now how i can use this array value into my specific input field of modal form ?

css not working after writing .htaccess

I was trying to get rid of my file extensions using .htaccess, it worked, but right now my CSS and images has stopped working. I have tried different things, but it's still not working. Please! I need help with this. Thanks in advance. All my php files are in the same directory which is the root folder and my css and image folder is in a different folder in my root folder. here is my code

RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*/.php$ %{REQUEST_FILENAME}.php [L]
RewriteRule ^(css|img) - [L]

Wordpress - Is using wp_mail function a sufficient way of sending emails

I am using wordpress and wish to create a custom php script instead of using a plugin for the contact form. I want to know if using the wp_mail function is the same as the php mail() function because my host sometimes has issues sending the mail without sending it via the smtp.

I've always used something like php_mailer ect for my contact forms but am new to wordpress.

Fatal Error call to member function count() is non object

I am trying to query a database using pdo, but I cant figure out the problem. I have created an init file for my db details and server details and config file for configuration and index file and DB file.

index.php

<?php
  require_once 'core/init.php';

  $user =  Db::getInstance()->get('users',array('username', '=' , 'raja' ));

  if($user->count()) 
  {
      echo "No user";
  }
  else{
    echo "OK!";
  }


?>

Db.php

<?php
    class Db
    {
        private static $_instance = null;
        private $_pdo,
                $_query,
                $_error=false,
                $_results,
                $_count=0;
        private function __construct()
        {
            try
            {
                $this->_pdo =new PDO("mysql:host=" .Config::get('mysql/host') . ";dbname=" .Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));
            }
            catch(PDOException $e)
            {
                    die($e->getMessage());
            }

        }

        public static function getInstance()
        {
            if (!isset(self::$_instance)) 
            {
                self::$_instance = new Db();
            }
            return self::$_instance;
        }
        public function query($sql,$params=array())
        {
            $this->_error = false;
            if($this->_query = $this->_pdo->prepare($sql))
            {   
                $x=1;
                if (count($params)) 
                {
                    foreach ($params as $param ) 
                    {
                        $this->_query->bindValue($x,$param);
                        $x++;
                    }
                }
                if ($this->_query->execute())
                 {
                        $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                        $this->_count = $this->_query->rowCount();
                 }  
                 else 
                 {
                    $this->error=true;
                 }
            }
            return $this;               
        }
        public function action($action,$table,$where=array())
        {
            if(count($where) === 3)
            {
                $operators = array('=','<','>','>=','<=');

                $field     = $where[0];
                $operator  = $where[1];
                $value     = $where[2];

                if(in_array($operator,$operators))
                {
                    $sql = "{$action}FROM{$table} WHERE {$field} {$operator} ?";

                    if($this->query($sql,array($value))->error()){
                        return $this;
                    }
                }
            }
            return false;

        }
        public function get($table,$where)
        {
            return $this->action('SELECT *', $table, $where);
        }
        public function delete($table,$where)
        {
            return $this->action('DELETE ', $table,$where);
        }

        public function error()
        {
            return $this->_error;
        }
        public function count()
        {
            return $this->_count;
        }
    }
?>

It reports a fatal error about not finding the count object:

Fatal error: Call to a member function count() on a non-object in C:\xampp\htdocs\Student Management system\index.php on line 6

What is a method to notify you when things "don't" happen?

I have lots of different scripts and quite a few cron jobs that trigger different things throughout the day. Many times it is to download data from an external API or to periodically run a script of some type.

However, I am at a loss in finding a simple method to notify me if these things don't happen. For example, recently, something happened on one of my servers that caused all the cron jobs to stop running. It took a few days before I started getting complaints that things weren't working right. What are some of the methods you use to make sure things happen on a regular basis?

Display the number of before held training

I am new in Laravel and I used Laravel 5 for my project. My specification is count the number of before held training according to category of training so i used join and group by and count function to get the number before held training:

In my controller code is as below:-

<?php

namespace App\Http\Controllers;
use Request;
use App\Training;
use App\Schedule;
use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\TrainingRequest;
use Carbon\Carbon;


  class TrainingController extends Controller
  {
/**
 * Display a listing of the resource.
 *
 * @return Response
 */

public function __construct(){

$this->middleware('auth',['only'=>'index']);
}
public function index()
{
    //


    $training=Training::all();

        $before_held=Schedule::join('training','training.id','=','schedule.training_id')
                 ->groupBy('training.category')->where('schedule.training_end_date','>=',carbon::now())->get();
   // echo count($before_held);
   //die();


    return view('Training.index',compact('training','before_held'));
}

In View:-

 <td><a href="/training/before_held">{{count($before_held)}}</a></td>

This always show 0 count in the table like this:-

|category|Held Before|
|test    |   0       |
|test    |   0       |

But I need count two if training_end_date greater than or equal to current time.

SO I am thankful if anyone can solve this issue.

Display wordpress sub-category posts on sub-category page

I'm trying to get a WP function to work properly.

I want it to display the posts from the selected sub-category page, for example, when navigating to: http://ift.tt/1BUiBUF, display all custom posts under "apples" category. I want to do this dynamically, so that no matter the number of sub-categories (apples, oranges, pears etc) this works every time the sub-category page is visited.

The following is my current function, but I don't know if the get_query_var('cat') is implemented properly. Currently, when I visit the sub-category page, it displays ALL posts with the parent category "fruits", but I want it to display just the "apples" posts.

<?php

$cat = get_query_var('cat'); // get current category
$yourcat = get_category($cat);

// only display product CPT posts 
query_posts( array( 'post_type' => 'products' ) ); 

if ( have_posts() ) : while ( have_posts() ) : the_post();
?>
  <div class="col-sm-3">
    <div class="thumbnail">
        <div class="more"><a href="<?php the_permalink(); ?>"><span class="fa fa-location-arrow"></span></a></div>
        <?php the_post_thumbnail(); ?>
        <div class="caption">
            <a href="<?php the_permalink(); ?>" class="btn btn-default" role="button"><?php the_title(); ?></a>
        </div>
      </div>
  </div>
<?php endwhile; endif; wp_reset_query(); ?>

ManyOnOne in a twig template

I have the following tables (and entities in / ):

+------------------+                  +--------------------+
|  forum_sections  |                  |  forum_categories  |
+------------------+                  +--------------------+
| id               ├--------|         | id                 |
| title            |        |---------| section            |
| position         |                  | position           |
| created_at       |                  | title              |
+------------------+                  | description        |
                                      +--------------------+

I want to archive the following html page (without the bullets ofcource):

  • this is a title (from forum_sections->title)
    • forum 1 (from forum_categories->title)
    • forum 2 (from forum_categories->title)
  • this is another title (from forum_sections->title)
    • forum 3 (from forum_categories->title)

I did some research on how to do this. So far I tried the following in my twig layout:

{% for section in sections %}
    <h1>title</h1>

    {% for category in categories %}
        bla bla
    {% endfor %}
{% endfor %}

Is this even possible with a 'findAll' query in Doctrine2? I tried some combinations, but they seem to get all the boards ignoring the sections.

My program in php is not working [on hold]

This program i have been debugging:


<?php
$SQLHost="localhost" ;
$SQLDBName="webgeein_database";
$SQLUser="webgeein_root" ;
$SQLPass="gaurav_singh"; 


$conn = new mysqli($SQLHost, $SQLUser, $SQLPass );
if ($conn->connect_error) 
{
$strErr = sprintf ( "Could not connect to server [%s] Error Code [%d]     \nError Message [%s]", $SQLHost, $conn->errno, $conn->error);
echo ( $strErr);
die ();
}

$conn->select_db ($SQLDBName);
$query = "SELECT * FROM student_record WHERE Name='RAMAN'" ;
if($query){echo("success");}else{echo("failure");} 

$result = $conn->query($query, MYSQLI_STORE_RESULT );
if($result){echo("success");}else{echo("failure");} 

$row = $result->fetch_assoc();
if($row){echo("success");}else{echo("failure");} 

$AGE = $row ['Age'] ;
if($T_Status){echo("success");}else{echo("failure");} 

echo($AGE);

?>

but even then the response is failure at running the query function.

and the result shown is

"""""successfailure."""""

I hope someone would solve the problem.

enter code here

MySQL syntax error (INSERT) [duplicate]

This question already has an answer here:

I need help with a simple MySQL insert query. I have the following code:

INSERT INTO reads (location, meter, value) VALUES ('$_GET[location]', '$meter', '$value')

Which, after PHP, translates into:

INSERT INTO reads (`location`, `meter`, `value`) VALUES ('1234','1111','2505')

This query returns the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'reads (location, meter, value) VALUES ('1234','1111','2505')' at line 1

I have gone over my syntax many times and just cant figure out what is wrong with my query. Can anyone spot it?

How to store XML field values in database using php

I have an XML in local server. I want to store values in databse using Php. How to do it. Any sample code plz to achieve it.

PHP file_exists returns false with existing files

I'm having a little problem with my PHP-code. I want to create a site which has different directories. Every directories has a file named pass (not .txt or something) with the value of the directories password. So if the pass-file doesn't exist the group will not exist. But even if the group exists it still says the group doesn't exist. Here's my code:

<?php
$name = $_POST['name'];
$group = $_POST['group'];
$pass = $_POST['pass'];
$filename = '/groups/' . $group . '/pass';
if(file_exists($filename)){
    $handle = fopen($filename) or die("can't open file");
    $hoi = fread($handle, filesize($filename));
    fclose($handle);
    if ($pass === $hoi){
        session_start();
        $_SESSION['name'] = $name;
        header('Location: http://www.google.com');
    }
    else{
        echo 'Password is wrong!';
    }
}
else{
    echo 'Group does not exist!';
}
?>

All POST-data is correct btw. Thanks for your help!

Ajax request to php from angular js

I am trying make an ajax request to php from angular js. But I am not getting the data I have sent. Please let me know where I am going wrong.

The following is the ajax call.

<script type="text/javascript">

    angular.module('app', []).controller("MyController", function($scope, $http) {

    var req = {
        method: 'POST',
        url: 'pujastrail/www/rest/get.php',
        headers: {
            'Content-Type': "application/x-www-form-urlencoded; charset=utf-8"
        },
        data: { lang: "fr" }
    }
    $http(req).success(function(data, status, headers, config){alert("done"+data);}).error(function(data, status, headers, config){alert("error"+res);});

        });
</script>

The following is the php code.

<?php
    if (isset($_POST['lang']) && !empty($_POST['lang'])) {
        $lang = $_POST['lang'];//this needs to be sent back to js file
    } else {
        $lang = "eRROR";// but this is being sent back to the js file
    }

    echo (json_encode($lang));
?>

I have tried this using $_REQUEST also but it didnot work.

How to use REST with MVC when there is no Database?

I have two servers, the first works using REST and other Webs pages that are built using MVC.

I usually always run REST commands in the Controller layer, however I am with a doubt, assuming that my project (using MVC) does not use database and I'm using Controllers only to send commands to the webservice to send and receive information.

  • The REST in this case would be equivalent to Model?

    In this case I should call the Rest within the Controllers and not create Models. eg .:

    public function createProductAction() {
        $rest = Rest('ws.example.com', 'PUT /items/', array(
                                            'price' => $price,
                                            'description' => $descricao
                                        ));
    
        if ($response->status === 200) {
            View::show('success.tpl');
        } else {
            View::show('error.tpl', $rest->error);
        }
    }
    
    

or

  • I would have to create Models to make the calls to REST?

    For example:

    class ProductsModel
    {
        public function putItem($preco, $descricao)
        {
            $rest = Rest('ws.example.com', 'PUT /items/', array(
                                                'price' => $price,
                                                'description' => $descricao
                                            ));
    
            //If status=200 new product is added
            return $response->status === 200;
        }
    
        public function deleteItem($id)
        {
            Rest('ws.example.com', 'DELETE /items/{id}', array(
                                                'id' => $id
                                            ));
    
            $response = json_decode($rest->getRespose());
    
            //If status=200 product is deleted
            return $response->status === 200;
        }
    
        public function getItem($id)
        {
            $rest = Rest('ws.example.com', 'GET /items/{id}', array(
                                                'id' => $id
                                            ));
    
            $response = json_decode($rest->getRespose());
            if ($response->status === 200) {
                //If status=200 return data
                return $response->data;
            }
    
            return NULL;
        }
    }
    
    

How should I proceed?

Facebook Graph API. How to get comment from post

Hi i have this to get comment from post it works is there is a years

 $json = file_get_contents("http://ift.tt/1RHTDtg");
    echo $json;

but now i have this error in facebook

{
   "error": {
      "message": "An access token is required to request this resource.",
      "type": "OAuthException",
      "code": 104
   }
}

how i can get all comment from post ?

i have using your code @luschn my request with true APP ID and App Secret

http://ift.tt/1eRiTBa]

i have this

{
   "error": {
      "message": "Invalid OAuth access token signature.",
      "type": "OAuthException",
      "code": 190
   }
}

i use chrome to look this error

-- English is not my native language, sorry for any mistakes.

Add Module to SugarCRM ACL Role List Admin Page when Module doesn't exist?

I am developing a module for SUgarCRM that is not your typical module.

My main module shows up in the SugarCRM Role list of mOdules but my module has several sub-modules which are sections in my main module that have there own custom database table and do not have a module folder or Bean.

Because of this, these sections do not automatically show up on the SugarCRM ACL Role admin page.

I am hoping someone can tell me how to or if it is even possible to add non-real modules as modules in the ACL Role admin page?

I am hoping with code I can manually create some database records and run some code to make it work. Any ideas?

Php include file in different folder that includes another file

I am new in PHP and I've been trying to make a file (index.php) include another file (connect.php) that includes another file (config.php) but they are located in different folders.

This is my directory structure:

 > index.php (in the [root]...)
 > connect.php ([root]/admin/)
 > config.php ([root]/admin/)

This is what I have so far:

index.php

include './admin/connect.php'

connect.php

$directory = getcwd();
chdir(__DIR__);
include "config.php";
chdir($directory);

This is actually working but somehow I'm not loving the idea of changing the working directory.

Is there a better way to achieve my goal?

Login failed in my code after inserting proper login details (i.e username and password), code in php and jquery

I have following code (php and jquery) for Login for Student and Teacher (using same form for both access). In my system the admin can create Student and Teacher. Once created, the details are saved into database. The saved details is suppose to be use for login to their admin panel. But, the problem is , when Student or Teacher wants to login with the login details, provided by the admin (which has already been saved in database table), It display error message : Login Failed, Please check your username and password. (Same details, saved into database table is used for login process). This aching my head. If someone can tell me , if there is some error in my code, will be much appreciated.

login_form.php

<form id="login_form1" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Sign in</h3>
<input type="text" class="input-block-level" id="username" name="username" placeholder="Username" required>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<button data-placement="right" title="Click Here to Sign In" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-signin icon-large"></i> Sign in</button>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').tooltip('show');
$('#signin').tooltip('hide');
});
</script>
</form>
<script>
jQuery(document).ready(function(){
jQuery("#login_form1").submit(function(e){
e.preventDefault();
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "login.php",
data: formData,
success: function(html){
if(html=='true_teacher')
{
$.jGrowl("Loading File Please Wait......", { sticky: true });
$.jGrowl("Welcome to Soch College's E- Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'dasboard_teacher.php'  }, delay);  
}else if (html == 'true'){
$.jGrowl("Welcome to Soch College's E- Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'student_notification.php'  }, delay); 
}else
{
$.jGrowl("Please Check your username and Password", { header: 'Login Failed' });
}
}
});
return false;
});
});
</script>

login.php

<?php include('admin/dbcon.php');
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//for student login
$query_student = mysql_query("SELECT * FROM student WHERE username='$username' AND password='$password'");
$count_stu = mysql_num_rows($query_student);
$row_stu = mysql_fetch_array($query_student);
//for teacher login
$query_teacher = mysql_query("SELECT * FROM teacher WHERE username='$username' AND password='$password'")or die(mysql_error());
$count_tea = mysql_num_rows($query_teacher);
$row_tea = mysql_fetch_array($query_teacher);
if( $count_stu > 0 ) { 
$_SESSION['id']=$row_student['student_id'];
echo 'true';
}else if( $count_tea > 0 ) { 
$_SESSION['id']=$row_teacher['teacher_id'];
echo 'true_teacher';
}
else{ 
}?>

In Moodle, how to achieve auto continuity between two different activities (Scorm PPT then Quiz) under a topic?

Expectation: A user opens a scorm (Basic001) view all the slides once the activity ends, the process must be automatically redirected to the second activity (Quiz).

I have created a "Category" under which I have created a "Topic" where I have added an activity (Scorm Package created using zenler) and then followed by another activity (Quiz) under the Topic (refer to the image below). I have also set restrictions and activity completion requirements.

The activities(ScormPPT & Quiz) under a topic

I'm using Moodle v2.9

How to achieve this method? If not is there any plugin which helps to achieve this or do this can be achieved by modifying Moodle program?

Symfony2: how can I make a or just

My buttons from the Symfony form component come out as:

<button type="button">Submit</button>

Of course, this doesn't submit the form.

What I'd like is:

<button type="button">Submit</button>
// or
<button>Submit</button>

I'd rather not use an <input type="submit"> so I have more control over the look of the button.

Session_start function not starting properly

I'm trying to use the session_start() function to write a login system using PHP. However, the document i am initializing my session in has the session_start(); on the top of it. I've made sure that nothing is being sent as headers by the document before the session_start(); is processed. However, the error "Cannot send session cache limit - headers already sent.." is still persisting.

<?php session_start(); ?> // The very beginning of my document



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://ift.tt/kkyg93">

<html xmlns="http://ift.tt/lH0Osb">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WorldOfConquer - WoC</title>
<link rel="SHORTCUT ICON" href="Style/favicon.ico">

<meta name="description" content=" WorldOfConquer - WoC, The best classic 1.0 server.">
<meta name="keywords" content="WorldOfConquer - WoC, The best classic 1.0   server.">

    <meta http-equiv="ROBOTS" content="INDEX,FOLLOW">
    <meta name="ROBOTS" content="INDEX,FOLLOW"> 
    <meta name="REVISIT-AFTER" content="2 days">
    <meta name="Author" content="Laviniu">
    <meta name="LANGUAGE" content="EN">
    <meta name="AUDIENCE" content="ALL">
    <link href="Style/index.css" type="text/css" rel="stylesheet">

How I initialize my session :

$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
echo "You have successfuly logged on!";

Gravity Forms - Date Picker - Disallow End Date to be before Start Date

basically I have a large form created on my WordPress site using Gravity Forms. One section of my forms has a bunch of items listed with a 'Start Date' followed by an 'End Date' -- Example:

Item | Start Date | End Date

Item#1 | 05/01/2015 | 05/25/2015

What I am after is making it so I can disallow the 'End Date' from being before the selected 'Start Date'. It would be best if the user was unable to even select the date from the date picker drop down, but if it has to be an error that pops up on submission, that is fine to. I have been researching this for hours and I am just too noob to know exactly what to do. Thanks for any and all help!

PHP : Echo java script code to given url

I wanted to auto-fill a form on a web page. I wrote the javascript code for that, and it is working fine. When I visit the web page manually and run the JS code in the console, it works. But I need this JS code to be run from a server by a PHP code. So I'd like to echo this javascript to the specified URL.

Basically, I want a PHP file on a server (with no browser environment) to run a javascript code on a webpage , using echo . I know how to echo HTML/JS from PHP, but I want it to run on a specific web page. Since there is no browser involved I can't use the JS code window.location.href=url to do this.

Here's the PHP code to echo the JS:

echo "  <html>
    <head>
        <script src="../js/xyz.js"></script>
    </head>
    <body onload="tmp()">
        <script type="text/javascript">
            function tmp(){
                // FIRST VISIT THE URL AND THEN RUN BELOW FUNCTION
                someJSfunction("12345","0019");
            }
        </script>"
    </body>
    </html>
    "
;

Cannot do OOP Callback function for usort

I have read through a few dozen discussion of the use of class members as callback functions but none of the examples address what seems to me to be the obvious OOP design, based upon working with other OOP languages such as C++ and Java.

I have defined a comparison method within the class:

class TestClass {
private $aField; // integer value
function _construct($value)
{
        $this->aField   = $value;
}       // TestClass::_construct

function compare($other)
{
    if ($other instanceof TestClass)
    {           // comparing two instances
    return $this->afield - $other->afield;
    }           // comparing two events
    else
    throw new Exception("parameter is not instance of TestClass");
}       // TestClass::compare
}       // class TestClass

$instances  = array(new TestClass(5),new TestClass(3));
// the following fails because:
// 1. $this is not defined outside a class member
// 2. compare does not take two parameters
usort($instances, array($this, 'compare'));

// the following kluge works around this
function order($this, $that) { return $this->compare($that); }
usort($instances, 'order');

All of the examples I can find on this forum and in the PHP documentation are not complete in that they do not show the context of the call to usort. Now I can get around this by making the comparison function a static function with two parameters and invoke it as a callable by array('TestClass','compare'), but it is not intuitive to define a comparison method as a static function of the class. Based upon over 30 years of personal experience in OOP static functions are in most cases a result of poor class design. In particular static methods defeat polymorphism.

What I am looking for is a sort function like that of Java, which exploits the Comparable interface. I see that there has been some discussion dating back to 2010 about defining a Comparable interface, but that discussion is only in connection with the comparison operators, and makes PHP purists uncomfortable because it overloads operators. However the Java Comparable interface does not overload operators since, with the glaring exception of the String class, Java does not support overloading operators. Implementing the Comparable interface in Java enables you to use the class in SortedMaps and to sort instances within a Collection, but if you wish to compare two objects you must explicitly call the compareTo method. I also see that there is an essentially undocumented compare_objects method which already overrides the default implementation of the comparison operators. In other words despite the purists' objections PHP already permits you to overload the comparison operators for a class. However it is undocumented whether or not the PHP sort function uses compare_objects when it is asked to sort objects.

Limit related records in polymorphic many-to-many realtionship with Laravel

I am using Laravel 5.1 and I need to limit the number of related records I am pulling using a polymorphic many-to-many relationship.

What I would like to do is get a list of categories by parent_id. For each category then I'd like to only pull four posts.

I have have this working with the code below, but it results in a bunch of extra queries. I'd like to just hit the database once if possible. I'd like to use the Laravel/Eloquent framework if at all possible, but am open to whatever works at this point.

@foreach ($categories as $category)
  @if ($category->posts->count() > 0)
    <h2>{{ $category->name }}</h2>
    <a href="/style/{{ $category->slug }}">See more</a>

    {-- This part is the wonky part --}

    @foreach ($category->posts()->take(4)->get() as $post)

      {{ $post->body }}

    @endforeach

  @endif
@endforeach

PostsController

public function index(Category $category)
{
  $categories = $category->with('posts')
      ->whereParentId(2)
      ->get();

  return view('posts.index')->with(compact('categories'));
}

Database

posts
    id - integer
    body - string

categories
    id - integer
    name - string
    parent_id - integer

categorizables
    category_id - integer
    categorizable_id - integer
    categorizable_type - string

Post Model

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    public function categories()
    {
        return $this->morphToMany('App\Category', 'categorizable');
    }

Category Model

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category', 'parent_id');
    }
    public function subcategories()
    {
        return $this->hasMany('App\Category', 'parent_id')->orderBy('order', 'asc');
    }
    public function posts()
    {
        return $this->morphedByMany('App\Post', 'categorizable');
    }

I have seen a number of links to this on the web, but nothing that has actually worked for me.

I have tried this solution without any luck.

$categories = $category->with('posts')
->whereParentId(2)
->posts()
->take(4)
->get();

I have looked into this solution by Jarek at SoftOnTheSofa, but it is for a hasMany relationship and to be honest is a bit beyond my sql skill for me to adapt it for my needs.

Using parseincludes in Laravel5 Fractal

Struggling using parseIncludes in http://ift.tt/1h7EiPY.

I have two tables, Property and Weeks. Each property has many weeks. Using Fractal I can return my property item with a collection of weeks. What I want to do is use parseIncludes, so that the return of weeks is optional.

PropertyTransformer.php

<?php
namespace App\Transformer;

use App\Models\Property;
use League\Fractal\TransformerAbstract;


class PropertyTransformer extends TransformerAbstract
{

    protected $availableIncludes = [
        'week'
    ];

    public function transform(Property $property)
    {
        return [
            'id'                => (int) $property['PropertyID'],
            'PropertyName'      => $property['PropertyName'],
            'ExactBeds'         => (int) $property['ExactBeds'],
            'weeks'             => $property->week
        ];
    }

    /**
     * Include Week
     *
     * @return League\Fractal\ItemResource
     */
    public function includeWeek( Property $property )
    {
        $week = $property->week;

        return $this->item($week, new WeekTransformer);
    }
}

WeekTransformer.php

<?php
namespace App\Transformer;

use App\Models\Week;
use League\Fractal;

class WeekTransformer extends Fractal\TransformerAbstract
{


    public function transform(Week $week)
    {
        return [
            'Week'          => $week['week'],
            'Available'     => $week['available'],
            'Price'         => (int) $week['price'],

        ];
    }

}

My PropertyController.php

<?php namespace App\Http\Controllers\Api\v1;

use App\Http\Requests;
use App\Models\Week;
use Illuminate\Support\Facades\Response;

use App\Models\Property;

use League\Fractal;
use League\Fractal\Manager;
use League\Fractal\Resource\Collection as Collection;
use League\Fractal\Resource\Item as Item;

use App\Transformer\PropertyTransformer;


class PropertyController extends \App\Http\Controllers\Controller {

public function show($id)
{
    $property = Property::with('bedroom')->with('week')->find($id);

    $fractal = new Fractal\Manager();

    if (isset($_GET['include'])) {
        $fractal->parseIncludes($_GET['include']);
    }

    $resource = new Fractal\Resource\Item($property, new PropertyTransformer);
    //$resource = new Fractal\Resource\Collection($properies, new PropertyTransformer);

    return $fractal->createData( $resource )->parseIncludes('weeks')->toJson();

}

I get the following error on the parseIncludes:-

Method 'parseIncludes' not found in class \League\Fractal\Scope

I'm following the guide here on transformers - http://ift.tt/1GEuNV5

I think I am going wrong somewhere here where it says:-

These includes will be available but can never be requested unless the Manager::parseIncludes() method is called:

<?php
use League\Fractal;

$fractal = new Fractal\Manager();

if (isset($_GET['include'])) {
    $fractal->parseIncludes($_GET['include']);
}

If I remove the parseIncludes, I don't get an error, I also get my property data with my collection of weeks, but ?include=week doesn't work to optionally get it.

mardi 5 mai 2015

AngularJS - Remove iOS scrolling and window dragging

I've seen a lot of similar questions to this but none seem to provide me with a solution that is working for me. So I'm using an AngularJS app and it's been made to feel very much like a native app on your phone, so it shouldn't really use any of Apple's bouncing scroll. If I drag the window I get something very similar to this:

http://ift.tt/1GZZgmg

It's not great when you're trying to create a native-feeling web app, so how would I go about removing this?

Angularized Bootstrap Menu Not Collapsing after Link Click

I have a Angularized bootstrap menu that works if it is loaded in a view, but not when in the index.html. I need it in the index.html before the views (data-ng-view) since I have content between the menu and views. When placed before my views in the index.html page, if I click on a link, I am able to go that link... but the menu stays open instead of closing after going to a link. I am using AngularUI and have injected 'ui.bootstrap' into the App (that is how it works when loaded in a view). The controllers for my views are tied to the page they relate to.

Example:

when('/home', { templateUrl: './views/home.html', controller: 'homeCtrl' }).

Here is my navigation:

<nav class="navbar navbar-default">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-ng-init="isCollapsed = true" data-ng-click="isCollapsed = !isCollapsed">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="/"><h1 id="pfch1">My Title</h1></a>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" data-ng-class="{collapse: isCollapsed}">
        <ul class="nav navbar-nav">
            <li><a href="/home">Home</a></li>
            <li class="dropdown" data-ng-class="{ open : dd1 }" data-ng-init="dd1 = false" data-ng-click="dd1 = !dd1">
                <a class="dropdown-toggle" role="button" aria-expanded="false" href="#">Categories <span class="caret"></span></a>
                <ul class="dropdown-menu" role="menu">
                    <li><a href="/categories/1/cat1">cat1</a></li>
                    <li><a href="/categories/2/cat2">cat2</a></li>
                    <li><a href="/categories/5/cat3">cat3</a></li>
                    <li><a href="/categories/4/cat4">cat4</a></li>
                    <li><a href="/categories/6/cat5">cat5</a></li>
                    <li><a href="/categories/3/cat6">cat6</a></li>
                </ul>
            </li>
            <li><a href="/add-article">Add Article Link</a></li>
        </ul>
        <form class="navbar-form navbar-right">
            <div class="form-group">
                <div data-ng-controller="userInfo">
                    <div data-ng-controller="loginCtrl" data-ng-hide="loggedin">
                        <input class="btn btn-default" type="submit" value="Login" data-ng-click="login()" />
                    </div>
                    <div data-ng-controller="loginCtrl" data-ng-show="loggedin">
                        <input class="btn btn-default" type="submit" value="Signout" data-ng-click="logout()" />
                    </div>
                </div>
            </div>
        </form>
    </div>
</nav>

Here is the relevant section of index.html (please note that the menu above is included via an ng-include. I have tried it without the ng-include but it still doesn't collapse):

<body>
<!-- Container start -->
<div class="container">
    <!-- Top Menu -->
    <div data-ng-include="'templates/topmenu.html'"></div>
            <div data-ng-view></div>
           <hr>
    <footer>
        <p>&copy; My Site 2015</p>
    </footer>
</div>
<!-- Container end -->
</body>

Django Rest Framwork and Angular

I am very new Django Rest Framework and Angular Js. What I wandering here is the best way to work with these two.

  1. Django Rest and Angular js together (Most of tutorials showed me this)
  2. Django Rest as backend and Angular js in frontend as 2 different projects

I am very confused, though I feel the 2nd approach is better. But still not sure. Can please anyone help me in this with pros and cons of both the approaches

Angular JS works in main layout(view) but not in child view of laravel 4.2

I'm trying to use Angular JS with Laravel 4.2. I've changed the blade's default {{}} into [[]], it works perfectly, now the problem is that when I puts Angular JS code in main layout (view) it works but when I put Angular JS code in a child view(actually child view extends the main layout and section is yielded using @section('contents') ...Angular JS code... @stop) it doesn't work at all, browser can't render the Angular JS exprerssion and shows it as it is in code editor! Here is my "main layout.blade.php" and "child.blade.php":

"main.layout.blade.php"

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Customer Management</title>

    <!-- Bootstrap -->
    [[ HTML::style('css/bootstrap.min.css') ]]
    [[ HTML::style('css/custom.css') ]]

    [[--angular js files--]]
    [[HTML::script('/js/angular/angular.min.js')]]
    [[HTML::script('/js/controllers.js')]]

    [[--jquery bootsrtap js files--]]
    [[ HTML::script('js/respond.js') ]]
    [[ HTML::script('js/jquery-1.11.2.min.js') ]]
    [[ HTML::script('js/bootstrap.min.js') ]]

</head>

<body>

    @include('layouts.main-menu')

    <div class="container" id="container">
        <div ng-app=""><!-- This Angular JS works fine -->
            <p>Name : <input type="text" ng-model="name"></p>
            <h1>Hello {{name}}</h1>
        </div>

        @yield('content')
    </div>

    @include('layouts.footer')


    <script>
        $("nav ul li").on("click", function() {
            $("nav ul li").removeClass("active");
            $(this).addClass("active");
        });
    </script>
</body>
</html>

Child.blade.php

@extends('layouts.main')
<!doctype html ng-app="myApp">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>

</head>
<body>

    @section('content')
        <div ng-app=""><!-- This Angular JS doesn't work fine -->
            <p>Name : <input type="text" ng-model="name1"></p>
            <h1>Hello {{name1}} </h1>
        </div>
    @stop
</body>
</html>

You can see clearly that same Angular Code snippet is used in both files but in "layout.main.blade.php" it works and in "child.blade.php" it doesn't work as it is in between @section('content') ... @stop I can't get understand why this is and how to solve it!!!!!!

how to add directive attribute to element in link function?

As we known, the angular have performance if there are more than 2000 records in the page, because only some of the records need add some behavior , so I would prefer to dynamically add attribute to element according model value in link function, as there will be less watches.

So I use $compile to recompile the element like below:

mainApp.directive("popoverSetting", function ($compile) {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            if (scope.item.isTrue) {
                element.attrs("ns-popover-trigger", "mouseenter");
                element.attrs("ns-popover-timeout", "0.01");

                $compile(element)(scope);
            }
        }
    }
})

Because there are about 1000 records, so the speed is very slow, is there some other way to add attribute and compile quickly? although there only 5 records need to add these attribute, it still increase about twofold time than before.

How to store data for my complex web app, similar to JS Fiddle

I'm designing a web app and I'd like to make sure that my data model will work and can grow. If anyone knows any resources or standards I should follow, I'd appreciate that too. Basically, it's a complex note application with the following pieces:

I have things called chapters, the user can only see one chapter at a time. A chapter consists of 2 parts : pages and comments.

The left half of the window houses the pages (there can be multiple pages). For sake of simplicity, a page is just a string of text.

The right half will contain the comments. In other words, when a user selects a certain sentence in a page, a comment will pop up.

I'd like to have as many of these chapters as necessary, and I haven't come up with a navigational structure but I suspect I'll need to be able to group chapters together.

Right now, how I was thinking about it was having an array for each chapter so it looks like this:

[
    {
        "page": "asd",
        "comments": another array
    },
    {
        "page": "random string, will include html elements"
        "comments": another array
    }
]

I'm using angular JS and using ng-repeat to loop through this array and display all the pages. Then depending on which comment the user clicks on, the selected comment will show up on the right side.

So I don't have a unique id for each chapter- is there a standard way? I also think I need some kind of id for comments, since there can be many comments per page. I was looking into guid's but I've never used them before.

I was thinking of having this comments array:

"comments": [ {"id": "guid", "comment":"asfasfd"}, {"id": "guid", "comment":"asfasfd"}]

I also wanted to assign a guid for each chapter. For testing, I was going to keep all the chapters in one json file.

What is generally done for stuff like this? For example, how does JS Fiddle store it's data? I assume there are chunks for the html, the JS and the CSS, along with metadata, but I'm not sure how their data model actually looks like.

How to navigate to a cordova/ionic page in android fragment with all styles and scripts loaded?

I am developing a hybrid application with angularJS and ionic. All the screens are html. After login user will pick some actions in the left panel and action screen will be displayed in the right panel. It is working fine in iOS. Due to some deign issues we decided to go with native for action panel and action screens in android. But still we have a html5 screen for a action menu item for android (simple HTML5 form). My problem with android is:

  • User logs in (HTML5 login screen)
  • Action screen displayed with left panel and right panel (native android)
  • User picks an action in the left, right panel displays the action screen. (native)
  • User picks a specify action xx in the left panel. Now show the HTML5 action screen inthe right panel.

I am using Android fragment and Cordova web view to load the HTML5 action screen for the specif action xx. But the screen is loaded without styles and other angular/ionic stuff. (using cordovawebview.loadUrl())

Because user is already logged in, app should show the action screen with all styles and JS applied. How do I do that ?

writing an $httpProvider for a long-polling comet app

TL;DR: Are there examples of Angular with long-polling integration out there? (Examples, specifically Comet examples would be nice!)

Our current app uses Angular and Comet. The client sends out long-polling requests that stay open until the server has data to return. When the server returns data, the data payload might have several messages for different 'channels'.

The out-of the box Comet JS code we have uses jQuery's $.get(), $.post() methods to make the long-polling requests.

Angular is built on a light version of jQuery and adds lots of (Angular-related) magic compared to $.get()/$.post() via Angular's $http object.

I've been told the Angular's $http object and the promises it returns are not compatible with message-based front-ends, but I'm not convinced

Is it true they are incompatible?

I was thinking a different $httpProvider that is Comet aware could be written, that would provide an $http object, that based on URL could determine if it should behave in normal ajax mode or long-poll mode.

The idea here is that typically each Comet channel has a message listener and the listener has a callback it invokes passing in the message.

To me this seems like a promise in disguise. Generally, the idea would be to create a promise for each channel. When the $http object is dealing with a long-poll request, when the server responds with data it would know how to parse the payload into messages for each channel, and then resolve each channel (which is now a promise in Angular world). Resolving each channel would have the effect of calling the channels/promises then() function.

Doesn't this achieve message-based behavior with listeners and callbacks? Are these just the same things, but with different names?

I'm considering toying with the approach and possibly prototyping it. But before I do, does this even make sense?

How these promises would resolve in Angular HTML templates I'm still uncertain about.

Are there already examples of Angular with long-polling integration out there?

I couldn't find any.

Get error : [$injector:unpr] Unknown provider: socketProvider <- socket <- LogCtrl

I am new to AngularJs and nodejs and I have a simple chat app with angular as client and socketio as server side. I got an error when loading angular page

Error: [$injector:unpr] Unknown provider: socketProvider <- socket <- LogCtrl

My client side

    <script src="http://ift.tt/1xHFqJ2"></script>
<script src="http://ift.tt/1ELJDLe"></script>
<script src="http://localhost:1337/socket.io/socket.io.js"></script>

<script type="application/javascript">
     socket = io.connect('http://localhost:1337/');
     angular.module('Log',['ngRoute'])

             .controller('LogCtrl',['$scope','socket','$location', function($scope,socket,$location){

                 console.log('ok baby !!');

                 $scope.addUser = function(){
                     socket.emit('init',$scope.user);
                     $location.path("/view/index.html");
                 };

             }]);
 </script>

<body  ng-app = "Log" >
<div class=" main"  ng-controller = "LogCtrl" style = "width: 300px; ">
<fieldset>
     <form  ng-submit = "addUser()">
         <h2 >Hello!!</h2>
         <input ng-model = "user" required  style = "width: 200px; " placeholder = "Nhập tên của bạn" >
         <input type = "submit" value = "OK">
    </form>
</fieldset>
</div>

Please help me what wrong with my client

Angular JS Can't interpolate: $selectMultiple.getPlaceholder()

So, i have this implementation of multi select ui on a form with other fields:

This is the view:

<div class="form-group">
<label for="components" class="col-sm-2 control-label">Components</label>
<div class="col-sm-10">
  <ui-select multiple ng-model="service.components" theme="bootstrap">
        <ui-select-match placeholder="Select a component">{{ $item.name }}</ui-select-match>
            <ui-select-choices repeat="component in components">
                <small ng-bind-html="component.name"></small>
        </ui-select-choices>
    </ui-select>
</div>

And in the backend i get the data on this way:

http.get('config/init_data.json').then(function(res) {
    service.components = res.data.components;
});

When i perform the submit function, everything works fine, get the data in the multiselect, show me the selected ones and creates the object perfectly. The problem is when i want to perform the same action for second time... in that case i get the error:

Error: [$interpolate:interr] Can't interpolate: {{$selectMultiple.getPlaceholder()}} TypeError: Cannot read property 'length' of undefined

ui-select error “Can't interpolate: {{$select.getPlaceholder()}}” have the same problem but the solution don't work for me.

Any ideas? Thank you some much for your help.

Include HTML/PHP in JS variable

I have the following JS code:

{var c;a.stores=[{name:"Nijiya Market",price:"$$",sales:292,rating:4},{name:"Eat On Monday Truck",price:"$",sales:119,rating:4.3}]

I call on these variables to produce an html table. What I want to do is use html within the JS variable to produce an image instead of text. So for example:

{var c;a.stores=[{name:"<img src='url'>",price:"$$",sales:292,rating:4},{name:"<img src='url'>",price:"$",sales:119,rating:4.3}]

Can anyone suggest how I do this and if the same method would work with php.

Don't know if it matters, but I am using AngularJS.

Thanks.

How to share user settings in 2 browsers

We have a scenario like this:

angular.module('xxx').service('PersistenceService', [ '$rootScope', '$window', function ($rootScope, $window) {
    'use strict';

    function makeKey(key) {
        return $rootScope.session.userName + '_' + $rootScope.session.tenantId + '_' + key;
    }

    this.get = function (key) {
        return $window.localStorage.getItem(makeKey(key));
    };

    this.set = function (key, value) {
        $window.localStorage.setItem(makeKey(key), value);
    };

    this.remove = function (key) {
        $window.localStorage.removeItem(makeKey(key));
    };
}
]);

Currently in our web app, we store the user settings in the Local Storage(js localStorage), the shortage of the local storage is we can't share the settings cross 2 sessions(may be 2 browsers is easy to understand).

Now we want to save the user settings to the server side so user can share his application settings via different browsers.

Here is the question: In our project, the API to interact with local storage is a synchronize design, 1.)if we keep the old interface, and do the sync server logic in each interfaces, the performance is very low. 2.)if we use promise to sync with server, lots of codes need to be changed.

I think neither of above 2 method is acceptable. Currently what i can think of is: Fetch the user settings on app initializing and copy the settings to localStorage, so we can use the old interfaces to without change any code out side of the persistence service. We also need to sync server logic in method(Set, Remove)

Does anyone have any better ideas? Thanks in advance!

What is best practise for user authentication across subdomains between an AngularJS UI and a Lithium API?

I have setup a lithium REST API with an AngularJS UI as two separate projects. For the setup of the UI I originally followed this tutorial before going down a slightly different approach. The UI has a session service that effectively syncs session data between itself and a PHP session which is started on the first request to the API. I have been building the apps and testing them locally on a vagrant box and they have been working fine with one and other but when it came to pushing them to the staging environment each call to the API would create a new session key and would not authenticate further than the single login request.

I have read some articles on cross domain security issues but from the sounds of it CORS is secure and may be what I'm looking for. I have had a little play setting the headers on my apache virtual host config in the staging environment to try to make the sessions persist with the UI ajax calls but without any luck.

So I guess my question is: is there a way to make this type of setup work across domains api.domain.com and ui.domain.com and is it secure?

The API currently only outs the standard 401 authentication status code and the UI uses an auth interceptor service on the $httpProvider to detect the status. The interceptor then calls $rootScope.$broadcast AUTH_EVENTS.unauthorized to broadcast that the app has lost authentication with the API and calls $state.go "login" to prompt the user to login.

I plan to add the 403 forbidden status down the line once I have implemented some form of ACL.

Lithium session bootstrap

use lithium\storage\Session;

$name = basename(LITHIUM_APP_PATH);
Session::config([
    'default' => ['adapter' => 'Php', 'session.name' => $name]
]);

use lithium\security\Auth;

Auth::config([
    'default' => [
        'adapter' => 'Form',
        'model' => 'Users',
        'fields' => ['email', 'password']
    ]
]);

use lithium\action\Dispatcher;
use lithium\action\Response;

Dispatcher::applyFilter('_callable', function($self, $params, $chain) {
    $controller = $chain->next($self, $params, $chain);
    $request = isset($params['request']) ? $params['request'] : null;
    $action = $params['params']['action'];
    $publicActions = isset($controller->publicActions) ? (array) $controller->publicActions : [];

    if (!in_array($action, $publicActions) && !Auth::check('default', $request)) {
        return function() use ($request) {
            return new Response(['status' => 401]);
        };
    }

    return $controller;
});

Bulk of the AngularJS

app = angular.module "App", ["ui.router"]

app.constant "AUTH_EVENTS",
    authenticated: "auth-authenticated"
    unauthorized: "auth-unauthorized"
    forbidden: "auth-forbidden"

app.config [
    "$httpProvider"
    "$stateProvider"
    "$urlRouterProvider"
    ($httpProvider, $stateProvider, $urlRouterProvider) ->

        $httpProvider.interceptors.push [
            "$injector",
            ($injector) ->
                $injector.get "AuthInterceptorFactory"
        ]

        $urlRouterProvider
        .otherwise "/home"

        $stateProvider
        .state "login",
            controller: "AuthController"
            controllerAs: "Auth"
            url: "/login"
            templateUrl: "./partials/login.html"
        .state "home",
            controller: "HomeController"
            controllerAs: "Home"
            url: "/home"
            templateUrl: "./partials/home.html"

]

app.run [
    "$rootScope"
    "$state"
    "AUTH_EVENTS"
    "AuthFactory"
    ($rootScope, $state, AUTH_EVENTS, AuthFactory) ->

        $rootScope.$on AUTH_EVENTS.authenticated, ->
            $state.go "home"

        $rootScope.$on AUTH_EVENTS.unauthorized, ->
            $state.go "login"

        $rootScope.$on "$stateChangeStart", (event, toState) ->
            if toState.name isnt "login" and not do AuthFactory.check
                do event.preventDefault
                $rootScope.$broadcast AUTH_EVENTS.unauthorized

]

app.factory "AuthInterceptorFactory", [
    "$rootScope"
    "$q"
    "AUTH_EVENTS"
    ($rootScope, $q, AUTH_EVENTS) ->
        responseError: (response) ->
            statuses =
                401: AUTH_EVENTS.unauthorized
                403: AUTH_EVENTS.forbidden
            $rootScope.$broadcast statuses[response.status], response
            $q.reject response
]

app.factory "SessionFactory", [
    "$http"
    "$q"
    ($http, $q) ->

        get: ->
            deferred = do $q.defer
            $http
            .get "api/session.json"
            .success (data) ->
                deferred.resolve data
            .error ->
                deferred.reject "Unable to get session."
            deferred.promise

        create: (key, value) ->
            deferred = do $q.defer
            data =
                key: key
                value: value
            $http
            .post "api/session.json", data
            .success (data) ->
                if data.success is undefined
                    deferred.reject "Unable to create session."
                else
                    do deferred.resolve
            .error ->
                deferred.reject "Unable to create session."
            deferred.promise

        remove: (key) ->
            deferred = do $q.defer
            $http
            .delete "api/session.json?key=" + key
            .success (data) ->
                if data.success is undefined
                    deferred.reject "Unable to delete session."
                else
                    do deferred.resolve
            .error ->
                deferred.reject "Unable to delete session."
            deferred.promise

]

class SessionService

    key: null

    data: {}

    constructor: (@$q, @$rootScope, @AUTH_EVENTS, @SessionFactory) ->
        do @get

    get: ->
        deferred = do @$q.defer
        get = do @SessionFactory.get
        get.then(
            (data) =>
                @key = data.key
                @data = data.data
                if @data.user
                    @$rootScope.$broadcast @AUTH_EVENTS.authenticated
                do deferred.resolve
            (reason) =>
                deferred.reject reason
        )
        deferred.promise

    write: (key, value) ->
        deferred = do @$q.defer
        create = @SessionFactory.create key, value
        create.then(
            =>
                @data[key] = value
                do deferred.resolve
            (reason) =>
                deferred.reject reason
        )
        deferred.promise

    read: (key) ->
        if @data[key] is undefined then null else @data[key]

    remove: (key) ->
        deferred = do @$q.defer
        remove = @SessionFactory.remove key
        remove.then(
            =>
                delete @data[key]
                do deferred.resolve
            (reason) =>
                deferred.reject reason
        )
        deferred.promise

    destroy: ->
        @key = null
        @data = {}

app.service "SessionService", [
    "$q"
    "$rootScope"
    "AUTH_EVENTS"
    "SessionFactory"
    SessionService
]

app.factory "AuthFactory", [
    "$http"
    "$q"
    "$rootScope"
    "AUTH_EVENTS"
    "SessionService"
    ($http, $q, $rootScope, AUTH_EVENTS, SessionService) ->

        login: (credentials) ->
            deferred = do $q.defer
            $http
            .post "api/users/login.json", credentials
            .success (data) ->
                if data.user
                    writeSession = SessionService.write "user", data.user
                    writeSession.then ->
                        $rootScope.$broadcast AUTH_EVENTS.authenticated
                        do deferred.resolve
                else
                    deferred.reject "Unable to login."
            .error ->
                deferred.reject "Unable to login."
            deferred.promise

        logout: ->
            deferred = do $q.defer
            $http
            .get "api/users/logout.json"
            .success (data) ->
                if data.success
                    do SessionService.destroy
                    $rootScope.$broadcast AUTH_EVENTS.unauthorized
                    do deferred.resolve
                else
                    deferred.reject "Unable to logout."
            .error ->
                deferred.reject "Unable to logout."
            deferred.promise

        check: ->
            not not SessionService.read "user"

]

Execute a function on ANY state reload/page refresh (UI-router)?

I need to call a function when ANY state is reloaded. Essentially, if the user refreshes the browser, I need to call something. Is there any way to do this without modifying EVERY state with $state.reload()?

I CAN put a controller on index.html which contains all the views/states if this would help.

Changing super-navbar-buttons titles

New to AngularJS in Supersonic/Steroids/Appgyver

I know this is not working, but are there some variants that would work:

<super-navbar-button side="left">
    {{ titleButtonLeft  }}
</super-navbar-button>
<super-navbar-button side="right">
    {{ titleButtonRight }}
</super-navbar-button>

while

$scope.titleButtonLeft = "Left"
$scope.titleButtonRight = "Right"

Alternatively, change the title by code on super-navbar-buttons without removing and adding them.

Can't seem to access the buttons specifically with, for example:

supersonic.ui.navigationBar.buttons.right[0]

or

supersonic.ui.views.current.navigationBar.buttons.left[0]

even though they should reside somewhere therein, according to:

http://ift.tt/1EWjBGT

Any suggestions?

AngularJS double ng-repeat

I'm working on accordion group and have two ng-repeat. Outer one repeats weeks from current week to a specific date. Inner repeats working hours sever days in each week.

function expand(week.id) is to call database and prepare data for variable "hour".

My problem is that when I click on one accordion-heading to show data in week#1, the rest of all other weeks(accordions) also show the same data, which makes this process very slow.

How could I just render the trs under the heading where I clicked? E.g My scenario is when I click on heading of week#1, only trs under week#1 are rendered.

Could anyone help me with this?

  <accordion-group   ng-repeat="week in weeks">
        <accordion-heading >
            <span ng-click="expand(week.id)">{{week.firstday}}--{{week.lastday}}</span>
        </accordion-heading>
        <table class="table table-striped">
            <thead>
            <tr>
                <th>Task</th>
                <th>Sun</th>
                <th>Mon</th>
                <th>Tue</th>
                <th>Wed</th>
                <th>Thu</th>
                <th>Fri</th>
                <th>Sat</th>
                <th>Total</th>
            </tr>
            </thead>
            <tbody id={{week.id}}>
            <tr ng-repeat="hr in hour">

                <td> <select class="form-control input-sm" ng-disabled="false"><option value="hr.task_name">{{hr.task_name}}</option></select></td>
                <td><input type="number" min="0" ng-model="hr.sun" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.mon" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.tue" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.wed" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.thu" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.fri" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.sat" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><span class="form-control">{{hr.sun+hr.mon+hr.tue+hr.wed+hr.thu+hr.fri+hr.sat}}</span></td>
            </tr>
            </tbody>
        </table>
         </accordion-group>

AngularJS, Browserify and module loading

Alright, I have no clue. I searched the internet for like 3 days now and couldn't find any example on how to use Browserify in combination with AngularJS and Gulp. Yes there are examples but they all show that simple 'hello world' app structure nobody will use in the end anyway. They all write their little controllers inside the main app.js file. No modular setup. And the modular setups I found, well .. they include all the files by hand in the index.html file.. sigh (sorry for my tone).

What i try to achieve is to autoload all my application files but it just doesn't work. What do i need to do to include my controller files? Isn't that what browserify is for? Why isn't it working?

The first answer will probably be: you need to require() the files. But how? I tried require('myApp.mainController'); as well as require('src/features/main/main-controller.js') with the result of:

Error: No Module found.

If someone can point me in the right direction, please help me! :). Thanks in advance! The necessary info is below the line.


Project structure

|project
|-builds
| |-development
| |-production
|-src
| |-components
| |-features
| | |-main
| | | |-main-ctrl.js
| | | |-main.html
| | |-dashboard
| | | |-dashboard-ctrl.js
| | | |-dashboard.html
| |-app.js
| |-app.scss
| |-index.html

app.js

require('angular');
require('angular-ui-router');

var app = angular.module('myApp', [
  'ui.router',
  'myApp.mainController'
]).config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/');

  $stateProvider
    .state('main', {
      url: '/',
      templateUrl: 'src/features/main/main.html',
      controller: 'mainController'
    })
    .state('dashboard', {
      url: '/dashboard',
      templateUrl: 'src/features/dashboard/dashboard.html',
      controller: 'dashboardController'
    })
}]);

main-ctrl.js

angular.module('myApp.mainController', [])

  .controller('mainController', ['$scope', 'Main', function($scope, Main) {
    $scope.message = Main.message;
}]);

gulpfile.js

gulp.task('js', function() {
  return browserify({
    entries: 'src/app.js',
    debug: true
  })
    .bundle()
    .pipe(gulp.dest('builds/development'))
    .pipe(connect.reload());

});

How to set class to first item in ng-repeat that has been sorted with orderBy?

I have a list of items, which comes in unsorted, I use orderBy to sort by name alphanumerically.

<li class="ticker-li"
    ng-repeat="ticker in tickers | orderBy:'ticker'"
    ng-class="{'selected':ticker.selected}">

Now in my controller this is how I'm currently setting the first items selected class:

var vs = $scope;
vs.tickers = data;
vs.tickers[0].selected = true;

^ This worked perfectly until I needed to add the orderBy so that items appear by alpha order:

enter image description here

I found this answer here, however it locks the first item to always have the class.

Modifying my code a bit, I was able to have other buttons gain that class on click, however the $first item still stayed with the class.

ng-class="{'selected':$first || ticker.selected}"

enter image description here

How should the code either in the markup or controller need to be updated to fix this issue?

Angular module won't display data

Pretty new to angular so forgive me. I am trying to work with chart.js to display some data I am pulling off of a webservice. I have tested that the $http.get() works by putting the data in a table, plus console logs. The issue I am having is when using these chart js templates the data is always in the html, obviously I wanted to put it in a js file. So I included the ng-app and ng-controller but it still wont work:

<html>

  <head>
    <script data-require="jquery@*" data-semver="2.1.3" src="http://ift.tt/16ygW8q"></script>
    <script data-require="angular.js@*" data-semver="2.0.0-alpha.20" src="http://ift.tt/1DRvsRh"></script>
    <script data-require="chart.js@*" data-semver="0.2.0" src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myapp" ng-controller="MainCtrl">
    <div id="canvas-holder">
            <canvas id="chart-area" width="500" height="500"></canvas>
        </div>
        <button id="randomizeData">Randomize Data</button>

  </body>

</html>

There isn't much to the html, which Is why I am wondering why it isn't working?

I made a plunker with everything and it worked up until I added the angular.module().controller() stuff. Any ideas? Thanks.

cordovaSQLite retrieving data slowly using ionic framework

I am making an application using the ionic framework and I am using sqlite to store a list of about 150 rows. Each row has two attributes, ID and Name.

Now I am retrieving this data using a database factory which runs a query.

It works, however when I test it on an my Galaxy Tab 3 the list takes about 5-10 seconds to load and once it it loaded the list it super laggy scrolling through the list items.

Here's my controller

.controller('ActionSearchCtrl', function($scope, ActionSearchDataService, DBA, $cordovaSQLite){

    var tablet = true;
    var query = "select action FROM actions;";


    $scope.items = []; 

    $scope.runSQL = function(){
        DBA.query(query).then(function(result){
            $scope.items = DBA.getAll(result);
        });
    }; 

    if(tablet){$scope.runSQL()};

Here's my Database Factory

.factory('DBA', function($cordovaSQLite, $q, $ionicPlatform) {
  var self = this;

  // Handle query's and potential errors
 self.query = function (query, parameters) {
    parameters = parameters || [];
    var q = $q.defer();

    $ionicPlatform.ready(function () {
      $cordovaSQLite.execute(herbsDatabase, query, parameters)
      .then(function (result) {
        q.resolve(result);
      }, function (error) {
        console.warn('I found an error');
        console.warn(error);
        alert(error.message);
        q.reject(error);
      });
    });
    return q.promise;
  }

  // Proces a result set
  self.getAll = function(result) {
    var output = [];
    for (var i = 0; i < result.rows.length; i++) {
      output.push(result.rows.item(i));
    }
    return output;
  }


  // Proces a single result
  self.getById = function(result) {
    var output = null;
    output = angular.copy(result.rows.item(0));
    return output;
  }
  return self;
})

So the query returns about 150 entries which I need all on one page (I've looked into infinite scrolling and pagination but my client wants all the items on one page so this is not an option. From what I've read, 150 entries shouldn't be too slow in terms of watchers as I am using ng-repeat for the list items to display. If anyone has a way I can display this many items using the cordovaSQLite plugin to make the list function quicker let me know! at the moment the list is pretty much unusable, I've tried it on other devices too and it has the same result.

I've also tried creating about 200 dummy objects in the controller (without making a call to the db to get data) and the performance is fine. That's why I am thinking it's an SQLite performance issue. This is my first post on here so apologies if I am not clear enough.

Angularjs Push does not work

I want to push an element in my html interface using angularjs, this element appears only when I refresh the url.

this is a portion of my html code :

   <nav class="navbar-default navbar-side" role="navigation"  ng-         controller="createController">
         <li ng-repeat="project in projects" id="proj" >
                <a  style="background: #AFAFAF"> <i ng-click="remove(project.id)" class="fa fa-fw fa-trash-o"></i>
                   {{project.name}}
                    <ul>

this is the push in my controllers:

        $scope.projects.push({"idProject": idp, "name": namep, 'path':  directory});

How to send multiple checkbox value using Angular post method to PHP?

I'm new to Angular and I don't know to send multiple checkbox value to PHP (Server-side).

Code: http://ift.tt/1EPc8YB

HTML

<form name="EnqFrm" ng-app="EnqFrm" ng-controller="EnqController" ng-submit="save()">
<label>Class Days:</label>
<input name="chkweek" ng-model="formData.chkweek.Mo" type="checkbox">Mo
<input name="chkweek" ng-model="formData.chkweek.Tu" type="checkbox">Tu
<input name="chkweek" ng-model="formData.chkweek.We" type="checkbox">We
<input name="chkweek" ng-model="formData.chkweek.Th" type="checkbox">Th
<input name="chkweek" ng-model="formData.chkweek.Fr" type="checkbox">Fr
<input name="chkweek" ng-model="formData.chkweek.Sa" type="checkbox">Sa
<button id="btnSubmit" class="btn btn-default">SUBMIT</button>

AngularJS:

/* ANGULAR JS */
var weeksknm;
var app = angular.module('EnqFrm', []);
app.controller('EnqController', function ($scope, $http) {

    $scope.formData = {};

    $scope.save = function () {
        var url = "Controller/enq_postadmin.php";
        $http.post(url, $scope.formData).success(function (da) {
            alert(da);
            $scope.formData = "";
        });
    };

});

PHP:

<?php if ($_SERVER['REQUEST_METHOD']=='POST') {
    $data=file_get_contents("php://input");
    $inp=json_decode($data);
    echo $txtWeek=$inp->chkweek;
}
else {
    echo'try agian';
}
?>

Angular-leaflet-directive Custom HTML popup

I'm attempting to create a custom popup while using the angular-leaflet-directive. I'm opening the popup from the leaflet.draw on:create event. Here:

map.on('draw:created', function(e) {

    layer = e.layer;
    drawnItems.addLayer(layer);
    var newComment = "Enter Comment";
    var newID = "ID";
    var newGeoJsonFeat = layer.toGeoJSON();
    newGeoJsonFeat.properties = {"comment":newComment, "id":newID};
    console.log(newGeoJsonFeat);

    onEachFeature(newGeoJsonFeat,layer);
    layer.openPopup();
});

Then I'm using @blackjid's logic as seen here: http://ift.tt/1EPc6Qv to bind the custom popup

function onEachFeature(feature, layer) {
    // Create get the view template
    var popupContent = '<div ng-include="\'partials/popup_newfeat.html\'"></div>';
    console.log("assigning popup");

    // Bind the popup
    // HACK: I have added the stream in the popup options
    layer.bindPopup(popupContent,{
      closeButton: false,
      maxHeight: 300,
      feature: feature
    });
};

$scope.$on('leafletDirectiveMap.popupopen', function(event, leafletEvent){

  // Create the popup view when is opened
  var feature = leafletEvent.leafletEvent.popup.options.feature;

  var newScope = $scope.$new();
  newScope.stream = feature;

  $compile(leafletEvent.leafletEvent.popup._contentNode)(newScope);
});

Long story short, Everything works fine except the popup container isn't resizing properly to fit the new content. The height seems right, but the width is off.

I tried using:

.leaflet-popup-content {
    width:auto !important;
}

Which will probably suffice, but this causes the popup anchor to shift to the bottom left of the popup for some reason. AutoPan is also broken when clicking near the top of the map.

Does anyone know where and how I can get popup.update() to fire? I believe thats what needs to happen, but I don't know where to implement it. I've tried calling it after layer.openPopup() like so:

    onEachFeature(newGeoJsonFeat,layer);
    layer.openPopup();
    layer.getPopup().update();
});

But that doesn't seem to do anything. Any help is greatly appreciated!