Reputation: 39
Hopefully I can ask this correctly cuz I know what I want it to do but can't seem to find any answers from searching.
I have a func.php page where I have all my functions and I want ajax to use one function from that page.
func.php
function toptable()
{
echo"something happens in here";
}
index.php
<?php include 'func.php'; ?>
<script type="text/javascript">
function check_username() {
uname=document.getElementById("username").value;
var params = "user_id="+uname;
var url = "topoftable()";
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: params,
beforeSend: function() {
document.getElementById("right").innerHTML= 'checking' ;
},
complete: function() {
},
success: function(html) {
document.getElementById("right").innerHTML= html ;
}
});
}
</script>
Make sense?
Upvotes: 2
Views: 33065
Reputation: 1562
It's not working like that.
Your AJAX request should look something like this:
$(document).ready(function() {
//some even that will run ajax request - for example click on a button
var uname = $('#username').val();
$.ajax({
type: 'POST',
url: 'func.php', //this should be url to your PHP file
dataType: 'html',
data: {func: 'toptable', user_id: uname},
beforeSend: function() {
$('#right').html('checking');
},
complete: function() {},
success: function(html) {
$('#right').html(html);
}
});
});
And your func.php
:
function toptable()
{
echo 'something happens in here';
}
//here you can do some "routing"
$func = $_POST['func']; //remember to escape it
switch ($func) {
case 'toptable':
toptable();
break;
default:
//function not found, error or something
break;
}
Also check that I change document.getElementById
to jQuery selector $('#...')
.
Upvotes: 11
Reputation:
Make sense? - no. You can't mix PHP (a server-side technology) with Javascript (client-side). You can use AJAX to ask a server to perform some function for you, but not by using the function name as a URL. You should create a PHP page to accept your AJAX request, perform the function and return the result, and use the URL of that page in your AJAX request
Upvotes: 0
Reputation: 4544
PHP is server side, JS is client side. You need to call the PHP script in the ajax request, not the function.
Something like
[...]
var url = "func.php";
$.ajax({
type: 'POST',
url: url,
[...]
func.php
<?php
function toptable()
{
echo "something happens in here";
}
toptable();
?>
In this case, the html
argument in the success handler of the ajax request will be equal to "something happens in here"
.
Upvotes: 0