0

I am writing a inline-PHP snippet that is grabbing values out of a query.
Here is the code I use:

$(".menu-price-slider").each(function(index) {
       console.log(timeToMinutes("<?php echo $query_results['d'.(++$d).'_o']?>"));
});

This code is giving me $query_results[1] every time, what I want is a counter that is increasing everytime this code gets executed.
$query_results[1], $query_results[2], $query_results[3], $query_results[4], etc.

Thanks in advance

Tompina
  • 726
  • 1
  • 9
  • 25
  • 1
    Is timeToMinutes a PHP method, or is it a Javascript method? – Chris Forrence Jan 27 '15 at 15:20
  • 1
    Make sure `$d` is initialized (presumeabe to 0) before, and in same scope as, your executions. – Eric Jan 27 '15 at 15:23
  • What are you actually trying to do? You are not showing much code context here. Is there some sort of a loop in play? You do realize that one PHP has written that out into the javascript parameter in the source code it is totally static (in other words PHP doesn't run in your browser)? – Mike Brant Jan 27 '15 at 15:30
  • @MikeBrant I updated the code alittle so you get the context – Tompina Jan 27 '15 at 15:36
  • Mike's point is that echoing PHP instructions from javascript is a waste of time, because the javascript is executed in the browser, after PHP has already run on the server. – Brian Warshaw Jan 27 '15 at 15:49
  • possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Beat Jan 27 '15 at 15:52

2 Answers2

2

OK. If you are expecting to get a different value for parameter of timeToMinutes with each iteration, then you are mistaken. I think you need to get a better understand for how PHP and javascript work. PHP is only working at the time of page render. One the page is rendered, javascript would work within the browser. If you didn't put all the values you need from PHP into the javascript source, you have no way to get to them after the page is rendered, short of using AJAX techniques you pull the data in after initial page render.

I might suggest a technique like this:

// pre-populate array of values from PHP
// here PHP $query_results must be numerically indexed array
// there should be equal number of elements in this array and
// .menu-price-slider DOM elements
var timeToMinutesParams = <?php echo json_encode($query_results); ?>;

// iterate through DOM elements,
// using index of element to get matching value from timeToMinutesParams
$(".menu-price-slider").each(function(index) {
       console.log(timeToMinutes(timeToMinutesParams[index]));
});
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
0

You could make a file initialize it with 0 if it does not exist and if it exists read from it and at the end increase the number in the file.

Vasspilka
  • 1,135
  • 1
  • 10
  • 22