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)

11
  • 1
    You should send a JSON object. Commented Dec 5, 2016 at 17:35
  • What do you mean by "safe"? Commented Dec 5, 2016 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? Commented Dec 5, 2016 at 19:17
  • You must emit a single JSON object; you can't concatenate JSON. You probably want an array. Commented Dec 5, 2016 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. Commented Dec 5, 2016 at 19:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

16 Comments

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: 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 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 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.
@Infinity: Then you should call $.getJSON().
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.