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.

14
  • From inside the javascript? Something like <?php echo getImgs('images/', '.*JPG'); ?>? Commented May 27, 2014 at 9:22
  • The answer is the same whether you use jQuery or plain Javascript: you have to use AJAX. Commented May 27, 2014 at 9:22
  • yes, the answer is the same, i do wanna use AJAX but how can i call the function from mainfile.php using AJAX. Commented May 27, 2014 at 9:24
  • I don't wanna use php tags inside the script tags, wanna call the function with AJAX @Johan Commented May 27, 2014 at 9: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...? Commented May 27, 2014 at 9:26

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
that is still executing the function from the PHP page, I want to execute the function from inside of the script tag.
@deceze over indulgence this morning. Updated ;]
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.

4 Comments

either way, i will be calling the function from another PHP file and not inside of the script tags?
have you viewed the link that I have posted in my question, calling PHP function from Javascript, it is using jQuery but calls the function from inside of script tags..
I'm rewriting my answer
will that let me manipulate the images when loaded into the DOM?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.