0

I know that this question has been asked before but all of them are using jQuery library and i would like to use Javascript only, no libraries so please bear with me.

This link shows the PHP function being called from jQuery.

How can I call PHP functions by JavaScript?

The code is calling a function that displays images.

I have the following code and I don't understand how to call the function from the mainfile.php and not functions.php.

mainfile.php

<button id="btn">Click</btn>   // button that calls ajax file
<div id="div"></div>   // div where it should appear

<script>
    function loadXML(method, url, div, index)
    {
        var xmlhttp;

        try
        {
            xmlhttp = new XMLHttpRequest();
        }
        catch(e)
        {
            try
            {
                xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch(e)
            {
                alert('sorry');
            }
        }

        xmlhttp.onreadystatechange = function()
        {
            if( xmlhttp.readyState === 4 && xmlhttp.status === 200 )
            {
                if( index === null || index === 'undefined' || xmlhttp === '')
                {
                    document.getElementById(div).innerHTML = xmlhttp.responseText;
                }
            }
        };

        xmlhttp.open(method, url, true);
        xmlhttp.send(null);
    }

    document.getElementById('btn').addEventListener('click', function()
    {
        loadXML('GET', 'imgs.php', 'div', null);
    }, false);
</script>

functions.php

<?php

    function getImgs($dir, $type)
    {
        $images = glob($dir . $type);

        print_r($images); // for now i'm printing the array the way it is to see the function work
    }
    getImgs('images/', '.*JPG');   // calling function from php file works

?>

I would like to call the function from inside mainfile.php without using any jQuery library, only plain Javascript, it should be possible considering that the libraries are made with Javascript. I don't know where to call the function from inside mainfile.php. Any help would be appreciated.

The reason I am getting files from php is because it is easier to load them into the DOM, I need to make an image gallery so I would like to know if it will be possible to manipulate the images when they are loaded into the DOM using AJAX.

Community
  • 1
  • 1
Hawk
  • 788
  • 1
  • 6
  • 18
  • From inside the javascript? Something like ``? – Johan May 27 '14 at 09:22
  • The answer is the same whether you use jQuery or plain Javascript: you have to use AJAX. – Barmar May 27 '14 at 09:22
  • yes, the answer is the same, i do wanna use AJAX but how can i call the function from mainfile.php using AJAX. – Hawk May 27 '14 at 09:24
  • I don't wanna use php tags inside the script tags, wanna call the function with AJAX @Johan – Hawk May 27 '14 at 09:24
  • 1
    An AJAX request is exactly like any other request. Your AJAX request will trigger exactly the same PHP code as it would when you type `http://.../imgs.php` (that's the URL you seem to be calling using AJAX) into your browser. Does this help...? – deceze May 27 '14 at 09:26
  • sorta, so should I make it a POST request? @deceze – Hawk May 27 '14 at 09:28
  • Just pass a key that you look for in your php file to trigger the method from an asynchronous request e.g. `if(isset($_GET['getImges']))`. Also, you probably want to echo your result as JSON. – Johan May 27 '14 at 09:28
  • I didn't say that. GET is fine. However, type that URL you're calling into the browser and see what the result is. – deceze May 27 '14 at 09:28
  • It doesn't look like you are sending data to the server that you expect it to store. POST doesn't seem like a good fit. – Quentin May 27 '14 at 09:28
  • I see the pictures being shown when I type the full url, that is because I have called the function in the PHP file @deceze – Hawk May 27 '14 at 09:30
  • OK, fine. Then open your browser's debug console, to the network tab, and see if the AJAX request triggers the same request/response. – deceze May 27 '14 at 09:32
  • Is it possible that you forgot to change the url in `loadXML('GET', 'imgs.php', 'div', null);` to `functions.php` so you're calling the wrong php file? – KhorneHoly May 27 '14 at 09:33
  • no, I am calling the correct file, the images are shown but I want to call the getImgs() function from the mainfile.php inside the script tags and not directly from the functions file @KhorneHoly – Hawk May 27 '14 at 09:34
  • it's showing test/images in the debugger, that's the path to the images file. how does that help @deceze – Hawk May 27 '14 at 09:37

2 Answers2

1

You can only do it by Making an AJAX request to a php page while passing in a parameter to initialise the function.

That means your AJAX will send in for example "functionName" to the php page "functionsListPage.php"

The GET will be recieved :

 if (isset($_GET['functionName']))
    functionExec();

This is the only way so you are not calling direct from the client however you are indicating to the server you want to run a predefined request.

You cannot call a PHP function directly from the clientside.

Pogrindis
  • 7,755
  • 5
  • 31
  • 44
  • 1
    That's quite a roundabout way to express that. It's dead simple: whatever happens server side depends on the URL that is visited. Nothing more, nothing less. Just like any other regular PHP page. *"AJAX becomes an interpreter"* - what? – deceze May 27 '14 at 09:30
  • that is still executing the function from the PHP page, I want to execute the function from inside of the script tag. – Hawk May 27 '14 at 09:31
  • @deceze over indulgence this morning. Updated ;] – Pogrindis May 27 '14 at 09:32
0

It's just like the answer from @Pogrindis, but i think so explanation is needed

It is possible to do it with with plain JavaScript with a little workaround!

What you need to do is the following in JavaScript after the xmlhttp.open();

var functionname = getImgs;
xmlhttp.open();
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(functionname);

What this does is simple: it sends the data to the server, so you php file can get this parameter!

In your called php file you need something like this:

if( isset($_POST['functionname']) )
{
    if($_POST['functionname']) == 'getImgs'
    {
        getImgs();
    }
}

Of course you need to make sure that you post the data with post in this case, if you want to use get you need to change the php to $_GET

Notice: This is totally unsafe right now! No escaping from the coming data and anything else.

KhorneHoly
  • 4,666
  • 6
  • 43
  • 75