简体   繁体   中英

JQUERY - store php variable and echo it in jquery script?

Is it possible to send the $data variable to the jquery script in the url: section to get the source from different php files ? (newbie programmer). I need to be able to do something like this for example:

var source =
            {
                 datatype: "json",
                 datafields: [
                     { name: 'timeserver', type: 'time'},
                     { name: 'val1', type: 'number'},

                ],

                url: '<?php echo $data; ?>.php',

                cache: false
            };


<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="jqwidgets/styles/jqx.base.css" type="text/css" />
    <script type="text/javascript" src="scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxcore.js"></script>
    <script type="text/javascript" src="jqwidgets/jqxchart.js"></script>    
    <script type="text/javascript" src="jqwidgets/jqxdata.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            // prepare the data
            var theme = 'classic';

            var source =
            {
                 datatype: "json",
                 datafields: [
                     { name: 'timeserver', type: 'time'},
                     { name: 'val1', type: 'number'},

                ],
                url: 'data.php',
                cache: false
            };      

           var dataAdapter = new $.jqx.dataAdapter(source,
            {
                autoBind: true,
                async: false,
                downloadComplete: function () { },
                loadComplete: function () { },
                loadError: function () { }
            });

         // prepare jqxChart settings
            var settings = {
                title: "Temperatura",
                showLegend: true,
                padding: { left: 5, top: 5, right: 5, bottom: 5 },
                titlePadding: { left: 90, top: 0, right: 0, bottom: 10 },
                source: dataAdapter,
                categoryAxis:
                    {
                        text: 'Category Axis',
                        textRotationAngle: 0,
                        dataField: 'timeserver',
                        formatFunction: function (value) {
                            return $.jqx.dataFormat.formatdate(value, 'HH:mm:ss');
                        },
                        showTickMarks: true,
                        tickMarksInterval: Math.round(dataAdapter.records.length / 6),
                        tickMarksColor: '#888888',
                        unitInterval: Math.round(dataAdapter.records.length / 6),
                        showGridLines: true,
                        gridLinesInterval: Math.round(dataAdapter.records.length / 3),
                        gridLinesColor: '#888888',
                        axisSize: 'auto'                    
                    },
                colorScheme: 'scheme05',
                seriesGroups:
                    [
                        {
                            type: 'line',
                            valueAxis:
                            {
                                displayValueAxis: true,
                                description: 'Temperatura',
                                //descriptionClass: 'css-class-name',
                                axisSize: 'auto',
                                tickMarksColor: '#888888',
                                unitInterval: 5,
                                minValue: 10,
                                maxValue: 50                          
                            },
                            series: [
                                    { dataField: 'val1', displayText: 'Temperatura' }
                              ]
                        }
                    ]
            };

            // setup the chart
            $('#jqxChart').jqxChart(settings);
        });
    </script>
    <style type="text/css">
</style> 
</head>
<body class='default'>
    <!-- <div class="flip3D"> 
         <div class="back">-->
         <div style="width:670px; height:400px" id="jqxChart">
         </div>
         <!--</div> 
         <div class="front"><div style="width:670px; height:400px" id="jqxChart"></div></div> 
     </div> -->
      <div class="flip3D"> 
<?php
// define variables and set to empty values
$data = $data1h = $data24h = $data7zile = $data1luna = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
   $data = test_input($_POST["gender"]); 
 }  
function test_input($data)
{
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>

<h2>Arhiva</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

   Select:
   <input type="radio" name="gender" value="data" >Curent
   <input type="radio" name="gender" value="data1h" >Ultima ora
   <input type="radio" name="gender" value="data24h" >Ultima zi
   <input type="radio" name="gender" value="data7zile" >Ultima saptamana
   <input type="radio" name="gender" value="data1luna" >Ultima luna
   <br><br>
    <input type="submit" name="submit" value="Submit"> 

</form>
<?php
echo json_encode($data);
?>
</div> 
</body>

If it's about that part:

url: '<?php echo $data; ?>.php'

Yes, that's possible.

var data = "<?php echo data; ?>";

The above line goes in your PHP template/View/Controller

usage in jQuery :

url : data + '.php'

The other answers might work, but they are NOT the right way to do this.

The proper way to do it is using json_encode .

var data = <?php echo json_encode($data) ?>;

Note that there are no quotes around the php statement. json_encode will escape characters specifically for javascript, and also it can handle different types as well as empty variables correctly.

Examples :

<?php
    $str = "Hello World";
    $nothing = null;
    $arr = ['apple', 'orange', 'banana'];
    $user = array(
        'name' => 'Rob',
        'age' => 42,
        'admin' => true,
    );
?>

<script type="text/javascript">
    var str = <?php echo json_encode($str) ?>,
        nothing = <?php echo json_encode($nothing) ?>,
        arr = <?php echo json_encode($arr) ?>,
        user = <?php echo json_encode($user) ?>;
</script>



// Results in all valid javascript variables
var str = "Hello World",
    nothing = null,
    arr = ["apple","orange","banana"],
    user = {"name":"Rob","age":42,"admin":true};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM