1

The following code is a method to grab the number of rows from a server.

<?php 

  //retrieving number of rows from server

  $num_check = $handler->query("SELECT * FROM table");

  $num_to_display = $num_check->rowCount();


?>

I'm using a counter widget written in Javascript to provide a customer facing counter that displays the number of rows found (numbers of entry in the table). The counter was written by chap named Chris Nanney. The section of the source that I am using is below.

<script>

  $(function(){

    //changed value to be a PHP variable.

    var myCounter = new flipCounter('myCounter', {value: myVar, inc: 0, pace: 1000, auto: true});

    $('#style-switcher a').on('click', function(e){
      e.preventDefault();
      $("#myCounter").removeClass().addClass('flip-counter '+$(this).data('style'));
      $('#style-switcher a').removeClass('active');
      $(this).addClass('active');
    });

//the following lines I probably don't need and will delete. But as they are in use now, I felt it necessary to include them

    $('#inc_slider').slider({
      range: 'max',
      value: 123,
      min: 0,
      max: 1000,
      slide: function(event, ui){
        $('#inc_value').text(ui.value);
        myCounter.setIncrement(ui.value);

        if (ui.value == 0) myCounter.setAuto(false);
        else myCounter.setAuto(true);
      }
    });

    // Pace
    $('#pace_slider').slider({
      range: 'max',
      value: 1000,
      min: 400,
      max: 2000,
      step: 100,
      slide: function(event, ui){
        myCounter.setPace(ui.value);
        $("#pace_value").text(ui.value);
      }
    });

  });
</script> 

The trouble I am running into is changing the PHP variable $number_to_display to a Javascript variable that can be parsed by the parameters of the function specifically the value field. Some debugging showed that the number echoes properly from the PHP end so I doubt the PHP is the issue. More likely the issue is in converting it to Javascript. So far I have attempted to change it over to JS within the function itself, and some treasure hunting on other forums gave me the following stub which was my most recent attempt at passing it.

<script language="javascript">

  / <![CDATA[

      var myVar = "<?php echo $num_to_display; ?>;""
      alert(myVar);

  // ]]>
</script>

Granted I'm not really JS savvy, I was wondering if anyone has some best practices for moving between PHP and JS. Am I not properly declaring the variable or passing it properly to the function?

EDIT:

Ok, thanks to the great help so far, I have the varibales parsing correctly. My question is, when I pass it to the function

$(function(){

var myCounter = new flipCounter('myCounter', {value: myVar, inc: 0, pace: 1000, auto: true});

It still is not passing in properly. Am I missing single or double quotation marks or something like that?

9
  • 1
    Is the second " character at the end of the line var myVar = "<?php echo $num_to_display; ?>;"" a typo? Commented Mar 6, 2015 at 5:11
  • It was. Thanks for the correction. Sadly it wasn't that simple... :( Commented Mar 6, 2015 at 5:15
  • Take a look at this: stackoverflow.com/questions/7605505/… emitting JSON is probably the best way to do this from PHP still Commented Mar 6, 2015 at 5:15
  • 1
    “The following code is a method to grab the number of rows” – and it is a bad one. You should have the database COUNT the records in the select statement directly. Commented Mar 6, 2015 at 5:49
  • Good point. Care to elaborate more on why the original was weak? @CBroe EDIT: I see you made an edit as I was submitting this. Thanks for the info! Commented Mar 6, 2015 at 5:50

3 Answers 3

1

No need for the CDATA. This should work:

<script>
    var myVar = "<?= $num_to_display ?>";

    // if it's an object
    var myObject = <?= json_encode($someArray) ?>;
</script>
Sign up to request clarification or add additional context in comments.

6 Comments

Cool. Thanks for the update. I seem to be having trouble passing that to the other script. Will the other script be able to pull this variable since it is in separate tags, or do I need to declare this with the master script?
@AndrewL If it's on the same page it doesn't matter what script tag it's in.
Ok I got the variables parsing correctly, but when I pass it to the function, $(function(){ var myCounter = new flipCounter('myCounter', {value: myVar, inc: 0, pace: 1000, auto: true}); It doesn't parse. Am I declaring the variable correctly? are there any added single or double quotations needed?
After declaring myVar, can you log it in the web console? console.log(myVar);
Now that is interesting. I did a document read out line for debug, and when I put the log right above it, it doesn't do the print. Curios? @kylehyde215
|
0

This code will works var a = <?php json_encode($variable) ?>;

In some cases echo $variable works. But the proper method is to json_encode($Array)

If its numeric use echo $value

Comments

0

I would put the data directly on the element the counter is invoked from which judging by your example is #myCounter. I don't know what type of structure it is, but let's say for this example it's just an empty div:

<div id="myCounter" data-counter-value="<?php echo $num_to_display ?>"></div>

So then we just need to make our creation of the counter take the new data attributes into account:

function initFlipCounter(id, options) {
   var $counter = $(id),
       o = $.extend({}, {value: $counter.data('counterValue'), inc: 0, pace: 1000, auto: true}, options||{});

   // we used a jQuery selector with our wrapper so get the raw
   // ID since flipCounter uses document.getElementById
   return new flipCounter($counter.attr('id'), o);
}

You could even expand this to take into account all the options. It also lets you override the ones on the element.

You usage would now be like this:

// basic only use the value from the element and defaults in the init func
var myCounter = initFlipCounter('#myCounter');

// override some stuff
var myCounter = initFlipCounter('#myCounter', {auto: false, pace: 500});

// even override value
var myCounter = initFlipCounter('#myCounter', {value: 365, pace: 3000});

Fiddle example: http://jsfiddle.net/2kpogjjj/

3 Comments

I think we are on the right track here. One question though, the JS you mentioned function (initFlipCounter...) where do you embed that? I put it above the other function, but does it need to be inside the main function? @prodigitalson
This depends on where you want to use it. You cant really invoke it successfully until after the DOM is ready since it uses jQuery, but you might want it defined outside of that closure or defined from within with window.initFlipCounter = function (id, options) { /* definition */ }; so its available anywhere.
Also since it uses jQuery and flipCounter you would want those included/defined before you define this function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.