Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

A PHP script obtains data from a MySQL database and returns an array to javascript using JSON. I can get the results but I cannot get them to print them out individually.

The PHP code -

header('Content-type:application/json');

$link = @new mysqli(_HOST, _USER, _PASS, _DB); //constants 
if(mysqli_connect_errno())
{
    //failure
}
else
{

    //success

    $sqlQuery = "SELECT COL1, COL2 FROM TABLE"; //the query should return two
                                               //columns from every selected row
    $mix = array();                            //array to return using JSON

    $result = $link->query($sqlQuery);

    if ($result->num_rows <= 0)
    {
        //no data
    }
    else
    {
        while ($row = $result->fetch_assoc())       //fetch loop
        {
            $mix["C1"][] = $row['COL1'];        
            $mix["C2"][] = $row['COL2'];        
        }
    }

    $result->free();

    // Close connection
    $link->close();
}

print json_encode($mix); //this line wont show up in previous code formatting block for some reason.

The Javascript / jQuery code -

$.ajax({ // ajax call
        url: 'serv.php', // server page
        data: 'fetch=1', //ignore any data
        dataType: 'json', // server return type
        success: function(data) // on success
        {
                for (var i in data) {
                    $('#someDiv').append( i + " = " + data[i] + '<br>');
                }
        }
    });

The output, as expected is like this -

C1 = 1,2
C2 = A,B

What I want to accomplish is to put these data (1,2,A,B) inside a form table element. And to do that I need to pick the every element of C1 or C2 individually.

How can I accomplish this?

share|improve this question

1 Answer 1

I've found the solution myself.

The following ajax call works-

$.ajax({ // ajax call
    url: 'serv.php', // server page
    data: 'fetch=1', //ignore any data
    dataType: 'json', // server return type
    success: function(data) // on success
    {
            for (var i in data["C1"]) {
                $('#someDiv').append( i + " = " + data["C1"][i] + '<br>');
            }
            for (var i in data["C2"]) {
                $('#someDiv').append( i + " = " + data["C2"][i] + '<br>');
            }
    }
});

Instead of accessing the data, I've tried to access the indices inside data. It was so simple.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.