Welcome to the LimeSurvey Community Forum

Ask the community, share ideas, and connect with other LimeSurvey users!

Can I write Ajax in Twig Template?

  • OngJunYew
  • OngJunYew's Avatar Topic Author
  • Offline
  • Junior Member
  • Junior Member
More
3 years 2 months ago #210951 by OngJunYew
Can I write Ajax in Twig Template? was created by OngJunYew
In this thread, I wanted to ask can I put AJAX in the Twig Templates. Because I wanted to show data from databases in the interface as text. I have written the AJAX code below in the Twig Templates but seem there is no result in text.

HTML in Twig Template:

<p id="data"></p>

AJAX in Twig Template:

<script>
    
    var ajax = new XMLHttpRequest();
    var method = "GET";
    var url = "data.php";
    var asynchronous = true;
    
    ajax.open(method, url, asynchronous);
    // sending ajax request
    ajax.send();
    
    // receiving responses from data.php
    ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        //converting JSON back to array
        var data = JSON.parse(this.responseText);
        console.log(data);
        
        // html value for <tbody>
        var html = "";
        //looping through the data
        for (var a = 0; a < data.length; a++)
        {
            var NRIC = data[a].NRIC;
            
            //appending at html
            html += "<p>" + NRIC + "<p>";
        }
        // replacing the <p>
        document.getElementById("data").innerHTML = html;
    }
};
</script>

PHP in data.php:

<?php
$con=mysqli_connect("localhost","root","ongjunyew","survey");

$result = mysqli_query($con,"SELECT NRIC FROM lime_tokens_20 Where token='abc123'");

$data = array();
while ($row = mysqli_fetch_assoc($result))
{
    $data[] = $row;
}

echo json_encode(data);



 
The topic has been locked.
  • DenisChenu
  • DenisChenu's Avatar
  • Offline
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
3 years 2 months ago #210955 by DenisChenu
Replied by DenisChenu on topic Can I write Ajax in Twig Template?
1. var url = "data.php"; surely false : better set a complete url
2. Why not use api.jquery.com/Jquery.ajax/

Assistance on LimeSurvey forum and LimeSurvey core development are on my free time.
I'm not a LimeSurvey GmbH member, professional service on demand , plugin development .
I don't answer to private message.
The topic has been locked.

Lime-years ahead

Online-surveys for every purse and purpose