-1

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:

Call php function from javascript

call function in jquery-ajax

Community
  • 1
  • 1
Russell Christopher
  • 1,677
  • 3
  • 20
  • 36
  • 5
    You 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 Jun 20 '12 at 13:41
  • 1
    There is nothing 'magic' about web development. It is a series of requests and responses. – MetalFrog Jun 20 '12 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 Jun 20 '12 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 Jun 20 '12 at 14:19

1 Answers1

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);

    });
});​
Russell Christopher
  • 1,677
  • 3
  • 20
  • 36