Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Jun 2012
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Use javascript variable to increment php array

    I am in need of incrementing through a php array with the javascript variable "i" instead of where i have 0 in the $members array call

    PHP Code:
    var i = 0;
        while (i<5)
          {
            if (<?php echo json_encode($members[0]['department']); ?> ==  "CHE"){
                    contacts.push({"NAME":"Sir Saula","TITLE":"John","CONTACT":"bab","RESEARCH":"Ph.D."});        
            }
          i++;
            
          }

  • #2
    Regular Coder
    Join Date
    Apr 2012
    Location
    St. Louis, MO
    Posts
    985
    Thanks
    7
    Thanked 101 Times in 101 Posts
    How about looping in PHP (inside <script type="text/javascript"> tags) instead of JavaScript, and include JS code as needed?

    Then, again.. this is not tested, but..

    Code:
     if (<?php echo json_encode($members[?>i<?php]['department']); ?> ==  "CHE"){ 
    ^_^

    If anyone knows of a website that can offer ColdFusion help that isn't controlled by neurotic, pedantic jerks* (stackoverflow.com), please PM me with a link.
    *
    The neurotic, pedantic jerks are not the owners; just the people who are in control of the "popularity contest".

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,553
    Thanks
    78
    Thanked 4,382 Times in 4,347 Posts
    You can't.

    PHP code can *NOT* see any JavaScript variables. Period.

    The only ways to send a javascript variable (or any client-side value) to PHP are:
    -- post a <form>
    -- use a querystring with a php URL
    -- use AJAX
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #4
    Senior Coder
    Join Date
    Sep 2010
    Posts
    1,996
    Thanks
    15
    Thanked 233 Times in 233 Posts
    The only way you can really do that is to have php rewrite the array in javascript, and then let javascript use it. The best way to do that is have javascript declare an array and then write code for php to use javascript 'push' to add elements to the array, because it prevents confusion in the case of mixed data types.
    myarray =[];
    loop over this;
    {
    echo 'myarray.push('.$data[i].');';
    }


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •