2

I'm looking for most secure way to call PHP file from Javascript and after It return back data from PHP to Javascript.

I'm developing Javascript game. I need to call PHP file to connect to databaase and select some data from database. This data should be passed to Javascript.

I've checked Chris Baker's answer here: Call php function from javascript

The javascript

 // handles the click event for link 1, sends the query
 function getOutput() {
   getRequest(
       'myAjax.php', // URL for the PHP file
        drawOutput,  // handle successful request
        drawError    // handle error
   );
   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;
 }
 // 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;
 }

The HTML

 <a href="#" onclick="return getOutput();"> test </a>
 <div id="output">waiting for action</div>

The PHP

 // file myAjax.php
 <?php
   echo 'hello world!';
 ?>

But I need to retrieve total 4 variables: 1 question and 3 answers, as per Chris answer It fetch only 1 echo.

My PHP file is like:

//some code
$questions->bind_result($question, $answer1, $answer2, $answer3);

while ($questions->fetch()) {
    echo $question;  
    echo $answer1;
    echo $answer2;
    echo $answer3;
}

My HTML + Javascript file:

<div class="question-area">

</div>
<div class="answers">
     <input type="button" class="btn" value="return getSuccessOutput();">   

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

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

I need to pass $question variable to .question-area and $answer1, $answer2, $answer3 to value of buttons. Could you help me to achieve It?

UPDATE

This is my connect.php, when I'm trying to refresh www.mywebsite/connect.php It most of times return nothing (blank page), after refreshing ~10 times It pick random data. What wrong with It? SQL query seems to be good, in phpMyAdmin working correctly.

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

while ($questions->fetch()) {
    $qa = array('question' => $question, 'a1' => $answer1, 'a2' => $answer2, 'a3' => $answer3);
    echo json_encode($qa);
}

If I pass var_dump($qa); inside while loop It always returning data. Something wrong with echo json_encode($qa)

Community
  • 1
  • 1
Infinity
  • 828
  • 4
  • 15
  • 41
  • 1
    You should send a JSON object. – SLaks Dec 05 '16 at 17:35
  • What do you mean by "safe"? – Jay Blanchard Dec 05 '16 at 17:42
  • @SLaks I've updated my question with problem. Something wrong with PHP file, while I'm using `json_encode($qa)`. Have you ideas? – Infinity Dec 05 '16 at 19:17
  • You must emit a single JSON object; you can't concatenate JSON. You probably want an array. – SLaks Dec 05 '16 at 19:23
  • @SLaks In my PHP file `$qa` is array which contains 1 question and 3 answers. I'm trying to refresh my `connect.php` file and sometime It returning array, sometime It return nothing. – Infinity Dec 05 '16 at 19:30
  • You can't `echo` multiple arrays and get valid JSON. – SLaks Dec 05 '16 at 19:33
  • @SLaks But I'm trying to echo only 1 array, I've tried to pass `echo json_encode($qa);` out of while loop, but still the same problem. Where I'm trying to echo multiple arrays? – Infinity Dec 05 '16 at 19:37
  • Oops; I missed your `LIMIT 1`. You shouldn't use a loop. – SLaks Dec 05 '16 at 19:40
  • Use your browser's dev tools to figure out what's going on. – SLaks Dec 05 '16 at 19:40
  • @SLaks I've also tried to remove loop, but in this case always I get `{"question":null,"a1":null,"a2":null,"a3":null}`. Browser DEV tools do not show any errors in any case - with loop or without. – Infinity Dec 05 '16 at 19:43
  • @SLaks I got warning at DEV consoloe: `DOM7011: The code on this page disabled back and forward caching.` Maybe that could be issue, It's something with https? Have you any ideas? – Infinity Dec 05 '16 at 20:00

1 Answers1

1

Put your data in an array and echo the json.

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

Now in your JS you will have access to an object with the same keys.

nerdlyist
  • 2,842
  • 2
  • 20
  • 32
  • Thank you for an answer, how could I access It via JS now? I'm trying like that `document.btn1.innerHTML = a1;`, but I got an error: `Uncaught ReferenceError: a1 is not defined` – Infinity Dec 05 '16 at 17:45
  • @Infinity: This gives you an object with properties. You need to use those properties (you also need to parse the JSON). Use your debugger to see what your Javascript has. – SLaks Dec 05 '16 at 17:46
  • @SLaks I've tried to use `var test = JSON.parse(qa); document.btn1.innerHTML = test;` but in this case I got an error: `(index):10 Uncaught ReferenceError: qa is not defined`. If I'm using `var test = JSON.parse(a1); document.btn1.innerHTML = test;` I'm receive an error: `Uncaught ReferenceError: a1 is not defined`. What's wrong with parsing JSON? – Infinity Dec 05 '16 at 17:52
  • @Infinity are you using Jquer? If you are then you could simplify a lot of this code. If not then please remove the tag. I will update my answer once you let me know what I can use. – nerdlyist Dec 05 '16 at 17:53
  • @Infinity you would not have a `qa` you have `responseText`. – nerdlyist Dec 05 '16 at 17:54
  • @nerdlyist Yes, I'm using `JQuery`. – Infinity Dec 05 '16 at 17:55
  • 1
    @Infinity: Then you should call `$.getJSON()`. – SLaks Dec 05 '16 at 18:08
  • @SLaks coud you help me to use `$.getJSON()` in my case? – Infinity Dec 05 '16 at 18:18
  • You're looking for the documentation. – SLaks Dec 05 '16 at 18:19
  • You can use the `$.getJSON()` or just `$.ajax()` http://api.jquery.com/jquery.ajax/ it is vastly more simplistic and you do not need to decode what is in success. – nerdlyist Dec 05 '16 at 18:26
  • @nerdlyist I've updated my question with problem. Something wrong with PHP file. – Infinity Dec 05 '16 at 19:11
  • @Infinity this update looks different then the initial question posed. It is good practice keep question specific and not long running. This one appears to be answered as you are getting the multiple elements as requested. – nerdlyist Dec 05 '16 at 20:11
  • @nerdlyist I got this problem after I'm using your provided PHP. – Infinity Dec 05 '16 at 20:18
  • @Infinity can you do a `var_dump($qa);`? – nerdlyist Dec 05 '16 at 20:21
  • @nerdlyist sure, I've done It before, var_dump always return array data, whereas echo json_encode only 1/10~ you could test It here: https://www.eurokos.lt/zaidimai/kaledinis/connect7.php – Infinity Dec 05 '16 at 20:24
  • It looks like you are having an encoding issue. Can you try `json_encode($qa, JSON_UNESCAPED_UNICODE)` – nerdlyist Dec 05 '16 at 20:41