0

Problem is that json_encode returns me array from PHP to Javascript. How could I extract values from an array?

I have simple connect.php file:

$questions = $con->prepare("
    SELECT Question, Answer1, Answer2, Answer3
    FROM Questions AS q
    ORDER BY RAND()
    LIMIT 1
"); 
$questions->execute();

$questions->bind_result($question, $answer1, $answer2, $answer3);
$questions->store_result();
$questions->fetch();

$qa = array('question' => $question, 'a1' => $answer1, 'a2' => $answer2, 'a3' => $answer3);

echo json_encode($qa, JSON_UNESCAPED_UNICODE);

It returns me data in following:

{"question":"This is my question?","a1":"test1","a2":"test2","a3":"test3"}

I need to pass those variables to index.html to Javascript.

// handles the click event for link 1, sends the query
function getSuccessOutput() {
  getRequest(
      'connect.php', // demo-only URL
       drawOutput,
       drawError
  );
  return false;
}

// handles the click event for link 2, sends the query
function getFailOutput() {
  getRequest(
      'invalid url will fail', // demo-only URL
       drawOutput,
       drawError
  );
  return false;
}

// handles drawing an error message
function drawError () {
    var container = document.getElementById('output');
    container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;   
    $("#btn1").attr('value', responseText[a1]);
    $("#btn2").attr('value', responseText[a2]);
    $("#btn3").attr('value', responseText[a3]);

}
// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                return false;
            }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req .readyState == 4){
            return req.status === 200 ? 
                success(req.responseText) : error(req.status)
            ;
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}      

I have div with id question where should I add question from json array.

And I have 3 buttons with id's: btn1, btn2, btn3 I need to change values of each button with a1, a2, a3 from json array.

        <div id="question">

        </div>
        <div class="question-answers">
            <div class="button">
                <input type="button" id="btn1" class="btn" value="">   

                <input type="button" id="btn2" class="btn" value="return getSuccessOutput();">   

                <input type="button" id="btn3" class="btn" value="return getSuccessOutput();">   
                <span id="output" class="output">000</span>
            </div>
        </div>

If I'm using something like that:

    var container = document.getElementById('output');
    container.innerHTML = responseText;  

It add text like: {"question":"This is my question?","a1":"test1","a2":"test2","a3":"test3"}

How could I extract values from array? like:

var q = This is my question; var a1 = test1; var a2 = test2; var a3 = test3

I've tried to use like that, but It not change values of buttons:

    $("#btn1").attr('value', responseText[a1]);
    $("#btn2").attr('value', responseText[a2]);
    $("#btn3").attr('value', responseText[a3]); 

Have you ideas how to change It?

UPDATE

I've tried to use in following, but not worked too.

$.getJSON("t.php", function(responseText){
        $.each(responseText, function(i, field){            

       $("#btn1").attr('value', responseText[a1]);
       $("#btn2").attr('value', responseText[a2]);
       $("#btn3").attr('value', responseText[a3]); 

        });
    });

UPDATE 2

I've also tried these, but not worked (nothing happenning):

function drawOutput(responseText) {
    alter(this.responseText);
    $.getJSON("t.php", function(responseText){
        $.each(responseText, function(i, field){
            var container = document.getElementById('output');
            var theObject = JSON.parse(responseText);
            container.innerHTML = theObject.a1;         

        });
    });

}

Also I've tried this one, but the same issue, nothing happened:

function drawOutput(responseText) {
    alter(this.responseText);
    var container = document.getElementById('output');
    var theObject = JSON.parse(responseText);
    container.innerHTML = theObject.a1;  

}

UPDATE 3

Strange, but If I use:

function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;
}

It adding to output text:

{"question":"This is my question?","a1":"test1","a2":"test2","a3":"test3"}

But If I'm using in following, nothing happening:

function drawOutput(responseText) {
    var container = document.getElementById('output');
    var theObject = JSON.parse(responseText);
    container.innerHTML = theObject.a1;  

}
Infinity
  • 828
  • 4
  • 15
  • 41
  • Have you considered using $.get function? You can specify that the data type will be JSON. My guess is that you are getting a JSON string that needs to be decoded. – Jordan Soltman Dec 06 '16 at 18:08
  • I've read this topic, but I couldn't make It successfully. – Infinity Dec 06 '16 at 18:09
  • @JordanS Thank you for reply, I've updated my question with $.getJSON that I've already tried. – Infinity Dec 06 '16 at 18:11
  • @Taplar so I need to use something like that: `var theObject = JSON.parse(responseText);` and after It I can access like `theObject.a1`? – Infinity Dec 06 '16 at 18:13
  • The $.each is wrong. Pull your inner code out of that. – Jordan Soltman Dec 06 '16 at 18:13
  • @JordanS I've tried to remove each, but not worked, nothing happens. Updated my question with code what I've tried at `Update 2` – Infinity Dec 06 '16 at 18:30
  • @Taplar I've updated my question with `Update 2` what I've tried, but unsuccessfully. – Infinity Dec 06 '16 at 18:30
  • @Taplar Yes, I meant alter, I've added It by mistake, now removed, tried all the methods what I mentioned, but still the same. – Infinity Dec 06 '16 at 18:40
  • Can you console.log(responseText) – Jordan Soltman Dec 06 '16 at 18:40
  • @JordanS I've added `console.log(responseText);` this inside `drawOutput` method, but nothing changed. – Infinity Dec 06 '16 at 18:42
  • @Taplar I've updated my question with part `UPDATE 3` do you see any error in this part of code? – Infinity Dec 06 '16 at 18:50
  • I think you are missing the point. If you put a console.log() in that method as the first thing, or `degugger;`, and you do not see that log in the console or the browser does not run the debugger, then either you have a javascript parse error that is causing your script to not run at all, or that method is not being executed, in which case the issue is else where. – Taplar Dec 06 '16 at 18:52
  • I've added `console.log(responseText);` as first thing in method and tried both ways from `UPDATE 3`. But I don't see any log in browsers dev tools console. If I use `function drawOutput(responseText) { console.log(responseText); var container = document.getElementById('output'); container.innerHTML = responseText; }` It gives me array's output, but still there is no any log in console. – Infinity Dec 06 '16 at 18:58

0 Answers0