call php function that is in a different file from a javascript function to retrieve data from 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 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 JS 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 my code:
JavaScript in a different file called divUpdate.php
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
base_url = '<?= base_url();?>index.php/';
</script>
<script type="text/javascript">
function changeDiv(venueID){
//document.getElementById('venue_description').innerHTML=venueID;
$.get(base_url+'home/get_venue_description/' + venueID,
function(data) {
$('venue_description').html(data);
});
}
</script>
Where the onClick function calls the JavaScript above:
<li><a href="#self" class="menulink" class=开发者_开发百科&{ns4class};
onClick="changeDiv(\''. $venue_details->VenueID . '\')">;
Function below is called from JavaScript above in divUpdate.php
. The function below is also in in the model- venue_model.php
function retrieveData($venueID){
$query = $this->db->query("SELECT * FROM venue WHERE VenueID = '$venueID' ");
return $query;
}
Then, in the controller home.php
I have a function that the JavaScript uses to pass the id that will then be used by the model to retrieve the data from the database
function get_venue_description($venueID){
echo $this->venue_model->retrieveData($venueID);
}
For some reason the code in the JavaScript divUpdater.php
doesn't work. It looks correct but doesn't work.
Basically, in your Javascript, you should do
http://www.mywebsite.com/foo.php?venueID=123
or a form in your framework, like
http://www.mywebsite.com/controller/action/123
You can use Firebug in Firefox to do a console.log(base_url)
because it looks like
base_url = '<?= base_url();?>index.php/';
$.get(base_url+'home/get_venue_description/' + venueID,
and your URL is something like:
http://www.mysite.com/index.php/home/get_venue_description/123
and in your PHP file, do a
$venueID = $_GET['venueID'];
if (preg_match('/^\d+$/', $venueID) {
$query = $this->db->query("SELECT * FROM venue WHERE VenueID = '$venueID' ");
}
The preg_match()
is to say, if the $venueID
is only full of digits and nothing else. This is to prevent SQL injection where somebody sends in some string to get your query to do something not intended by you.
Also, do some print_r()
or var_dump()
in your PHP file so that you can make sure what you are getting from the browser is correct.
精彩评论