Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
rated 0 times [  160] [ 2]  / answers: 1 / hits: 7563  / 10 Years ago, tue, may 27, 2014, 12:00:00

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.


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

function loadXML(method, url, div, index)
var xmlhttp;

xmlhttp = new XMLHttpRequest();
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');

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

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



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.

More From » php


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']))

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.

[#45012] Monday, May 26, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 382
Total Questions: 99
Total Answers: 85

Location: Cape Verde
Member since Fri, Nov 27, 2020
3 Years ago
julieth questions