-1

This is my select option:

<form id="contact" action="insert_pre.php" method="post">
    <select id="mySelect" onchange="myFunction()">
      <option value="Audi">Audi</option>
      <option value="BMW">BMW</option>
      <option value="Mercedes">Mercedes</option>
      <option value="Volvo">Volvo</option>
    </select>
    <p id="textt"></p>
  </form>

Normally I would do something using Javascript:

<script>
function myFunction() {
  var x = document.getElementById("contact").value;
  document.getElementById("textt").innerHTML = "You selected: " + x;
}
</script>

How can I run a PHP function when the users changes the select option value? As I understand, one cannot run PHP from JS. But could AJAX be an solution? How would it look in that case? I want the users to still be on the same page.

Cyborg122
  • 7
  • 1
  • 1
    Yes, AJAX is the necessary solution here. – El_Vanja Nov 20 '20 at 20:26
  • @El_Vanja Could you please show an example for me on how I could do it? – Cyborg122 Nov 20 '20 at 20:29
  • [This](https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started) might be a good starting place for you. – El_Vanja Nov 20 '20 at 20:29
  • Welcome to SO! For what you're doing, I recommend staying with JS. JS should handle user-facing UI problems ("you selected x!", etc.); server-side (PHP, etc.) should handle business logic ("is user allowed to select x?"). AJAX has to hit the server (2 seconds transit time minimum), JS runs instantaneously (no wait time at all). Know the advantages and disadvantages before you choose the tool for the job. – HoldOffHunger Nov 20 '20 at 20:30
  • @HoldOffHunger But I havt to get data from server, so JS wont work I guess? – Cyborg122 Nov 20 '20 at 20:35
  • Yes. So AJAX is your solution. If you haven't used it before, find some tutorials – ADyson Nov 20 '20 at 20:43

2 Answers2

1

You need to get data from the server, so, as others have mentioned, you will need Ajax... or something similar.

We can delve (briefly) into web history to see the evolution of Ajax:

So that's XHR and XHR2 (ie. Ajax)


But... (here's the point of the brief history lesson above), the modern client-server communication API which supersedes XHR2 is the Fetch API which is built on ES2015 Promises and can be written either:

  • using ES2015 asynchronous .then() syntax; or
  • using ES2017 async / await syntax

If you choose ES2017 async / await syntax, you will be able to write something which handles an asynchronous server request from the client but looks (almost) like synchronous code:

async function myFunction() {

  const response = await fetch('/path/to/server-side/script.php');
  const x = await response.text();
  await document.getElementById('text').innerHTML = "You selected: " + x;
}
Rounin
  • 27,134
  • 9
  • 83
  • 108
  • 1
    Though, one should definitely take note of `fetch`'s [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#Browser_compatibility) and the notes that it is still in the experimental phase, so behaviour changes are possible. – El_Vanja Nov 20 '20 at 21:16
  • Good point, @El_Vanja. Here's **CanIUse** on **Fetch API**: https://caniuse.com/fetch – Rounin Nov 20 '20 at 21:24
  • Might be wise to edit it into the question. Comments can be easily overlooked, despite emphasis. – El_Vanja Nov 20 '20 at 21:44
  • Note that it's only IE and Opera Mini that don't support `fetch()`. The last time Safari didn't support `fetch()` was 2016. The last time Edge didn't support `fetch()` was 2015. – Rounin Nov 20 '20 at 23:11
1

It could be like this:

HTML file:

<form id="contact" action="insert_pre.php" method="post">
    <select id="mySelect" onchange="myFunction()">
      <option value="Audi">Audi</option>
      <option value="BMW">BMW</option>
      <option value="Mercedes">Mercedes</option>
      <option value="Volvo">Volvo</option>
    </select>
    <p id="textt"></p>
  </form>



<script>
  function myFunction() {
    var x = document.getElementById("mySelect").value;

    var httpRequest;
    makeRequest(x);

    function makeRequest(x) {
      httpRequest = new XMLHttpRequest();

      if (!httpRequest) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
      }
      httpRequest.onreadystatechange = onResponse;
      httpRequest.open('GET', 'get_car_info.php');
      httpRequest.send("car=" + x);
    }

    function onResponse() {
      if (httpRequest.readyState === XMLHttpRequest.DONE) {
        if (httpRequest.status === 200) {
          var car = JSON.parse(this.responseText);
          document.getElementById("textt").innerHTML = "You selected: " + car.name; // it should set "Bayerische Motoren Werke AG"
        } else {
          alert('There was a problem with the request.');
        }
      }
    }
  }
</script>

PHP file get_car_info.php

<?php
  if ($_GET["car"] == "BMW"){
    $myObj->name = "Bayerische Motoren Werke AG";
    $myObj->Industry = "Automotive";
    $myObj->city = "Munich, Germany";

    $myJSON = json_encode($myObj);
  }

  echo $myJSON;
?>
SAlex
  • 54
  • 2