Passing js variable to php string

I need a little help im trying to list the js variable in the url that php is handling using file_get_contents. I'm not sure where to start doing this.

<script type="text/javascript">
var js_variable = appl+goog+fb+mfst+nflx;
</script>

<?php
$ticker = js_varable_here;
$file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re');

?>

any advice is appreciated, as I told them in the dark on this.

+3
source share
3 answers

Here is an example using jquery.

JavaScript:

<script type="text/javascript">
  var js_variable = appl+goog+fb+mfst+nflx;
  $.post("/somephp.php", {ticker: js_variable}, function(data) {
    // returned from php
  });
</script>

PHP:

 <?php
   $ticker = $_POST['ticker'];
   $file = file_get_contents("http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re");
 ?>
+1
source

Turning around on what Jashwant says ...

PHP is a server language that runs behind the scenes. Javascript is the client side that runs and executes the code on the local client machine (i.e., through the browser).

AJAX ( JavaScript XML), HTTP- . , AJAX .

jQuery ajax. .: http://api.jquery.com/jQuery.ajax/

, .

+1

Here is how you can do it with jquerys post () and then return json, you can build the result as you expect, output it to the php part, or you can use jquery to loop with each () through the result.

<?php
if($_SERVER['REQUEST_METHOD']=='POST'
   && isset($_SERVER['HTTP_X_REQUESTED_WITH'])
   && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){

    if(!empty($_POST['s'])){

        $ticker = $_POST['s'];
        $file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s='.$ticker.'&f=soac1p2ghjkj1re');

        header('Content-Type: application/json');
        echo json_encode(array('result'=>$file));
    }else{
        echo 'Request not allowed!';
    }
    die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" charset="utf-8"></script>
<script>
var js_variable = "appl+goog+fb+mfst+nflx";

$.post('this_script.php',{s: js_variable}, function(data) {
  $('#divResult').replaceWith('<div id="divResult">'+ data.result +'<div>');
});
</script>
</head>
<body>

<div id="divResult"><div>
</body>
</html>
+1
source

All Articles