1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Call PHP function by Ajax

Discussion in 'JavaScript' started by blueparukia, Feb 21, 2008.

  1. #1
    I have asked before, I'll ask again. How can I call PHP functions with Ajax? I have looked at PHP classes - such as PHPLiveX, and while they work, the Javascript is poorly contained, and does not work if I contain it properly - so it validates xHTML.


    So could anyone point me to how to this using xmlHTTPrequest ONLY.

    Thanks,

    BP
     
    blueparukia, Feb 21, 2008 IP
  2. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Can you expand on your problem?

    PHP is executed whenever the page is requested. So just request the page with AJAX.
     
    MMJ, Feb 21, 2008 IP
  3. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #3
    OK, so I have found a nice, xHTML compliant PHP class: Sajax.

    However, it is shockingly under documented, and all I can do with it atm is call the response text via an alert() - wish to stick it in a div's innerHTML.

    Help appreciated,

    BP
     
    blueparukia, Feb 23, 2008 IP
  4. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Do you have a link?
     
    MMJ, Feb 23, 2008 IP
  5. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #5
    If you can throw the responseText in an alert, why can't you put it in the div?

    Instead of alert(varForResponseText), you'd do document.getElementById('your_div').innerHTML = varForResponseText
     
    zerxer, Feb 23, 2008 IP
  6. sharry

    sharry Peon

    Messages:
    319
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    0
    #6
    // function to create XmlHttp Object
    function getxmlhttp(){
    var xmlHttp = false;
    if (window.XMLHttpRequest){
    // If IE7, Mozilla, Safari, etc: Use native object
    var xmlHttp = new XMLHttpRequest();
    }else{
    if (window.ActiveXObject){
    // ...otherwise, use the ActiveX control for IE5.x and IE6
    var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    }

    return xmlHttp;
    }

    //function to process an XMLHttpRequest
    function process_ajax(phpPage, divID, getOrPost, ''){
    xmlhttp = getxmlhttp();
    var obj = document.getElementById(objID);
    if(getOrPost == "get"){
    xmlhttp.open("GET",serverPage);
    xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
    obj.innerHTML = xmlhttp.responseText;
    }
    }
    xmlhttp.send(null);
    }
    }

    these are the two functions you'll ever need to make a ajax call
    enjoy :)
     
    sharry, Feb 23, 2008 IP
  7. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #7
    http://www.modernmethod.com/sajax/download.phtml

    It's the library, one of the output types is alert, and is the only one I know, since I cannot find any others on the site.

    I know that, but that just calls a PHP file, I want to call a PHP function. I would prefer to do it without a framework, but I can settle for using one if I have to.

    Thanks,
    BP
     
    blueparukia, Feb 23, 2008 IP
  8. sharry

    sharry Peon

    Messages:
    319
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    0
    #8
    y not just make a file, which includes the php file with the function defination and a right after that a function declaration of a instance
    for example

    function blahblah(x,y){
    ....
    ....
    ...}
    blahblah(1,2);
     
    sharry, Feb 23, 2008 IP
  9. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #9
    Yeah, but if I want to execute it onclick() or whatever, that won't work.
     
    blueparukia, Feb 23, 2008 IP
  10. rkquest

    rkquest Well-Known Member

    Messages:
    828
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    140
    #10
    Well, since you want to use SAJAX, try this one:

    
    <?php
    
    require('sajax.php');
    
    function say_something($something) {
    	return $something;
    }
    
    sajax_init();
    sajax_export('say_something');
    sajax_handle_client_request();
    
    ?>
    
    <html>
    <head>
    	<script type="text/javascript">
    	<?php sajax_show_javascript(); ?>
    	function say(something) {
    		document.getElementById('container').innerHTML = something;
    	}
    	</script>
    </head>
    <body>
    <div id="container"></div>
    <a href="javascript:x_say_something('Hello, World!', say)">Say Something</a>
    </body>
    </html>
    
    PHP:
    Basically, you're passing the sajax function's (x_say_something) return value to another javascript function (say).
     
    rkquest, Feb 23, 2008 IP
  11. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #11
    Thank you. I will try it when I get home. Sajax is not really my preferred method of doing things, but if it works, it works :p

    Though could I use onclick='' instead of href='javascript:' ?

    Thanks again
     
    blueparukia, Feb 23, 2008 IP
  12. rkquest

    rkquest Well-Known Member

    Messages:
    828
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    140
    #12
    Let me guess, you don't like all the JavaScript codes it adds to your page? :D
    I've been using Sajax (because my company requires it) for a while and if it is your problem,
    I may have a workaround although I haven't really tried it.
     
    rkquest, Feb 23, 2008 IP
  13. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #13
    Yeah, I prefer external JS. You can PM your workaround if you'd like :)
     
    blueparukia, Feb 23, 2008 IP
  14. Lisans

    Lisans Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #14
    jquery.com


    
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    /*
     ajax fonksiyonu
     Ajax('div', 'page.php', 'form_id', [, Mixed append], [, String data])
     Coded by Tan SEZER
    */
    function Ajax(id, page, form, append, data)
    {
    	var veri = '';
    	if( typeof(data) == "string")
    		veri = data;
    	else 
    		veri = $(form).serialize();
    	$.ajax({
       type: "POST",
       url: page,
       data: veri,
       error: function(html)
       {
       		alert("Ajax hatası meydana geldi..");
       },
       success: function(html)
       {
        	if( typeof(append) == "boolean")
    			$(id).append(html);
    		else
    			$(id).html(html);
       }
      });
      return false;
    }
    </script>
    
    Code (markup):
    simple:
    <div id="test" onclick="Ajax('#test', 'test.php', null, 'data=test');"></div>
    Coded me :)
     
    Lisans, Feb 25, 2008 IP
  15. LordWEB

    LordWEB Peon

    Messages:
    1
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #15
    You can call php functions with javascript and get responce back in javascript with jAPI Direct class.

    jAPI Direct contains PHP and JavaScript script that enables you to call PHP methods direct from JavaScript just by typing their names.

    For example you can call PHP method that looks like this:

    class MySimpleMath {

    public function Addition($firstParam, $seccondParam) {
    $sum = $firstParam+$seccondParam; echo $sum;
    }
    }
    ...from JavaScript just with:

    And you will have as a result: "3"

    To use jAPI in your project you will have to fallow a few steps only.

    First download jAPI project source from this address.
    http://www.phpclasses.org/package/6314-PHP-Handle-calls-of-JavaScript-to-PHP-code.html

    Make sure that you included in your html page all scripts properly. You also have to include this two scripts in your html file: jAPI.js, jAPI-Remote.php.

    jAPI-Remote.php actually can be any php script from which you want to use their server side methods.

    You have to include jAPI-Core.php script in this file (jAPI-Remote.php) by adding this line of code at the beggining of your script:

    include("httpHandler/jAPI-CORE.php");

    And at the end of your script you will have to create a new instance of jAPI Base Class like this:

    //all classes names comma separated as jAPIBaseClass parameter which you want to use

    new jAPIBaseClass('YourClass,AnotherClass');

    So, that's it!
     
    LordWEB, Jul 7, 2010 IP
  16. bvraghav

    bvraghav Member

    Messages:
    123
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    33
    #16
    is it this simple as i mentioned under, or i misunderstood something?

    <a href="javascript:void(0)" id="call-php-fn">Click here to call on a php function with parameters XX &amp; YY</a>
    HTML:
    javascript code should look like:
    $("a#call-php-fn").click( function() {
        jQuery.ajax( {
            url: "simple-php-fn.php",
            type: "POST", //or may be "GET" as you wish
            data: { foo: "XX", bar: "YY" },
            complete: function( xml, status ) {
                jQuery( "#update-div" ).text( jQuery( "data", xml ).text() );
            }
        } );
    ) );
    Code (markup):
    though this was using jQuery framework, (to make it look comprehensive), it can be implemented using any framework, or even without any framework.
    for jQuery framework refer this

    and the php file would look like
    <?php
    /* 
     * simple-php-fn.php
     *
     */
    
        function my_php_fn( $a, $b ) {
            return "I got 2 variables - $a & $b";
        }
    
        if ( isset($_REQUEST['foo']) && $_REQUEST['foo']    &&    isset($_REQUEST['bar']) && $_REQUEST['bar'] ) {
            echo "<root><data>" . my_php_fn( $_REQUEST['foo'], $_REQUEST['bar'] ) . "</data></root>";
        } else {
            echo "<root>Error: no input values</root>";
        }
    ?>
    PHP:
     
    bvraghav, Jul 7, 2010 IP
  17. guatebus

    guatebus Peon

    Messages:
    1
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #17
    In bvraghav's response I see how jQuery.ajax() is used to invoke my_php_fn() in the simple-php-fn.php file. However, the function's name is not specified in the jQuery.ajax() call. Can simple-php-fn.php contain other functions, and how one specify which one should be invoked? Thanks! :cool:
     
    guatebus, Feb 10, 2012 IP
  18. Rift2552

    Rift2552 Peon

    Messages:
    1
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #18
    I don't know if this is what your looking for but it seems to work for me. You need to make sure that
    the php file is included beforehand

    <script type="text/javascript">
    //Calls the php function
    function jsHelloWorld(){
    <?php HelloWorld(); ?>
    }
    </script>

    //Calls the java script hello world when clicked
    <a href="javascript:HelloWorld()"></a>
     
    Rift2552, May 8, 2012 IP