jquery - Sending an array from PHP to javascript

971

In the PHP file can anyone help me directly making a for loop where I don't know the number of rows that are going to be selected.

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "mydb";//database details
    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) 
    {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT * FROM mytable";
    $result = $conn->query($sql);
    $myarray = array();
    $index = 0;

    if ($result->num_rows > 0) 
    {
        // output data of each row
        while($row = $result->fetch_assoc()) 
        {
            $myarray[$index] = $row["firstname"];
            $index++;
            $myarray[$index] = $row["lastname"];
            $index++;
            $myarray[$index] = $row["email"];
            $index++;
        }
    } 
    else 
    {
        echo "0 results";
    }
    $conn->close();
?>

The Javascript code contains javascript of a search bar suggestion code and here i didn't mention the typeahead javascript file

var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
        var matches, substringRegex;

        // an array that will be populated with substring matches
        matches = [];

        // regex used to determine if a string contains the substring `q`
        substrRegex = new RegExp(q, 'i');

        // iterate through the pool of strings and for any string that
        // contains the substring `q`, add it to the `matches` array
        $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
            }
        });

        cb(matches);
    };
};

$('#the-basics .typeahead').typeahead({
    hint: true, //here i used typeahead js code though i didnt mentioned here
    highlight: true,
    minLength: 1
}, {
    name: 'states',
    source: substringMatcher(states)
});
875

Answer

Solution:

You can simplify the PHP a little bit here when you read in the values as you dont need to increase the index:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);//making a connection
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $myarray[] =$row["firstname"];
        $myarray[] =$row["lastname"];//storing in the array
        $myarray[] =$row["email"];
    }
} else {
    echo "0 results";
}
$conn->close();
?>

You could echo in the results to the Javascript where you require them,echo($myarray[0]) for example.

Your Javascript may look something like this:

var matches = <?php echo($myarray[0]); ?>
83

Answer

Solution:

There are 4 ways you can do to insert dynamic content to your javascript code.

  1. Make the javascript inline to your PHP page. That is, putting your js code inside<script> tags

  2. Make the dynamic js variables global and populate them in your php page. Your separate JS files will be able to read these global js variables.

  3. If you want to have a separate file for JS, you have to generate it everytime (because you cant have PHP code in javascript. The browser cannot interpret it, and the server cannot interpret it)
  4. If you want to force the server to interpret PHP code in JS files, add a handler so that .js is handler by the php interpreter (whether php module or php-cgi) see Clean links to PHP-generated JavaScript and CSS

People are also looking for solutions to the problem: PHP ignoring cookie

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.