Need PHP to grab a variable from external .js file

Discussion in 'PHP' started by BAM78, Jan 5, 2008.

  1. #1
    <script src="file.js" type="text/javascript" charset="utf-8">
    </script>

    Inside file.js is

    var a = "somedata"


    How do I make php echo the variable a from file.js?
     
    BAM78, Jan 5, 2008 IP
  2. kmap

    kmap Well-Known Member

    Messages:
    2,215
    Likes Received:
    29
    Best Answers:
    2
    Trophy Points:
    135
    #2
    <script src="file.js" type="text/javascript" charset="utf-8">

    </script >

    <script type="text/javascript" charset="utf-8">

    document.write(a);

    </script>
     
    kmap, Jan 5, 2008 IP
  3. BAM78

    BAM78 Peon

    Messages:
    115
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I need to make the
    var a = "somedata"
    a php variable I mean
     
    BAM78, Jan 5, 2008 IP
  4. kmap

    kmap Well-Known Member

    Messages:
    2,215
    Likes Received:
    29
    Best Answers:
    2
    Trophy Points:
    135
    #4
    are you using a form on that page

    Regards

    Alex
     
    kmap, Jan 5, 2008 IP
  5. BAM78

    BAM78 Peon

    Messages:
    115
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Nope no form
     
    BAM78, Jan 5, 2008 IP
  6. Millar

    Millar Peon

    Messages:
    334
    Likes Received:
    19
    Best Answers:
    0
    Trophy Points:
    0
    #6
    This wouldn't be reccomended as typically PHP serves the data to output JavaScript and HTML, not the other way round.

    However, if you want to take data from the user and do something with it (i.e. perform a PHP function on it) then you could use Ajax for this.

    PHP could never go on to echo this information though, it could only parse it, JavaScript would echo it.
     
    Millar, Jan 5, 2008 IP
  7. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #7
    
    
    //Get content
    $file = 'file.js';
    $f = fopen($file,'r');
    while($c = fread($f,10256547)){
    	$total .= $c;
    }
    fclose($f);
    
    //Find match and echo it
    preg_match('/.*var a="(.*)".*/iUs',$total,$result);
    print_r($result);
    
    PHP:
    Peace,
     
    Barti1987, Jan 5, 2008 IP