Calling Javascript Function In PHP Not Working - php

I'm new to Google Documents and have set up a spreadsheet that accesses the amount of "Likes" on three different Facebook pages. The code is part of the library on Google Documents but I'm trying to take the resulting total and pull it up on my site which is PHP. I'm starting simply with one site just because I can't get it working.
Here is the Javascript that was written to compile the likes:
function FacebookFans(aPageId)
{
if (aPageId === undefined || aPageId === null)
{
throw "No parameter specified. Write Facebook PageID as parameter."
}
if (typeof aPageId != "number")
throw "Parameter must be number.";
// See http://developers.facebook.com/docs/reference/fql/page/ for API documentation
var url = "http://api.facebook.com/method/fql.query?query=SELECT%20page_id,page_url,fan_count%20FROM%20page%20%20WHERE%20page_id=%22" + encodeURIComponent(aPageId) + "%22";
var response = UrlFetchApp.fetch(url);
if (response.getResponseCode() != 200)
throw "Unexpected response code from Facebook.";
var responseText = response.getContentText();
if (responseText == null || responseText == "")
throw "Empty response from Facebook.";
var fan_count = 0;
try
{
var xml = Xml.parse(responseText, false);
var page = xml.getElement().getElement();
if (page == null)
throw "Wrong PageID.";
fan_count = parseInt(page.getElement("fan_count").getText());
}
catch (e)
{
throw "Problem with response from Facebook: " + e;
}
return fan_count;
}
Now, to preface, I am very new at Javascript so don't kill me if my code is way off, I'm still trying to understand. I tried to run this in the body:
<script type="text/javascript">
document.write(FacebookFans(40796308305));
</script>
I figured the function returns a value and this would print that value out (the number btw is Coca Cola's Facebook page ID, figured it was a good one to test with). Is this a conflict between Javascript and PHP? I know that's a mixture of client-side and server side scripts. The reason I'm not sure what's wrong though is that I set a var inside the Javascript and then used to document.write to call it back just to test that my code was valid and it recalled the var fine. Anyways, any help is greatly appreciated. Thanks.

I used the Google Docs script debugger to step through your script.
The first arrow is what starts the script. In the dropdown for Select Function, choose the "doit" function I created (see bottom of screenshot). Finally, you can click where the second arrow is pointing and create a breakpoint, so the debugger stops.
After stepping through all of your code, you'll be glad to know it works just fine.
Your problem must be related to your understanding of how/when the code will be run. Note there is NO PHP in any of this code, so I'm not sure why you were asking about PHP.
You need certain "Actions" to run your scripts. You can read more about how scripts are run in Google docs. But your document.write doesn't apply here because you aren't writing a script for a webpage. You are inside the Google Docs environment.
If you want to run your script outside of Google Docs, you have a problem with the UrlFetchApp call, since that is a Google specific thing. If you load that script (and put it inside tags) in a .html doc, you can use Google Chrome to find out the errors. Select Wrench Icon->Tools->Javascript Console and it will show you the error right away. Now, normally you could just translate this to something else, but Javascript does its best to prevent you from making cross domain requests (learn more).
To translate this into server side code, it's pretty simple in PHP. You are basically just calling one url and then parsing it with XML. To load the contents of the url, use file_get_contents and then parse the xml.

If FacebookFans(40796308305) really works and returns result, so the problem is somehow in document.write.
Try:
<script type="text/javascript">
alert(FacebookFans(40796308305));
</script>
To be sure that the function works. And:
<script type="text/javascript">
var a=FacebookFans(40796308305);
document.write('a='+a);
</script>
To check the different types of issues.
If nothing helps, so we need more info, how do you invoke this function.

Related

I seem to be unable to get AJAX/JS to reload a PHP script and update various page elements

So here is the situation. I'm building a page to host a radio stream hosted on an Icecast server. I got the player working great and cobbled together a PHP script to extract and parse out various data points from the server. Information such as current track, number of listeners, etc.
Here's the problem. It loads fine when the page is first opened, but I can't figure out a way to get these variables to be updated every 5-10 seconds or so and update the page with the new information WITHOUT reloading the page completely (it is a radio station after all, and having to re-buffer the station ever 10 seconds just isn't feasible.
Here's what I have so far, after various attempts have been removed from the code. Any ideas? I've seen it done for one or two variables, but I have almost a Dozen here...
<div id="current_song"></div>
<script language="javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script language="javascript">
{
$.ajax({
type: 'POST',
url: 'script.php',
data: 'getLatestInfo',
dataType: 'json',
cache: false,
success : function(dp){
$.getJSON('script.php', function(dp) {
//'data' will be the json that is returned from the php file
$.("#current_song").html("dp[9]");
});
getlatest();
};
});
}
</script>
and here is the PHP parser
<?php
Function getLatestInfo() {
$SERVER = 'http://chillstep.info:1984';
$STATS_FILE = '/status.xsl?mount=/test.mp3';
$LASTFM_API= '27c480add2ca34385099693a96586bd2';
//create a new curl resource
$ch = curl_init();
//set url
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE);
//return as a string
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//$output = our stauts.xsl file
$output = curl_exec($ch);
//close curl resource to free up system resources
curl_close($ch);
//loop through $ouput and sort into our different arrays
$dp = array();
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$output,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($dp,$to_push);
}
}
$x = explode(" - ",$dp[9]);
echo json_encode($dp);
}
?>
I know it doesn't look pretty yet, but that's what CSS is for right?
Any ideas? Essentially I need the PHP script to rerun, update the variables, and rebuild the text output without touching the audio tag.
Javascript is code that executes client-side (on the website visitors machine) and PHP executes serverside. The way to insert content into a page without reloading the entire page is to use Javascript to inject code into the HTML. Now, for example, say that you have a PHP file on your server, called getLatest.php with a function called getLatestVariables() that finds out the latest values for all your variables and returns an array containing them. What you can do is use javascript to call getLatestVariables() from getLatest.php, and when the function returns the array, it will return it to the javascript. Once the array of variables has been returned to the javascript you can then insert the variabes into HTML divs without having to refresh the entire page.
to call the php function I suggest using jquery to perform an ajax call
also to insert the data returned from the php, jquery is your best bet too.
You need client side JavaScript for this. Get your hands on basic ajax books.
You can request the script for updated data every 5 seconds and update it on the page, this is complicated and needs some knowledge of JavaScript.
The script will have to be new too, or this one edited to trace type of request and return data accordingly.
var url="http://script-address"
var req = new XMLHttpRequest(); // Begin a new request
req.open("GET", url); // An HTTP GET request for the url
req.send(null);
This is how you can check the response
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
//we got a complete valid HTTP response
var response = req.responseText;
//code to handle response
}
php is a serverside language, so re-running the php inside your page will always result in the entire page refreshing, however if you use a javascript ajax call (I suggest using jquery) to a different php file, that php file can be executed serverside without affecting your page. you can then return the newly found variables from this php file to the javascript, and insert them in the callback of the ajax call.
see the answer to this question
If you need any more detail let me know...
$.getJSON('phpFileThatReturnsJSON.php', function(data) {
//'data' will be the json that is returned from the php file
$.("#idOfDivToInsertData").html("an item from the json array ie data['song']");
});
look at JQuery docs for ajax calls, if you've got this far you should be able to nail it out pretty quickly.
Also dont forget to include the jquery library in your html header...
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>

