ngIf doesn't update with variable - php

I have a very simple ng-if construction using two MD buttons and one AngularJS scope variable isPlaying. However, the ng-if doesn't seem to work along with the variable. I can see the variable changing as I click the buttons, using console tools, however no changes to the DOM. Strangely enough the ng-if does seem to trigger when I hover other Angular components, such as buttons in the main nav.
HTML/MD/PHP:
<md-button class="md-icon-button" ng-if="!isPlaying" ng-click="play()" aria-label="Play">
<md-icon md-svg-src="<?php echo get_stylesheet_directory_uri(); ?>/img/icon/ic_play_arrow_black_24px.svg"></md-icon>
</md-button>
<md-button class="md-icon-button" ng-if="isPlaying" ng-click="pause()" aria-label="Pause">
<md-icon md-svg-src="<?php echo get_stylesheet_directory_uri(); ?>/img/icon/ic_pause_black_24px.svg"></md-icon>
</md-button>
JS:
$scope.play = function () {
player.playVideo();
$scope.isPlaying = true;
}
$scope.pause = function () {
player.pauseVideo();
$scope.isPlaying = false;
}

The problem was being caused by a function wrapped inside a timeout block. I replaced the setTimeout with $timeout and everything started working fine:
$scope.isPlaying = false;
$scope.videoTime = 0;
function onPlayerStateChange() {
console.log(player);
if (player.getPlayerState() === 1)
$scope.isPlaying = true;
else
$scope.isPlaying = false;
$timeout(onPlayerStateChange, 500);
}

Related

How to use a PHP function for multiple calls within the same PHP page?

I am trying to use a php function to get the prices of a tola (11.664 grams) at an order status page. The function uses a php page 'priceApi4CurCtrl.php' that fetches the price data from a website using an external API. My function is as follows:
function tolaPrice($cur_pick) {
require('priceApi4CurCtrl.php');
if($cur_pick == 'pkr') {
$tola_price = $bitprice_pkr*10*11.664;
return $tola_price;
} elseif($cur_pick == 'usd') {
$tola_price = $bitprice_usd*10*11.64;
return $tola_price;
} elseif($cur_pick == 'aed') {
$tola_price = $bitprice_aed*10*11.64;
return $tola_price;
}
}
// Succeeds for the first call as under
$cur_pick = 'pkr';
echo tolaPrice($cur_pick);
// Fails for the second call as under
$cur_pick = 'aed';
echo tolaPrice($cur_pick);
The function works fine for the first call using echo tolaPrice($cur_pick). However, it fails all subsequent calls and hence I am unable to complete the order status of second and subsequent orders.
I am not sure how to work around this.
Instead of trying to wrap an if else loop in a function, I simply calculated the prices in a separate file named tola_price.php as follows:
include('priceApi4CurCtrl.php');
$tola_price_pkr = $bitprice_pkr*10*11.664;
$tola_price_usd = $bitprice_usd*10*11.64;
$tola_price_aed = $bitprice_aed*10*11.64;
And then called the tola_price.php within my script with if else loop as follows:
require_one('tola_price.php');
if($cur_pick == 'pkr') {
$tola_price = $tola_price_pkr;
} elseif($cur_pick == 'usd') {
$tola_price = $tola_price_usd;
} elseif($cur_pick == 'aed') {
$tola_price = $tola_price_aed;
}
And then used the prices to build further script.
Thanks to those who offered help

Issue with redirect() when using conditional to evaluate multiple form buttons

So I've built a small conditional to evaluate which button is pressed in my form (as there are 2). This works fine and fires off the correct method and writes the appropriate data to the DB, however my redirect is not working. It saves() to the DB and then simply stays on the page designated as the POST route.
I suspect the problem has something to do with my conditional and the use of $this.
Here is my check_submit method:
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
$this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
$this->invoice_complete();
}
}
Here is one of the 2 methods which I am currently testing:
public function invoice_add_item()
{
$input = Request::all();
$invoice_items = new Expense;
$invoice_items->item_id = $input['item_id'];
$invoice_items->category_id = $input['category'];
$invoice_items->price = $input['price'];
$invoice_items->store_id = $input['store'];
if(Input::has('business_expense'))
{
$invoice_items->business_expense = 1;
}
else{
$invoice_items->business_expense = 0;
}
$invoice_items->save();
return redirect('/');
}
Perhaps there is a better way of handling this in my routes(web) file, but I'm not sure how to go about this.
You should add the return to the check_submit() method. Something like
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
return $this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
return $this->invoice_complete();
}
}
Better yet, you should probably return a boolean on invoice_add_item() and based on that, redirect the user to the correct place (or with some session flash variable with an error message)

