Get MySQL Record using Php & JQuery
Here's my scenario:
I have a drop down menu, with different values. When option 'A' is chosen, I want it to use JQuery to call a Php script. That Php script will make a database query which returns a record ID. When that record ID is returned to the javascript, javascript will direct the browser to a particular URL based on the returned ID (i.e. /products/$ID)
Right now, I have it so that the dropdown menu triggers a javascript function. I also have开发者_如何转开发 the Php script that does the database work. Im just not sure what should go in the javascript function, or how to make it connect with he Php script, and how I get the returned data (and how to deal it with the return type -- xml, html, etc)
Im using JQuery library, and Php 5.x.
A simple example would be to take a form like
Example.php
<form id="form" name="form">
<select name="dropdown" id="dropdown">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<input type="submit" id="submit" name="submit" value="Submit!" />
</form>
Then link it with some JQuery to intercept the form, and send it to a PHP file
JQuery.js
$(document).ready(function(){
$("#dropdown").change(function(event) {
$.ajax({
type: "POST",
url: "query.php",
data: $('#form').serialize(),
datatype: "json",
success: function(data){
var ret = jQuery.parseJSON(data);
// Redirect to ret.link
}
});
event.preventDefault();
});
});
Then, create the PHP file to interpret it
query.php
$stmt = $sql->dbh->prepare("SELECT `Link` FROM `Links` WHERE `ID` = :id");
$stmt->bindValue(':id', $_POST['dropdown']);
$stmt->execute();
$link = $stmt->fetch()['Link'];
echo json_encode(array('link' => "{$link}"));
die();
$("#menu-item").click(function() {
jQuery.ajax({
type: "POST",
url: "yourScript.php",
data: "data=foo",
success: function(response){
//redirect to id using response
window.location.replace("http://yoursite.com/products/" + response);
}
});
});
Of course, this will need to be customized to your unique situation.
精彩评论