Question:

Is there anyway i can send something in php to Javascript?

by  |  earlier

0 LIKES UnLike

Is this valid?

<input type="button" value=" \/ " name="B1down2" onclick="movedown(<? echo $rows2['totalNum']?>)">

And than in my javascript...

function findSum(totalNum)

 Tags:

   Report

1 ANSWERS


  1. I don&#039;t think it&#039;s doing what you&#039;re trying for.  I think you mean to reference the php array &quot;rows2&quot; using a JavaScript index of &quot;totalNum&quot;, which is not possible.  I&#039;m not sure what you&#039;re doing exactly, but you probably want to make that purely JavaScript from the looks of things.  As it stands (suppose that $rows2[&#039;totalNum&#039;] was 5 when you ran the php script), you&#039;re outputting JavaScript code that&#039;ll look like:

    ... onclick=&quot;movedown(5)&quot; ...

    And if that&#039;s what you&#039;re looking for, that&#039;s fine, but I think you&#039;re really looking to change that number dynamically? One way to do this might be to print out the JavaScript:

    var rows2 = new Array();

    &lt;? php

    foreach ($rows2 as $key =&gt; $val) {

      echo &quot;rows2[$key] = &#039;$val&#039;;\n&quot;;

    }

    ?&gt;

    Then, you&#039;ve got your rows2 array in JavaScript, and can reference it there as you otherwise might.  By the time that JavaScript starts, your php program is already done, so JavaScript can&#039;t access any of its values, functions, etc.  The only way around that would be to build up an Ajax library for your JavaScript to call on the fly, with a backend in php.  But that would probably be unnecessarily slow if you&#039;re just trying to access array values or something.

    [edit]

    Ok, so you&#039;re trying to print out the maximum value of your php array called $rows2? I&#039;m not a big php person myself, but I believe you can do this with $rows2[], which returns the maximum integer value in the array.  Of course, that doesn&#039;t really tell you *how many* things are in the array, just the maximum integer value, which is probably the same thing, assuming you&#039;re filling it up with 0, 1, 2, 3, etc.

    Really, though, you want to fix this in your JavaScript.  If you&#039;re getting a non-existent DOM element or something, trap for it.  Checking your boundaries within JavaScript will be more reliable than counting on your PHP code to be correct.  Plus, it&#039;s more re-usable!

    [/edit]

    DaveE

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.