Jquery/ajax Populated Html Form When Dropdown Selected
I am trying to populate a form on my page. The information required to populate the form is pulled from a MySQL database using the ID of the drop down option as the ID in the SQL
Solution 1:
On a quick glance there seems to be two issues with the code you've posted so far:
The AJAX request
Even though $.ajax()
defaults to a request type of GET by default, it's good to specify it. There is also a syntax error in your request — you have closed the success
callback with a });
where it should be a }
only:
$.ajax({
url: "recall.php",
data: {
recall: recall
},
type: "GET", // Declare type of request (we use GET, the default)dataType: "json",
success: function(data)
{
var id = data[0];
var vname = data[1];
$('div#box1').load('DFBristol.html');
} // The problematic closure
});
Even better: instead of using the deprecated jqXHR.success()
function, use the .done()
promise object instead, i.e.:
$.ajax({
url: "recall.php",
data: {
recall: recall
},
type: "GET", // Declare type of request (we use GET, the default)dataType: "json"
}).done(function() {
// Successvar id = data[0],
vname = data[1];
$('div#box1').load('DFBristol.html');
});
Fixing the file recall.php
When you make an AJAX GET request to recall.php
, the file needs to know what variables you intend to pass, which you have not defined. You can do that using $_GET[]
(see doc), i.e.:
<?php// Assign the variable $recall with the value of the recall query string from AJAX get request// I recommend doing a check to see if $_GET['recall'] is defined, e.g.// if($_GET['recall']) { $recall = $_GET['recall']; }$recall = $_GET['recall'];
// The rest of your script, unmodified$user = 'root';
$pass = '';
$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$recall = $DBH->prepare("SELECT * FROM bookings WHERE ID = '%$recall%'");
$recall->execute();
$recallFormResult = $recall->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($recallFormResult);
?>
Note: However, if you choose to make a POST request, then you should use $_POST[]
(see doc) instead :)
Post a Comment for "Jquery/ajax Populated Html Form When Dropdown Selected"