Naphstor
Naphstor

Reputation: 2496

can we pass a variable containing our url in jquery $.get() from a php file

hi i have a graph created from a .csv file using the jquery $.get(). but currently i am passing hardcoded file name as first argument to my get() method. My function is in a file named index.js and is like this

    $(document).ready(function() { 
        $.get('myproject.csv', function(data) { ..... } 
    ....... });

but what i want is to pass a variable which contains the file name so that it can have any file name instead of 'myproject.csv'

    $.get($filename, function(data) { 

where $filename could be any filename passed. i don't have much idea about jquery and all so not sure.

Now the main thing is that i have a .phtml file where i have this javascript file incorporated as inline script. So I have no idea how to pass the variable from this .phtml file to this javascript file. My .phtml file:

      <head>.......</head>
      <body>
      <script type="text/javascript" src="/PFFd02/public/media/js/modules/appone/index/index.js"></script>      // this is where i need to pass my variable. 
      ...........
      </body>

any help???

Upvotes: 0

Views: 872

Answers (3)

Naphstor
Naphstor

Reputation: 2496

Thanks to you all. I figured out a simple way of passing the variable from php file to my js.

What i did was i created a view variable in my controller file and assigned it a string containing div tag as follows:

    $this->view->filename = "<div id=\"filename\" style=\"display:none\">".$file."</div>";

where $file is the variable that contains my filename which i have to pass to javascript. Now in my zend view i did something like this:

    <?php echo $this->filename ?>

which is making the filename available to my view where i have to run that javascript. Then in my javascript function i initialized a variable like this:

        var file = $('#filename').text();
        $.get(file, function(data) {

and so i got the variable passed from php file to my javascript function.

Upvotes: 0

Marc B
Marc B

Reputation: 360742

$.get(<?php echo json_encode($filename) ?>, function(data) {

using json_encode ensures that any JS metacharacters in the filename won't "break" your script.

Upvotes: 1

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

This should work:

var filename=<?=json_encode($filename)?>;
$.get(filename, function(data) { 

This sets the Javascript variable filename to the value of the PHP variable $filename, and calls $.get(filename).

Upvotes: 2

Related Questions