How to call PHP functions from a JavaScript function to access a database
How do you call a PHP function that is in a different file from a JavaScript function?
I have a JavaScript function that recieves a variable from an onclick function. The variable is an id that开发者_开发问答 I will use to retrieve data from a MySQL database. The variable is then passed on to a PHP function that will access the database to get the data and return back to my JavaScript function for display, but it does not seem to be working. How can I get it to work? I am using CodeIgniter PHP.
Here is the code.
The JavaScript code is in a different file called divUpdate.php
.
<script type="text/javascript">
function changeDiv(venueID){
//retrieveData(venueID) is a PHP function from venue_model.php
var dest = retrieveData(venueID);
document.getElementById('venue_description').innerHTML=dest;
}
</script>
---Where the onclick function calls the JavaScript code above. ----
<li><a href="#self" class="menulink" class=&{ns4class};
onClick="changeDiv(\''.
$venue_details->VenueID.
'\')">;
--- Function retrieveData is called from the JavaScript code above. This is in the model (CodeIgniter). --
function retrieveData($venueID){
$query = $this->db->query("SELECT * FROM venue WHERE VenueID = '$venueID' ");
echo $query;
}
Use Ajax as already suggested. Using jQuery you will get this fixed with ease.
You will need to create a controller to access your Ajax calls. I, simply enough, created the Ajax controller like this:
<?php
class Ajax extends Controller
{
public function index()
{
$this->output->set_output("This is the AJAX Controller");
}
public function get_venue_description( $venueId )
{
$this->load->model('yourmodel');
$data = $this->yourmodel->retrieveData($venueId);
$this->output->set_output($data);
}
}
?>
Then your JavaScript code, after implementing jQuery, should look something like this:
<script type="text/javascript">
function changeDiv(venueID)
{
$.get('/ajax/get_venue_description/' + venueId, function(data) {
$('#venue_description').html(data);
});
}
</script>
I haven't tested it, but I hope you get the idea.
What you are looking for is "AJAX" - try searching for a tutorial on google. Also, you'll find it a lot easier to perform AJAX requests by using a JavaScript library like jQuery.
Here's jQuery AJAX function: http://api.jquery.com/jQuery.ajax/
精彩评论