在PHP和JavaScript之间传递数据?

时间:2014-04-19 21:53:19

标签: javascript php jquery google-visualization

总体思路是绘制一个div中某人得分的图表。我有一个按钮,当点击它时运行图形绘制功能。我还有另一个函数,它使用switch语句从我的数据库中检索数据,因为该函数与其他按钮共享。

我的数据检索功能:

var getdata = function(button_id) {
    $.ajax({
        type: "POST",
        url: "../scripts/getdata.php",
        dataType: "html",
        data: {id: button_id},
        success: function(result){
            $("#profilebox").html(result);
        }
    });
};

运行getdata.php并将值返回到空白div。

getdata.php:

<?php
session_start();
$switchcase = $_POST['id'];
$email = $_SESSION['user']['email'];
//connect to database here
$result=mysqli_query($con,"SELECT * FROM users WHERE email = '$email'");
switch ($switchcase) {
    case "profile_home":
        while($row = mysqli_fetch_array($result)) {
        echo $row['username'] . "'s Profile<br><br>";
        echo "Name: " . $row['firstname'] . ' ' . $row['lastname'] . "<br><br>";
        echo "Things I like:<br>";
        echo $row['like'] . "<br><br>";
        echo "Things I dislike:<br>";
        echo $row['dislike'] . "<br><br>";
        echo "Other Sports:<br>";
        echo $row['sports'];
    };
        break;
    case "profile_scores":
        while($row = mysqli_fetch_array($result)) {
        $row['correct'];
        $row['incorrect'];
    };
        break;
    case "profile_merits":
        //CODE GOES HERE;
        break;
    case "profile_help":
        //CODE GOES HERE;
        break;
    case "profile_edit":
        //CODE GOES HERE;
        break;
}
mysqli_close($con);
?>

接收POSTed div id(profile_scores),从数据库获取数据,切换到第二种情况。现在问题出在这里,我不知道如何通过

        $row['correct'];
        $row['incorrect'];

返回原始页面并让它们显示在图表

/* correct value */

/* incorrect value */

图形绘制功能:

function drawVisualization() {

    getdata("profile_scores");

    // Create and populate the data table.
    var data = google.visualization.arrayToDataTable([
        ['', 'Correct', 'Incorrect'],
        ['Scores',  /* correct value */, /* incorrect value */],
    ]);

    var options = {
            'title': 'Total Scores Overall',
            'width': 600,
            'height': 400,
            'hAxis': {title: ''},
            'backgroundColor': 'transparent'
    };
    // Create and draw the visualization.
    new google.visualization.ColumnChart(document.getElementById('profilebox')).
    draw(data, options);
};

此功能是用户单击按钮时运行的函数,因此它调用getdata函数,然后使用从getdata.php接收的值绘制图形。

感谢任何帮助:)

3 个答案:

答案 0 :(得分:0)

您的PHP代码可以在(JSON编码的)关联数组中编码返回参数。然后,您可以通过ajax响应中的键分别检索它们,并在JavaScript代码中传递它们。

答案 1 :(得分:0)

我完全不确定你要求的是什么,但这是我的猜测。

如果您希望从页面上的数据库中 $ 2 中获取 $ result 。然后,您可以使用JSON将PHP数组传递给Javascript,然后完成剩下的工作。就像假设你的switch语句没有2那样

case "profile_scores":
{
    $row = $result->fetch_array(MYSQLI_NUM);
    echo json_encode($row);
    break;
}

在您的ajax响应中执行此操作

$.ajax({
    type: "POST",
    url: "../scripts/getdata.php",
    dataType: "html",
    data: {id: button_id},
    success: function(result){
        console.log(result);
        console.log(JSON.parse(result));
        var phparray = JSON.parse(result);
        var correct = phparray[12];   //<---This will return 100 
        var incorrect = phparray[13];  //<---This will return 10
        //I Dont know which one is your correct or incorrect column number but you can have an idea now
    }
});

这样你就得到了你的PHP数组到javascript,这是数据库结果。另外,我建议您更正Switch语法。这不会产生太大的影响,但应该小心,这是正确的语法。

switch($switchcase)
{
   case "case1":
   {
       //Code to go
       break;
   }
   case "case2":
   {
       //Code to go
       break;
   }
   case "case3":
   {
       //Code to go
       break;
   }
}

请注意,我已将 break; 命令放在切换案例

答案 2 :(得分:0)

尝试使用json.php为javascript调用获取json解析字符串。 下载链接:class.json.php

Javascript的变化:

   var getdata = function(button_id) {
        $.ajax({
            type: "POST",
            url: "../scripts/getdata.php",
            dataType: "json", // html -> json
            data: {id: button_id},
            success: function(result){

                $("#profilebox").html(result.html);

                return result;
            }
        });
    };

    function drawVisualization() {

        var data = getdata("profile_scores");

        // Create and populate the data table.
        var data = google.visualization.arrayToDataTable([
            ['', 'Correct', 'Incorrect'],
            ['Scores',  data.correct, data.incorrect],
        ]);

        var options = {
                'title': 'Total Scores Overall',
                'width': 600,
                'height': 400,
                'hAxis': {title: ''},
                'backgroundColor': 'transparent'
        };
        // Create and draw the visualization.
        new google.visualization.ColumnChart(document.getElementById('profilebox')).
        draw(data, options);
    };

getdata.php中的更改:

<?php
    // INCLUDE JSON
    // ----------------------------
    include_once("class.json.php");
    $json = new JSON();

    $coreJSON = array();
    // ----------------------------

    session_start();

    $switchcase = $_POST['id'];

    $email = $_SESSION['user']['email'];

    // call as result.html in javascript
    $coreJSON['html'] = ""; 
    // call as result.correct in javascript
    $coreJSON['correct'] = "";
    // call as result.incorrect in javascript
    $coreJSON['incorrect'] = "";

    //connect to database here
    $result=mysqli_query($con,"SELECT * FROM users WHERE email = '$email'");
    switch ($switchcase) {

        case "profile_home":  // <- CHANGES

            while($row = mysqli_fetch_array($result)) {

                $coreJSON['html'].= <<<EOF
                    {$row['username']}'s Profile<br /><br />
                    Name: {$row['firstname']} {$row['lastname']}<br /><br />
                    Things I like:<br>
                    {$row['like']} <br /><br />
                    Things I dislike:<br />
                    {$row['dislike']}<br /><br />
                    Other Sports:<br />
                    {$row['sports']}
EOF;
            }
            /* Start the closing EOF at the beginning of the line, and delete all spaces and tabs after the semicolon. Next code must start in a new line.*/

            break;

        case "profile_scores":

            while($row = mysqli_fetch_array($result)) {
                $coreJSON['correct'].= $row['correct']; // <- CHANGES
                $coreJSON['incorrect'].= $row['incorrect']; // <- CHANGES
            }

            break;
        case "profile_merits":
            //CODE GOES HERE;
            break;
        case "profile_help":
            //CODE GOES HERE;
            break;
        case "profile_edit":
            //CODE GOES HERE;
            break;
    }

    mysqli_close($con);

    // CLOSING AND CONVERTING
    // ----------------------------
    $encodeJSON = $json->encode($coreJSON);

    header('Content-Type: text/json'); // text/plain is good to
    header('Content-Length: '.strlen($encodeJSON));

    die($encodeJSON); 
    // ----------------------------
?>

我希望它有所帮助。