Home:ALL Converter>How to call PHP file from Javascript and return data from PHP back to Javascript

How to call PHP file from Javascript and return data from PHP back to Javascript

Ask Time:2016-12-06T01:29:39         Author:Infinity

Json Formatter

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)

Author:Infinity,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/40979973/how-to-call-php-file-from-javascript-and-return-data-from-php-back-to-javascript
yy