Bootstrap - How to save the state of collapse in a SESSION

I use Bootstrap and I would like to save the current state of collapse (open or close) in a session variables PHP (not in a cookie).
Could you give me :
- an example code to save the current state in a session variable PHP.
- and an example code to open or not the collapse (depends on the state stored in the session variable) when the page loads.
Thank you very much
First of all, do you really need to store it into session? Does some PHP script work with that value?
Both cases:
You must store somewhere in JavaScript variable the state of collapsed items:
var collapsed = false; // the default value
$('.collapse').on('hide.bs.collapse', function () {
collapsed = true; // on hide, collapsed is true
})
$('.collapse').on('show.bs.collapse', function () {
collapsed = false; // on show, collapsed is false
})
Yes, i need to store it into session:
At each request, you must add the collapsed variable and pass it for example trhough GET method:
$('a').on('mousedown', function() {
var c = collapsed ? 1 : 0;
var href = $(this).attr('href');
if(href.indexOf('?') !== -1) {
$(this).attr('href', href + '&collapsed=' + c);
else {
$(this).attr('href', href + '?collapsed=' + c);
}
});
And somehow save it to session
$_SESSION['collapsed'] = $_GET['collapsed'];
No, i don't need to store into session:
Most modern browsers now have localStorage variable, which is something like session in JavaScript.
Save into variable (in event handlers for example):
if(typeof(Storage)!=="undefined")
{
window.localStorage.setItem('collapsed', collapsed); // saves with no expiration
code.sessionStorage.setItem('collapsed', collapsed); // saves until browser is closed
}
else
{
// Sorry! No Storage support..
}
Load in some startup script:
if(typeof(Storage)!=="undefined")
{
collapsed = window.localStorage.getItem('collapsed'); // again choose one
collapsed = code.sessionStorage.getItem('collapsed');
if(collapsed) {
$('.collapse').collapse('show');
} else {
$('.collapse').collapse('hide');
}
}
else
{
// Sorry! No Storage support..
}
There may be other solutions, but these are the only i can think about. :)
All codes require jQuery
I would do something like this on the PHP side of things. It allows for storing and retrieving the state of multiple ID:s. Session handling is not included; the functions assume there is an active session going. Also, the functions are static since there is no real need to instantiate a class. And it makes for simpler usage.
class Collapse
{
public static function set_state($id = null, $state = null)
{
if ($id === null || $state === null || !is_numeric($state)) {
return false;
} else {
$state = ($state == 0 ? 0 : 1);
$_SESSION['collapse_state'][$id] = $state;
}
}
public static function state($id = null)
{
if ($id === null) {
return false;
} else {
return $_SESSION['collapse_state'][$id];
}
}
}
// --- Sets the state for chosen ID.
Collapse::set_state('info', 0);
// --- Returns the state of the ID.
Collapse::state('info');
Use this class together with the JavaScript proposed by Tomáš Tomíík Blatný and you'll be able to save your states. I'd probably use POST instead of GET though, to make the URL:s look a bit nicer. This can be done by populating a hidden form field or by sending an AJAX request to a PHP-script that only handles the collapse states.

PHP dynamic link list breaks ajax

