It's clear from reading through threads that I can call a PHP function using Ajax / JQuery, but I can't quite get my head around the particulars.
Let's say I have a function foo() which simply adds 'bar' to some string I pass in. foo() lives in foo.php. To use this in my JavaScript-less HTML, I'd do something like this:
<?php include 'foo.php';?>
<?php echo foo('bar')?>
...and my output is "foobar". Great.
I suspect I do something like so to grab the output of foo() via JavaScript:
<script>
$.post("http://foo.com/foo.php", {
<Magic happens here>
}, function(response) {
useTheOutput(response);
});
</script>
....but I'm not clear on whether I should be POSTing or GETing...and how to pass in a value, like 'bar'.
Can anyone push me in the right direction? Here are other threads that discuss the same thing, I just can't connect all the dots:
-
5You seem to lack the understanding of what php is, how it differs from javascript and what ajax does. I recommend using a tutorial which covers this stuff.Sgoettschkes– Sgoettschkes2012年06月20日 13:41:31 +00:00Commented Jun 20, 2012 at 13:41
-
1There is nothing 'magic' about web development. It is a series of requests and responses.MetalFrog– MetalFrog2012年06月20日 13:45:22 +00:00Commented Jun 20, 2012 at 13:45
-
Actually, I get it. I have a php function which generates a "ticket". This function must be fired server-side as the request itself needs to come from a trusted IP address, which is the server on which the .php page lives. I need to call this function from JavaScript - I see other people have accomplished this on StackOverFlow, but I still need a little help.Russell Christopher– Russell Christopher2012年06月20日 13:48:01 +00:00Commented Jun 20, 2012 at 13:48
-
For your POST/GET question, use POST for destructive actions such as deletion, editing, and creation. Reason for this is because you can't hit a POST action in the address bar of your browser. Use GET when it's safe to allow a person to call an action from the address bar, i.e. guiding you to a specific page, setting options in a form etc.ohaal– ohaal2012年06月20日 14:19:55 +00:00Commented Jun 20, 2012 at 14:19
1 Answer 1
Solution:
PHP (foo.php):
<?php
function generateTicket()
{
//get_trusted_ticket_direct is another function that does heavy lifting...
$ticket= get_trusted_ticket_direct($_POST['server'], $_POST['user'], $_POST['targetsite']);
echo $ticket;
}
if ($_POST['toDo'] == 'generateTicket') {
generateTicket();
}
?>
JavaScript:
$(document).ready(function() {
// Handler for .ready() called.
$.post('http://foo.com/foo.php', {
toDo: 'generateTicket',
server: 'serverName',
user: 'userName',
targetsite: ''
}, function(response) {
alert(response);
});
});