سؤال

The overall idea is drawing a graph of somebody's scores in a div. I've got a button which when clicked runs the graph drawing function. I also have another function which retrieves data from my database using a switch statement as the function is shared with the other buttons.

My data retrieval function:

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

Runs getdata.php and returns values into a blank 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);
?>

Receives POSTed div id (profile_scores), gets data from database, switches to second case. Now here is where the problem is, I'm not sure how to pass the

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

values back to the original page and get them to show up in the graph where

/* correct value */

and

/* incorrect value */

are.

Graph drawing function:

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);
};

This function is what is ran when the user clicks the button so it calls the getdata function and then draws the graphusing the values received from getdata.php.

Any help is appreciated :)

هل كانت مفيدة؟

المحلول

I am totally not sure what you are asking for but here is my guess.

If you want the $result fetched in case 2 from database on your page. Then you can use JSON to pass PHP array to Javascript and then do the rest of the job. Like suppose this is the case no 2 of your switch statement

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

And in your ajax response do this

$.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
    }
});

This way you got your PHP array to javascript which was database result. Also I would like to suggest you to correct the Switch syntax. This won't make much difference but should be taken care so this is the correct syntax.

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

Note that I have put break; command inside Switch Case

نصائح أخرى

Your PHP code can encode the returning parameters in a (JSON-encoded) associative array. Then you can retrieve each of them separately via the keys from your ajax response and pass them around in your JavaScript code.

Try to use json.php to get json parsed string for javascript call. Download link: class.json.php

Changes in 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);
    };

Changes in 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); 
    // ----------------------------
?>

I hope it helps a bit.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top