I have this list of things generated from an array, where the array value maps to the array key, which maps to a query in the database. Now the problem I'm facing is that when this list is included in my ajax portion, it only works for one click before the page refreshes. What gives?
I'm using the HTML5 History API method to change the url upon clicks by the href="" portion of the link.
I'm somewhat new to jQuery, which is odd since I'm a front end developer primarily but I just never got the time to catch up, but my link list breaking this code just doesn't make sense to me.
$("a[rel='ajax']").click(function(e){
//e.preventDefault();
pageurl = $(this).attr('href');
$.ajax({url:pageurl+'?rel=ajax',success: function(data){
$('#ajax')
.load(pageurl + ' #resultati');
}});
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
The links are generated using this function in PHP, I'm using the laravel framework if that makes any difference.
public static function filterlink ($filter, $what)
{
if (URI::segment(2) == 'make')
{
$first = URI::segment(3);
$next = URI::segment(4);
}
else
{
$first = URI::segment(2);
$next = URI::segment(3);
}
// what == 0 is the filter, what == 1 is the +filter. This reffers to the link being created.
switch (substr($first, 0, 1))
{
case ' ': // example.ex/make/[+]current starts with a plus sign.
if($what == 0)
//new no+ filter.
{
return HTML::link('make/'.self::slug($filter.'/'.$first), $filter, array('rel' => 'ajax'));
// example.ex/make/+current => example.ex/make/newfilter/+current
}
elseif($what == 1)
//new +filter
{
return HTML::link('make/+'.self::slug($filter), $filter, array('rel' => 'ajax'));
// example.ex/make/+current+replaced+by+newfilter
}
break;
default:
if($what == 0)
// new no+ filter.
{
if(!empty($next))
{
return HTML::link('make/'.self::slug($filter.'/'.$next), $filter, array('rel' => 'ajax'));
}
else
{
return HTML::link('make/'.self::slug($filter), $filter, array('rel' => 'ajax'));
}
}
elseif($what == 1 && (!empty($first)))
{
return HTML::link('make/'.self::slug($first.'/+'.$filter), $filter, array('rel' => 'ajax'));
}
elseif($what == 1 && (empty($first)))
{
return HTML::link('make/+'.self::slug($filter), $filter, array('rel' => 'ajax'));
}
}
}
I've tried putting my link lists outside the ajax field, which keeps the ajax flow going without any boring page refreshes, but my link urls don't update, obviously, and I'm only able to construct one-ended links, breaking the pages dual filter functionality.
Any help would be great.
If you're actually loading HTML content with links that you want to be AJAX friendly, then you'll need to use .on so that the new links also get taken over by your jQuery function.
$(document).on('click',"a[rel='ajax']",function(e) {
Working sample here:
http://jsfiddle.net/hansvedo/cJW54/
Just a quick thought, what about placing preventDefault where the pushState function is? Or even just uncommenting it where it is? preventDefault prevents the normal linking action from happening.
if(pageurl!=window.location){
e.preventDefault();
window.history.pushState({path:pageurl},'',pageurl);
}

is there a way to exchange variables between JavaScript and PHP

I have build a website in Drupal, and I am trying to create a fun way to get members involved with the site by building a userpoint system, the system is all in place, but I'm trying to make a shop where they can buy 'titles'.
This is the script I wrote for the shop, with a bit of error handling, but I'm stuck with a problem,
In my JavaScript, I have the function buyitem( ) with 2 variables, which I want to use in my PHP functions which check everything in my database, is there a way to get those variables from JavaScript to the PHP function I wrote without going to an external PHP file?
<?php
include "php-scripts/DBConnection.php";
$con = getconnection();
mysql_select_db("brokendi_BD", $con);
function getKarma()
{
$result = mysql_query("SELECT * FROM userpoints WHERE uid='getUID()'");
$row = mysql_fetch_array($result);
$currentkarma = (int)$row['points'];
return $currentkarma;
}
function getUID()
{
global $user;
if ($user->uid)
{
$userID=$user->uid;
return $userID;
}
else
{
header('Location: http://brokendiamond.org/?q=node/40');
}
}
function hasRole($roleID)
{
$usersid = getUID();
$returnValue = false;
$result = mysql_query("SELECT * FROM users_roles");
while ($row = mysql_fetch_array($result))
{
if ($row['uid'] == $usersid)
{
if ($row['rid'] == $roleID)
{
$returnValue = true;
break;
}
}
}
return $returnValue;
}
function enoughKarma()
{
if ( getKarma() >= $requiredKarma)
{
return true;
}
else
{
return false;
}
}
function buyRole()
{
$currentKarma = getKarma();
$newkarma = $currentKarma - $requiredKarma;
$userID = getUID();
mysql_query("UPDATE userpoints SET points = '$newkarma' WHERE uid='$userID'");
mysql_query("INSERT INTO users_roles (uid, rid) VALUES ($userID, $roleID)");
}
?>
<script type="text/javascript">
buyItem(1 , 0);
function SetStore()
{
}
Function buyItem(itemID,reqKarma)
{
if (<?php enoughKarma(); ?>)
{
<?php buyRole(); ?>
}
else
{
alert('You do not have enough Karma to buy this title.');
}
}
</script>
PHP is a server side script and javascript is a client side, server side scripts are executed before the page loads, meaning your javascript cannot pass variables to it, BUT you can how ever pass php variables to your js.
Best solution in your case is to use ajax to send those variables to php and have the php set variables on it's side, this doesn't quite solve your problem, but with some creativity in your code you can make it happen.
you can either reload the page (which I doubt is what you'r looking for) or make an ajax call to your php script sending the 2 variables.
if you're using jQuery, this should give you an idea of how to do this

Categories