Kriss0612
Kriss0612

Reputation: 55

Trying to get information from database with jQuery

I am VERY new to jQuery, and I have been trying to get information from my SQL database whenever the user chooses a new option in a datalist form. This is the code:

<form>
<input list="chemicals" name="chemicalsearch">
  <datalist id="chemicals">

 <?php while ($info3=mysql_fetch_array($info2)) {
      echo "<option value='$info3[name]'>$info3[formel]</option>";
        }

?>
</datalist>
</form>

<script type="text/javascript">

$('#chemicals').on('change', function() {
    var record_id = $(this).val(); 
    var data = {
        'id': record_id
    };

    $.ajax({
        type: "GET",
        url: '/Chemistry%20Calculator/getchemical.php', 
        data: data,
        success: function(response) {
            document.getElementById('formel').innerHTML = data.formel;
        },
        error: function(jqXHR, textStatus, errorThrown) {
        }
    });
});
</script>

And then the PHP file:

<?php

include_once 'connect.php';

$info="SELECT * from chemicals where name='$id'";
$info2=mysql_query($info) or die("Wrong link. This page does not exist.");
$info3=mysql_fetch_array($info2);

$name = $info3['name'];
$formel = $info3['formel'];
$massa = $info3['molmassa'];

$array = array($name, $formel, $massa);

$data = json_encode($array);

echo $data;

?>

Please be patient with me here, as I have never used jQuery before. And yes, I am aware of the fact that I'm using the old MySQL syntax, I will change that as soon as I get this working. Any help would be greatly appreciated :)

Upvotes: 0

Views: 162

Answers (2)

Bud Damyanov
Bud Damyanov

Reputation: 31919

The success method is a function to be called if the request succeeds. The function gets passed three arguments:

  1. The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified;
  2. A string describing the status;
  3. The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.

In your case:

      success: function(data, textStatus, jqXHR) {
         //The "data" returned from server is assigned to HTML element here
         document.getElementById('formel').innerHTML = data;
      }

A side note: usage of mysql_* functions is deprecated, use PHP PDO instead.

EDIT: Do not forget to include jQuery library in your file, before trying to execute the code $(“#chemicals")..... The error of $ being undefined means exactly that.

Upvotes: 0

Vasiliki M.
Vasiliki M.

Reputation: 372

You are not writing what exactly is the problem, either from the side of php or javaScript. But anyway, correct your syntax to php regarding the variables. Like below:

<?php while ($info3=mysql_fetch_array($info2)) {
  echo '<option value="'.$info3[name].'">'.$info3[formel].'</option>';
}?>

and later on your query...$info='SELECT * from chemicals where name="'.$id.'"'

Upvotes: 1

Related Questions