Call JavaScript Function From PHP Script Using jQuery getScript

I'm very new to jQuery & web development in general. I'm attempting to use jQuery's ".getScript()" method to load a couple JavaScript scripts that are written in a particular PHP file, but I think I'm missing something.
(NOTE: I noticed several different questions that looked like they had the potential to help me, but none did. If there's one you know of, feel free to point me in that direction. Thanks.)
When I debug this in Firebug it hits the ".getScript()" call & then jumps on to the next line, seemingly without executing.
Here's how I'm trying to do it:
jQuery.getScript("relative/path/to/script/phpScript.php", function(){
alert("I'm HERE!");
setValues(); // JavaScript function that's written by phpScript.php
});
In this case, the JavaScript is being generated by the "phpScript.php" file and my "alert()" never gets run, but I'm not sure why. Any ideas?
I did notice that I'm getting some kind of parse error by following a suggestion in another question. I don't know how to resolve that. Here's the code for that:
jQuery(document).ajaxError(function(event, request, settings){
alert('error loading: ' + request.status + "\nevent: "+ event);
for (var key in request){
if (request.hasOwnProperty(key)) {
alert(key + " -> " + request[key]);
}
}
});
BTW, we're running jQuery with "jQuery.noConflict();" set, which is why I'm not using the shorthand "$()" notation.
Here is a snippet from the response body from the GET call in getScript():
<html><script type="text/javascript">
function setValues()
jQuery("#formname").text(window.formNAME);
jQuery("#Form_Path").text(window.formPATH);
jQuery("#Form_DB").text(window.formDB);
jQuery('#pertaining_to').text(window.pertainNAME);
jQuery("#Pertain_To_ID").text(window.pertainID);
jQuery("#Form_ID").text(window.formID);
jQuery("#Field_ID").text(window.fieldName);
}
</script>
<head>
Thanks in advance,
-Mark
If you're loading JS scripts, try writing them as discrete functions into a .js file (e.g.: jsscript.js) and then using this HTML line:
<script type='text/javascript' src='jsscript.js'></script>
Then you can just call the functions themselves without using .getScript().
(Of course, you need to put the above line before the point where you call the scripts.)
That seems like a much cleaner way of doing it than what you're currently attempting.
EDIT: Given your present circumstances (i.e.: a PHP page that generates JS scripts and a PHP page that calls the scripts), maybe you can so something like this?
//PHP page that generates the scripts
function gen_script() {
//JS script generated into $script variable
return $script;
}
//PHP page that calls the scripts
include ('generate.php');
echo gen_script();
I thought you may just edit your phpScript.php file as
function setValues(){
jQuery("#formname").text(window.formNAME);
jQuery("#Form_Path").text(window.formPATH);
//...
}
That will be OK.

