Can I do this with ajax?

I want to get a little more familiar with ajax,
I created a simple form which connect to a cars table (mysql)

http://php_class.teamluke.net/ajax/
Currently, im using PHP to add elements to the dropdown list

<option>Select</option>
<?php
 $sql = "SELECT make FROM cars";
 foreach ($conn->query($sql) as $row){
 echo "<option value=".$row['make'].">$row[make]</option>"; 
 }
 ?>
</select>

Isnt that pretty intense of the server?
I think it would be much more efficient If I used AJAX to accomplish the same thing
Is that right?
How do do it?

The server will still have the same work to do, but it will appear smoother because the user can already see the main page while the additional content is getting loaded in the background. Just put your code in a separate PHP file, like e.g.

<select id="makes">
  <option disabled>Select</option>
</select>
// myScript.php
<?php

// Establish db connection etc., then
$sql = "SELECT make FROM cars";
$rows = $conn->query($sql);

foreach ($rows as $row) {
  echo '<option value="' . $row['make'] . '">' . $row['make'] . '</option>'; 
}

You can then populate the select with AJAX like

const xhr = new XMLHttpRequest

xhr.addEventListener('load', () => {

  if (xhr.status === 200) {
    document
      .getElementById('makes')
      .innerHTML += xhr.responseText
  }
})

xhr.open('GET', 'myScript.php')
xhr.send()
2 Likes

Adding to what @m3g4p0p said. Another major benefit in this specific case, is that you’re taking your business logic out of your view. Your business logic should never mix your business logic with your view, it makes code vulnerable and unmaintainable. But there are plenty of PHP ways to fix that.

ok, made a few changes and got it to work!
http://php_class.teamluke.net/ajax/populate_select.php
I had a hard time understanding your script as I’m not too advanced when it comes to this, but heres what I did…
(let me know if its ok?)
Heres my PHP in fillSelect.php

<?php
include("db/conn.php");
$sql = "SELECT id,make FROM cars";
$rows = $conn->query($sql);
echo "<option>Select</option>";
foreach ($rows as $row) {
  echo '<option value="' . $row['id'] . '">' . $row['make'] . '</option>';
}
?>

I also changed the script to a function & run it when the page loads

<script>

window.onload = loadList;

function loadList() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("makes").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "fillSelect.php", true);
  xhttp.send();
}
</script>

im sort of confused mawburn,
I understand that the view is the page with my form, but what do you mean by business logic? And how can it be fixed via PHP?
Did I fix it using AJAX instead?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.