I have a javascript function that's executed on a button click and I have an included file containing all my PHP functions. One of the PHP functions returns me an array of filenames encoded as a JSON object. I'd like to call this function from my Javascript function so that I can use the array. I know I can call a PHP file which would run but in this case I only want to call one specific named method.
I tried the following but couldn't get it to work (Console error: Unexpected < )
function getPHPArray(){
var picArray;
picArray = <?php getPicArrayJson(); ?>;
}
Can this be done using XMLHttpRequest or do I need to find another method? (If reasonably possible I'd prefer straight Javascript over JQuery but I can use JQuery if it makes this significantly easier)
If so how?
My PHP method is as follows:
function getPicArrayJson(){
global $fileArrayString;
If (!empty($fileArrayString)){
echo json_encode($fileArrayString);
}
}
My JavaScript so far:
function getPHPArray(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "phpFunctions.php?name=getPicArrayJson", true);
xmlhttp.send();
}
This is essentially a Remote Procedure Call. For use with PHP, I'd check out JSON-RPC PHP.
Anyway, here's a basic way you can do it without much complexity to your app. You will have to make an ajax request to the server. The idea for you here is to use call_user_func.
call_user_func("getPicArrayJson");
You can use
call_user_func($_POST["name"]);
But I highly recommend that you only allow certain functions to be called
phpFunctions.php
$allowed_functions = array("getPicArrayJson");
$name = $_POST["name"];
function getPicArrayJson() {
$pics = array("1.jpg", "2.jpg");
return json_encode($pics);
}
// legal function
if (in_array($name, $allowed_functions)) {
header("Content-Type: application/json");
$json = call_user_func($name);
die($json);
}
// invalid access
else {
// Error 400
}
Then do you Ajax request per normal
...
xmlhttp.open("POST", "phpFunctions.php?name=getPicArrayJson", true);
xmlhttp.send();
ps my own two cents, I would use a GET request for this. Following RESTful API conventions for web services, a POST request would only be used to create a new element.
Related
This type of question has already been asked many times, but I can't find an answer that:
Does not use jQuery
Works
jQuery answers: https://stackoverflow.com/a/44105591, https://stackoverflow.com/a/43393223
Not jQuery, but doesn't work: https://stackoverflow.com/a/38982661
"Drop that and try jQuery"
First of all, I'm trying to do this with a browser extension.
Here is my (only) JS file:
// ...
function log(info,time){
if(time===undefined)time=true;
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState===4&&this.status===200){
console.log(this.responseText);
}
}
info="http://localhost/log.php?log_item="+encodeURIComponent(info)+"&time="+(time?"true":"false");
xhttp.open("GET",info,true);
xhttp.send(null);
}
// ...
Of course, this uses GET. info is a string, and time is either undefined (handled in the function) or boolean.
This is how I tried to use POST:
function log(info,time){
if(time===undefined)time=true;
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState===4&&this.status===200){
console.log(this.responseText);
}
}
info="log_item="+encodeURIComponent(info)+"&time="+(time?"true":"false");
xhttp.open("POST","http://localhost/log.php",true);
xhttp.send(JSON.stringify({
"log_item":info,
"time":time?"true":"false"
}));
}
As taken from https://stackoverflow.com/a/38982661
And here is my log.php:
<?php
header("Access-Control-Allow-Origin: *");
if(isset($_POST["log_item"],$_POST["time"])){
$_POST["log_item"]=urldecode($_POST["log_item"]);
if($_POST["time"]==="true")file_put_contents("log.html","<li><b>[".date('l, F j, Y \a\t h:i:s A')."]: </b>$_POST[log_item]</li>\n",FILE_APPEND);
else file_put_contents("log.html",$_POST["log_item"]."\n",FILE_APPEND);
echo $_POST["time"];
}
You shouldn't have to worry about it, though. It just logs to log.html.
I can't find a working solution to this (or maybe I'm not using the working solutions correctly). And again your answer should not include jQuery.
What you're doing there (sending URL-encoded data within a JSON object) makes no sense. You're mixing two different data formats arbitrarily. You also haven't set the content-type header, which is needed, otherwise it defaults to plain-text/HTML and the server won't populate it into the $_POST variables.
This version will work:
function log(info,time){
if(time===undefined)time=true;
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState===4&&this.status===200){
console.log(this.responseText);
}
}
info="log_item="+encodeURIComponent(info)+"&time="+(time?"true":"false");
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //set content type
xhttp.open("POST","http://localhost/log.php",true);
xhttp.send(info); //just send the URL-encoded data without wrapping it in JSON
}
P.S. $_POST["log_item"]=urldecode($_POST["log_item"]); is redundant in the PHP - the data will be decoded automatically already.
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.
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.
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.
This question already has answers here:
How does Ajax work with PHP?
(2 answers)
Closed 9 years ago.
Below is the code I have.
The flow needs to be:
-On button click, value is passed to JS
-JS sets as variable
-The variable needs to be sent to PHP without refreshing the page (AJAX?)
-The variable needs to be output in php
Can anyone show me how to do this?
<button onclick="updateVar(2)" class="btn btn-acceptColor m-t-lg">Accept</button>
<script type="text/javascript">
function updateVar(profferRequestID){
var profferRequestID;
//pass to ajax then pass to php??
}
</script>
<?php
//echo out that JS variable
echo $profferRequestID;
?>
Oy. I need 6 more points before I can add a comment.
Please answer the following questions:
Does this have to be cross-browser compatible?
If so, you may want to consider using the jQuery JavaScript library. There are a "ton" of browser inconsistencies with AJAX that jQuery abstracts out.
Either way, you may consider using jQuery because of it's powerful AJAX libraries.
Do you want to return the php response to your JavaScript function, or display it somewhere on your HTML page?
After you answer that, I'll be happy to provide you with a complete answer. I'm trying to give back to the StackOverflow community. :)
try something like this
using jquery
javascript code
var name = "John";
$.get( "your_file.php", { user_name: name},function( data ) {
// on success perform action you want.
});
php code
$user_name = $_GET['user_name'];
ANOTHER WAY
In javascript (not checked)
var name = "John";
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// on success perform action you want.
}
}
xmlhttp.open("GET","your_file.php?user_name="+name,true);
xmlhttp.send();
EDITED CODE
function updateVar(val){
$.get( "path_to/your_file.php", { profferRequestID : val},function( data ) {
// on success perform action you want.
});
}
your_file.php
$profferRequestID = $_GET['profferRequestID'];
I'm not familiar with AJAX, or PHP, but I know that in javascript, you can read/edit innerhtml. I think your best bet would be to create a hidden element, and use that to store your variables.
i cant find an answer to this
i have been learning ajax lately but i learned how to do it all in javascript
now i go swiming around ajax question here and almost all are using jquery
so i end up confused. should i use normal javascript or do it through jquery?
so what are the differences?
this is my normal approach
var xmlHttp = createXmlHttpRequestObject(); //you first create the object to this function global
function createXmlHttpRequestObject() //here you instruct the function
{
var xmlHttp; //here you tell it to use the local variable not the global version of it because this returns to the global with the propper values
if (window.XMLHttpRequest) //if the "window" or browser is aware of this Object 90% of browsers
{
xmlHttp = new XMLHttpRequest(); // if true then the variable is now equal to the heart of ajax
}
else //for internet explorer
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp; //we return it back to daddy the global variable this objects does everything
//this object is everything in ajax for the most part
}
function process() //function that gets called on load of the body
{
if(xmlHttp) //if its not void or if you can run ajax
{
try //try catch statement are sort of required for the heart of things like ajax and server communication
{
xmlHttp.open("GET", "bacon.txt", true); //here 1st type of call 2nd from where 3rd
//is it true assyscronly or at the same time
//it does not start the connection to the server, its only sets up settings for the connection
xmlHttp.onreadystatechange = handleServerResponse; //anytime something changes[propertie]
//i want to call that function handleserverresponse
//begin communication
xmlHttp.send(null); //this is what communicates to the server makesure on ready statechane before this
//if the server responds you want to make sure everything is taking care of like what function onready state change is it going to call
//or what to do like open a text file in this case
} catch(e)
{
alert( e.toString() ); //alert the error message as a string on a popup
}
}
}
//handling the server response
function handleServerResponse()
{
theD = document.getElementById('theD'); //get the div in a var
if(xmlHttp.readyState==1) //if the connection to the server is established
{ //google crhome may not show this one, some browsers ignore some states
theD.innerHTML += "Status 1: server connection established<br>";
}
else if(xmlHttp.readyState==2) //request received, hey client i am the server and i received your request
{
theD.innerHTML += "Status 2: request reveived <br>";
}
else if(xmlHttp.readyState==3) //while is doing its thing
{
theD.innerHTML += "Status 3: processing request <br>";
}
else if(xmlHttp.readyState==4) //your request is finished and ready
{ //it means your response is ready but doesnt guaranteed no trouble
if(xmlHttp.status==200) //if the status is 200 then is succesufll
{
//IF everthing finally good THE GOOD PART
try //put all your calls on a try statement REMEMBER
{
//get the txt file as a string
text = xmlHttp.responseText; //response text n a normal string
theD.innerHTML += "Status 4: request is finished and response is finished";
theD.innerHTML += text;
}catch (e)
{
alert( e.toString() );
}
} else //for the other statuses like 404 else somehting went wrong
{
alert( xmlHttp.statusText ); //this will give you a status report on the wrong
}
}
}
jQuery simply wraps all of the XmlHttpRequest calls into a simple to use library. In the guts of jQuery you will see code that creates the XmlHttpRequest objects.
You can see the code that does this here:
https://github.com/jquery/jquery/blob/master/src/ajax/xhr.js
The nice thing about using a framework like jQuery is that they handle a lot of the browser idiosyncrasies for you. They also handle a lot of the edge cases you might not think about when writing your code.
Using jQuery is just for ease of use. If you prefer doing it the javascript way then carry on doing that.
jQuery ajax calls do exactly the same as what you are doing but jQuery is a javascript framework which simplifies what you write.
jQuery is a javascript framework which contains library of simplified functions compared to the Native Javascript. One of the functions is the XMLHttpRequest.
This way we just need to implement functions that is needed to implement without needed to write the traditional codes to setup the AJAX system to work
You may learn more about jQuery ajax here:
http://api.jquery.com/jQuery.ajax/
I am pretty new to creating web applications, so I am very unfamiliar with working over a web server. Just to let everyone know, I am implementing html, javascript, strawberry perl, AJAX, and running over an APACHE 2 web server. I finally have my web app working, I have an html file that calls a perl script that is in my htdocs directory. Here is a mock up of my .html file for reference, this one simply alerts the user of the output printed by the perl script:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
var str;
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Get output from perl script and print it
str = xmlhttp.responseText;
alert(str);
}
}
xmlhttp.open("GET","http://localhost/try.pl" , false); //perl script
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Example</h2></div>
<button type="button" onclick="loadXMLDoc()">Display</button>
</body>
</html>
So this file test.html calls a perl script [try.pl] within the same directory. Also, the perl script just prints a number so this alerts the user of the number. This is just an example of my implementation. My actual perl script and java script [inside the ready state block] is much more complicated. Now I have to add functionality to my web app, so to my questions:
I am looking to run a second and separate perl script when a different event happens. For example, when a button is clicked this perl script is being ran. I am going to have another different event, say a double click on an icon or something, that will need to call this second perl script. Will I simply have the new event call a different function [the first is called Loadxmldoc()] that is almost identical to the one I have here except it will have different code in the ready state block and call a different perl script at the end of it? I am a little confused as to how to implement this.
Also, If I have a list of file names within my javascript code, I need to process EACH of the files using a perl script. Currently I am only processing one so calling the perl script as I have here is fine. I have looked all over the internet to try to find how I would do this but it seems every explanation just covers how to call "a" CGI script. So within my code, say where I am "alerting" the user, I am going to have an array that stores the file names. I need to iterate over this array and for each filename [array element] I need to call the same perl script to process that file. How should I go about implementing this? Currently, my html file is only calling the perl script once and I do not know how I could call it for EACH file since my GET command is outside of my ready state block...
Any help or direction would be appreciated. I am expected to deliver soon and have been spending way too much time sifting through repetitive examples that haven't helped me...:/
As far as generalizing your AJAX request, you can create a function (or rather, a set of functions) that would process different types of responses, as follows:
var requests = [];
requests['script1'] = "http://localhost/try.pl";
requests['script2'] = "http://localhost/try2.pl";
var response_processing = [];
response_processing['script1'] = function (xmlhttp) {
var str = xmlhttp.responseText;
alert(str);
};
// Here, you can add more functions to do response processing for other AJAX calls,
under different map keys.
Now, in your AJAX code, you call an appropriate request AND appropriate response processor, based on your script name (passed to loadXMLDoc() call as follows): loadXMLDoc("script1");
function loadXMLDoc(script_name) {
// Your generic AJAX code as you already implemented
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
response_processing[script_name](xmlhttp);
// Careful so script_name doesn't get closured in onreadystatechange()
}
}
xmlhttp.open("GET", requests[script_name], false); //perl script
xmlhttp.send();
}