Setting a PHP $_SESSION['username'] using a jQuery $.post call and a callback method

I've researched and played around a fair bit, but I am stumped. Essentially I want to setup my site so that it can detect if a user is 'logged in' and thereby change the way it looks: removing the "Sign In" link and replacing it with a "Sign Out" link, and so forth.
For testing purposes I started my index.html page with:
<?php
session_start();
$_SESSION["username"]="javaman";
?>
Next, I call my setup function from within the jquery document.ready:
$(document).ready(function() {
setup_page();
};
The setup function looks like:
function setup_page()
{
var username = get_user();
//check for error
var index = username.indexOf("error");
//if not an error
if(username.length > 0 && index == -1)
{
//do the jquery calls to hide/show links
}
}
And that get_user function looks like:
function get_user()
{
var result;
$.post("./session.php", {action : "get", key : "username", value : "val"}, function(data){
result = data;
});
return result;
}
The session.php is a simple app that takes in 3 post values and hopefully spits out the proper result, the problem I am running into is that the js result variable is often undefined, especially so when I debug via the IE dev toolbar. FF seems ok though. Am I using the callback in the correct way? I've tried putting alert() functions everywhere to figure out where the code is screwing up, but that doesn't help either as often the alert's say the result is undefined. Meanwhile, it seems like the get_user calls the post function but the stack immediately returns and never gets to the return statement until AFTER the get_user has returned a value of.. undefined. I believe I am misunderstanding the code flow here. I am used to C where logically one function follows another. In that vein I am interpreting the callback to essentially be like:
int i = callback_function(post("some data"));
So in my mind the post completes it's action and then calls another function or at least performs another action and then that completes and then the get_user can return it's value.
Or is the order of operation: post, get_user, callback?
...confused in Seattle
Internet Explorer does not natively support indexOf on arrays. Use jQuery's $.inArray() instead:
var index = $.inArray("error", username);
Keep in mind that AJAX stands for Asynchronous Javascript and XML. So the callback fires as soon as a response comes, but the rest of execution goes on. If you want to lock the execution until AJAX-request will be completed, use
$.ajaxSetup({async:false});
before AJAX call.

Ajax request with Javascript

I have a page on which I want to show a couple of MySQL tables.
There is one table on the right that may only change when a different person is selected.
De second table is the main table in the center. I have a dropdown box with contains every person. The results from the selected person is showed in the middle table. There are multiple results for each person so there is a second dropdown box to choose which of these results you want to show. This is al done by a Ajax XMLHTTP request.
The problem is that the right table uses some javascript. I know this is not possible with Ajax in combination with a XMLHTTP-request. But without the javascript I can't make what I want. Is there a way, to show the right table after the javascript is finished doing his work?
I now use frames. This is not very nice. Because I have to style both pages to look nice together, and that's not so easy as said. But this way it is doing as I want it to be.
So I searched the internet (a long time) and just a few minutes before I wanted to give up i found this piece of code (coming from http://www.javascriptkit.com/dhtmltutors/ajaxincludes.shtml):
function HttpRequest(url){
var pageRequest = false //variable to hold ajax object
/*#cc_on
#if (#_jscript_version >= 5)
try {
pageRequest = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try {
pageRequest = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e2){
pageRequest = false
}
}
#end
#*/
if (!pageRequest && typeof XMLHttpRequest != 'undefined')
pageRequest = new XMLHttpRequest()
if (pageRequest){ //if pageRequest is not false
pageRequest.open('GET', url, false) //get page synchronously
pageRequest.send(null)
embedpage(pageRequest)
}
}
function embedpage(request){
//if viewing page offline or the document was successfully retrieved online (status code=2000)
if (window.location.href.indexOf("http")==-1 || request.status==200)
document.write(request.responseText)
}
}
HttpRequest("external.htm") //include "external.htm" onto current page
This code works perfectly... The first time. As soon as you change the person the whole page disappears and only the table shows up and firefox keeps "loading" the page (you see that circle going round). I do know how to edit the code above to fit my needs but I have no understanding of Ajax or how to fix this problem. Hopefully someone can help me and give me a good solution! And tell me why the code above isn't working properly?
Thanks in advance!
Milaan
document.write only works when the page is loading for the first time, Once the page rendering is done, calling document.write will clear the page first.
https://developer.mozilla.org/en/document.write
What you might want to do instead is:
if (window.location.href.indexOf("http")==-1 || request.status==200) {
var elm = document.createElement('div');
elm.innerHTML = request.responseText;
document.getElementsByTagName('body')[0].appendChild(elm);
}
It´s been a long time since I´ve seen code like this, but one problem I can see, is that you don´t include any kind of variable in your XMLHttpRequest; no user ID or anything. Is it just supposed to load a static page?
And is there any reason you can´t use a library like jQuery? It´s no magic bullet but it will make your life and ajax requests a lot easier.
You might want to use dom functions to add your downloaded content to the existing document, like:
document.getElementById('mypanel').innerHTML = '<html code goes here>';
The best idea probably would be to use a slim javascript framework lie jquery which helps you with browser compatibility.
jQuery should make things easier for you. Your code should look something like this.
$.post("somepage.php", function(data){
$("#divID").html(data);
});
<div id="divID"></div>
And somepage.php could be something like this:
<?php
// get table content
echo "<table>...</table>";
?>

Would Apache running on port 8080 prevent dynamically loaded scripts in JavaScript?

Had a nice PHP/HTML/JS prototype working on my personal Linode, then tried to throw it into a work machine.
The page adds a script tag dynamically with some JavaScript. It's a bunch of Google charts that update based on different timeslices. That code looks something like this:
// jQuery $.post to send the beginning and end timestamps
$.post("channel_functions.php", data_to_post, function(data){
// the data that's returned is the javascript I want to load
var script = document.createElement('script');
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
var text = document.createTextNode(data);
script.type= 'text/javascript';
script.id = 'chart_data';
script.appendChild(text);
// Adding script tag to page
head.appendChild(script);
// Call the function I know were present in the script tag
loadTheCharts();
});
function loadTheCharts() {
// These are the functions that were loaded dynamically
// By this point the script tag is supposed be loaded, added and eval'd
function1();
function2();
}
Function1() and function2() don't exist until they get added to the dom, but I don't call loadTheCharts() until after the $.post has run so this doesn't seem to be a problem.
I'm one of those dirty PHP coders you mother warned you about, so I'm not well versed in JavaScript beyond what I've read in the typical go-to O'Reilly books. But this code worked fine on my personal dev server, so I'm wondering why it wouldn't work on this new machine.
The only difference in setup, from what I can tell, is that the new machine is running on port 8080, so it's 192.168.blah.blah:8080/index.php instead of nicedomain.com/index.php.
I see the code was indeed added to the dom when I use webmaster tools to "view generated source" but in Firebug I get an error like "function2() is undefined" even though my understanding was that all script tags are eval'ed when added to .
My question: Given what I've laid out, and that the machine is running on :8080, is there a reason anyone can think of as to why a dynamically loaded function like function2() would be defined on the Linode and not on the machine running Apache on 8080?
jQuery supports javascript responses:
$.post("channel_functions.php", data_to_post,
function (data, textStatus, xhr) {loadTheCharts()},
'script');
However, a dataType of "script" will turn a cross-domain POST into a GET, as per the documentation.
The main problem with eval is the eval-ed code inherits the scope the eval is in. Instead, you can use jQuery.globalEval. Try something like:
$.post("channel_functions.php", data_to_post,
function (data, textStatus, xhr) {
/* data might have errors, which will cause an exception.
We'll let the default exception handler catch & log it.
*/
$.globalEval(data);
loadTheCharts();
});
Why don't you just eval the responseText? I don't see the need to create a new script node.

Categories