I constantly get 500 Internal Server Error while trying to query a db. The data is passed by Ajax to that specific page.
Here is the code:
<script type="text/javascript">
$(document).ready(function(){
$(".pool-player-list-a").click(function(){
/* Prosleđujem parametre za upis u bazu na stranicu insert_tim.php */
var id = $(this).next().val();
var br_dresa = $(this).next().next().val();
var zapisnik = <?php echo $zapisnik->id; ?>;
var mec = <?php echo $zapisnik->idMeca; ?>;
$.post('../wp-content/plugins/leaguemanager/admin/insert_tim.php', {id: id, zapisnik: zapisnik, mec: mec, br_dresa: br_dresa},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(500);
});
return false;
});
});
</script>
<div id='message'></div>
<div id='pool-holder'>
<!-- Lista igrača iz domaćeg tima -->
<div id="pool-home">
<h3 style="margin:0; padding:10px;" align="center">DOMAĆI</h3>
<?php
$igraci_home = $this->igraci_u_timu($league_id, $mec->home_team);
foreach ($igraci_home as $igrach){
/* Listam igrače */
echo "<div class='pool-player-list'>
<a class='pool-player-list-a' id='insertTim' href='#'>
$igrach->ime $igrach->prezime
</a>
<input type='hidden' class='igracId' value='$igrach->id' />
<input type='hidden' class='brDresa' value='$igrach->brojDresa' />
</div>";
}
?>
</div>
I have checked everything with the variables. Everything is fine.
And this is the insert_tim.php page that is sending Server Error.
<?php
global $wpdb;
$id = intval( $_POST['id'] );
$row = $wpdb->get_row("SELECT * FROM wp_pls_leaguemanager_person WHERE id = '$id'", ARRAY_A);
echo $row['ime'];
?>
It works on other pages.
Thanks!
Please, read this post carefully about AJAX in WordPress plugins.
You need to send AJAX requests to special script, not directly to your plugin! And then you handle request using actions.
But what you have done? – You send request to your script, so it knows nothing about WordPress :). WordPress must include your plugin and then your plugin will have access to native functions and classes.
Update. More detailed explanation.
AJAX is just calling your script from given link. When you call your script directly (http://site.com/wp-content/plugins/myplugin/insert_tim.php), then php begins to execute it and NOTHING MORE! It doesn’t initiate WordPress engine. So $wpdb will be undefined variable that will throw exception on use (if exception display is disabled in your php config, then you will just see “Internal Server Error 500”). Of course, if you remove $wpdb usage – all will be OK.
And what does WordPress’s ajaxurl (http://site.com/wp-admin/admin-ajax.php) change? If you will open this file – you will see, that it contains WordPress engine load:
So if you pass ajaxurl to your AJAX call – then this script will load WordPress engine, then using actions – will call your function and your function will see $wpdb class.
Remember the rule: Don’t call your plugin’s PHP scripts directly using AJAX. Use native WordPress behavior.