Forum Moderators: open

Message Too Old, No Replies

PHP called by onclick cannot output to txt file

         

tasios

12:48 pm on Jan 10, 2009 (gmt 0)

10+ Year Member



Hello to everyone,

In my main page I have an onclick event that calls a function. This function uses xmlHTTP to pass some variables to a php, for further processing.

I want that php file to output to a txt file. I use the method with fopen(file-name, text) but that does not create the file.

However, fopen() works when called by my main page.

Can anyone tell what am I doing wrong?

Thanks a lot!]

P.S. I also had the same problem with echo. I assume it has something to do with the php file being called by the main page.

methode

4:14 pm on Jan 10, 2009 (gmt 0)

10+ Year Member



correct syntax for a function which uses fopen() in the way you mention is like this:

function defunc($data){
$fp = fopen('path/to/file.txt', 'w');
fwrite($fp,$data);
fclose($fp);
}

If you want to append to the file, use $fp = fopen('path/to/file.txt', 'a')

If you use the fopen() in the way you specified, then definitely that's the problem. Try searching the error_log, if exist.

What's the issue exactly with the echo() ?

tasios

6:29 pm on Jan 10, 2009 (gmt 0)

10+ Year Member



Thank you methode for your answer.

I am using the syntax you propose. I mean, that is the one I used the first place; and it does not work.

In order to get a better understanding of my problem, I think I have to inform you that I am writing a plugin for wordpress (tell me if you don't know).

I am trying to achieve this:

1. Place an input text and next to it a submit button. achieved
2. Pass the variable of the input text to a javascript-defined function when the button is clicked. achieved
3. The javascript function uses xmlHttp to pass the value of the variable to a php file. achieved
4. The php file to output its results to a file located at the user's computer. not achieved

I am testing the results to a localhost created with WAMP. So, I expect the file to be created at the same file my php file is located... provided that I don't define a certain path.

Can you help me? If there is anything you don't understand, please tell me.

Thank you!

P.S. Is there any way I can send files via this post; so that I can send you my files.

methode

6:58 pm on Jan 10, 2009 (gmt 0)

10+ Year Member



Actually am a WP plugin developer so I know what it is :)

With PHP you will never reach the end-user's PC in any way other than cookie. Even the clipboard is hard to reach with JS (+Flash), so the HDD is definitely a big no.

On localhost you will certainly achieve the result i guess as it's local, but to reach a remote HDD, nah. May I suggest to create the file on the server then prompt for download.

Think with the browser's mind: it will think that the file you want to put on the HDD is malicious, would never allow it, even if you sign it with a certificate standing on your head on the Googleplex's top.
Like a pop-up. I can put as many window.open in window.onload, it will always get blocked cos it's less likely the user asked for that pop-up than a camel on Antarctica.
If it would allow automatic file creation (other than cookie), in no time my hard disk would be full with malicious code/executable. Like those stupid Virus codecs: if you visit the site the spammers ask you to go, you will be prompted to download the codec, because it doesn't let ANY programming language to put anything else than cookies on your HDD.

Without disclosing the plugin features or what will it do, could you tell me what is the purpose of the file which should be created on the user's end?

Now that I wrote a smaller novel, did I misunderstood something and you actually don't want to put anything on the end-user's PC?!

tasios

7:30 pm on Jan 10, 2009 (gmt 0)

10+ Year Member



Wow! You are a wp plugin developer? That is just great...

Your idea of letting the user download the file I create is not bad at all.

What is the file about? Well, the plugin adds a menu option at settings panel of the administrator. There, all the posts are ordered from last to first posted (descending, that is).

On the top of this menu, above the posts, there is an input text area where the user gives a number. This number says to the plugin how many posts to use in order to create an xml file.

So, that is what it's all about.

Say, for example, the user writes 5 and presses the send button, located next to the input text area. I, having attached a function to the onclick event of the send button, want this information to be send to a php file that will create an xml file of the last 5 posts and present it to the administrator.

That is why I use javascript and xmlHTTP. Because I want this to happen once the button is clicked.

methode

7:51 pm on Jan 10, 2009 (gmt 0)

10+ Year Member



Sure thing. Since you're in the admin back-end no-one should complain about a file download since all the backups and import/export stuff of WP is managed that way.

Now what's the issue with that echo() cos you mentioned it and didn't tell a word regarding the issue. it's like telling a kid "You get a candy" then throwing it 10 miles away
Not the kid

tasios

8:17 pm on Jan 10, 2009 (gmt 0)

10+ Year Member



When I write an echo in the file of the plugin the text appears, as it is supposed to be, at the page of the plugin.

However, this is not the case with the echo at the php file that I call via javascript. When I write an echo there, its text does not appear at the page.

methode

9:13 pm on Jan 10, 2009 (gmt 0)

10+ Year Member



I guess the issue should be at the XHR. If am not mistaken the php file does echo what it should even if you don't see, the problem is that JS can't catch it. Most likely because:
1. The XHR never reaches the 4th state (completed)
2. You don't catch the answer of the php file and push it in a container.
3. Both

Let's assume you have a span with "catcher" id where should conain the answer of the PHP file.
You have a JS function which listens to the XHR: if it's completed updates the catcher span with the data received from the php file, like this:
function updateCatcher(){
if (XHR.readyState==4 ¦¦ XHR.readyState=="complete"){
document.getElementById("catcher").innerHTML=XHR.responseText;
}
}

XHR is the object which controls the... well... the XHR. It's browser specific, in IE's case its an ActiveX object called either Microsoft.XMLHTTP or another one I don't remember (google it, its something with "XMLHTTP" and is an ActiveX object), at all the other decent browsers (pun intended MS) is XMLHttpRequest(). By the way, XHR is the abbreviation of XmlHttpRequest.
You call the above within your function which is called on the onclick event.

So, something like this. If I find it, will post a link to a W3 school page where all the above is explained clearly cos i guess my explanation is like a worm hole: huge and not understandable. Questions? Ask :)

[edit]: here's the linkie: [w3schools.com...]

tasios

10:09 pm on Jan 10, 2009 (gmt 0)

10+ Year Member



I think it's number 2!

Thanks a lot methode.

However, I haven't solved the xml problem. I know we said I should make it downloadable, but do know how could I do this?

Thanks.

methode

9:18 am on Jan 11, 2009 (gmt 0)

10+ Year Member



Sure.

Take a look in your WP installation's /wp-admin/includes/export.php

That's the file which contains the necessary functions to export specific author's posts as an XML file. Make a copy of it and modify it in the best way to fit your needs. Put the modified file in your WP plugin's directory, then modify the onclick event's function to call the current page but with an additional variable set. Like
http://example.com/wp-admin/edit.php?ADD_VAR=TRUE&user=john+doe&num=5

Your php function should catch the variables only if ADD_VAR == true, then construct the xml file, maybe save it, but that's optional, and lastly force download by sending forced download specific HTTP headers, which are:

header('Content-Description: Some title');
header('Content-Disposition: attachment; filename=some_file.xml');
header('Content-Type: text/xml; charset= UTF8);

But take a look on that WP file, it will give you inspiration.

tasios

1:04 pm on Jan 13, 2009 (gmt 0)

10+ Year Member



methode, thanks a lot. You were very helpful.

Can I ask you one last thing? It seems I have another problem with this combination of javascript and php.

At event onclick I have attached another php file which I want to modify the database I have created for wordpress. I have created other such php files, but this one seems to be so stubborn...

Here is the code:

>

--------------------------- Start of Code ---------------------------
<?php
$number = $_GET['num'];

$con = mysql_connect('myhost', 'myusername', 'mypassword');
if (!$con)
{
die("Could not connect: " . mysql_error());
}

mysql_select_db('mydatabase', $con);

$sql = "UPDATE mytable
SET mycol = '$number'
WHERE id = 1;
";
mysql_query($sql);

mysql_close($con);
?>
---------------------------- End of Code ----------------------------

However, the value is not updated and I am not able to find what is going wrong.

Do you have any idea?

Thanks!

methode

5:09 pm on Jan 13, 2009 (gmt 0)

10+ Year Member



woah, php and mysql. I missed them so much.

On first look, you surely missed to put in quotes the selector's value (WHERE id = '1').
On second look, placing your $sql variable in the mysql_query() function will look like this:

mysql_query("UPDATE mytable SET mycol = '$number' WHERE id = 1;");

When it should look like this:

mysql_query("UPDATE mytable SET mycol = 'a_number' WHERE id = '1'");

So the modification should be committed in the $sql variable to make it look like this:

$sql = "UPDATE mytable SET mycol = '$number' WHERE id = '1'";

I stripped the line breaks because it's easier to read and debug. Put them back if you wish.

Somebody please correct me if am wrong, i didn't touch PHP for some time.

A quick guide to mysql manipulations (in this case the UPDATE) from PHP: [w3schools.com...]

{am not affiliated with w3schools, I just find their content extremely useful}

tasios

5:40 pm on Jan 13, 2009 (gmt 0)

10+ Year Member



methode thank you very much for your answer.

However, the problem still exists. I can't update the table.

Thanks a lot for everything mate!

methode

6:02 pm on Jan 13, 2009 (gmt 0)

10+ Year Member



Hmmm. That's weird.

Some guesses regarding why it isn't working:

1. $number is not a number and MYSQL expects int (col type or what the heck is int(x) where X is a number)
2. id 1 doesn't exist.
3. I messed up the query.

The third is the most likely, but please double checkthe database too. If you're on a UNIX based server (you know, CentOs, red hat, etc.) and managed by cPanel, you have PhpMyAdmin installed. If you have, try it out, it's the easiest way to manage databases and to look in problems.

If you have PhpMyAdmin I suggest you to run the query manually ($sql) in PhpMyAdmin, see if it works or see what that big, red, ugly, trout-like error message says. If it passes through and the table gets updated, then above the table should be a link saying something like "create php code". Press it, then use the code it suggested.

I will ask for money from cPanel and w3schools for referring users to them /*slaps himself with a steak*/

tasios

1:02 pm on Jan 14, 2009 (gmt 0)

10+ Year Member



methode, I 've just found out what the problem is.

The function the onclick event is located in is presenting a menu in the administrator's panel at wordpress.

So, when I was calling a php file with the url:

'wp-content/plugins/myplugin/myphpfile.php'

I was expecting it to read:

'localhost/wordpress/wp-content/plugins/myplugin/myphpfile.php'

but, it was reading:

'localhost/wordpress/wp-admin/wp-content/plugins/myplugin/myphpfile.php'

because I was calling it from a function that was creating a submenu in the administrator's panel.

To give you a better idea, those are the functions I used:

add_action('admin_menu', 'aFunction'); -> to add the submenu at admin's panel

aFunction() -> to create the submenu's properties
{
if (function_exists('add_submenu_page'))
{
add_submenu_page('options-general.php', __(Settings), __('TagRank Plugin'), 2, __FILE__,
'myFunctionCreatingSubMenu');
}

myFunctionCreatingSubMenu() -> to fill in the submenu; this is where the onclick is called.

So, it was all a matter of wrong url... my mistake. I didn't know it would that.

Thanks a lot for all your help and sorry for the trouble; I should have found out sooner.

P.S.: I tried changing the method I was using for calling the php. Instead of the onclick event I used the action property of the form and that is where it throwed me the message that the url 'wordpress/wp-admin/...' could not be found. Thanks again!

methode

1:15 pm on Jan 14, 2009 (gmt 0)

10+ Year Member



Well... s**t happens... even with the best :)
please, let me know somehow when your plugin is finished and is on the repository, would like to check it out cos, to be sincere, I still have no idea what it will do and am quite interested. or at least tell me the plugin name and will watch for it. Would appreciate it. Thanks

BTW, a tip: publish your plugin on a weekday cos you will get natural linkback from webblogtools (or something like that). If this is your first plugin and you didn't mess yet with SVN and you need help with it, let me know. Sometimes it can be a nightmare to publish a plugin on the SVN repo.

tasios

9:38 am on Jan 15, 2009 (gmt 0)

10+ Year Member



Well, I guess s**t happens all the time.

I am sorry to ask you again, methode, but do you have any idea why a status 0 would be returned to a xmlHttp request?

My url is good, the variables at the uri get the values I want them to have... I can't figure out what is going on.

To give you a picture... I have this

<input type='button' onClick='someFunction(value1, value2); return false;'>

and the function is something like that

function someFunction(value1, value2)
{
try
{
var xmlHttp = new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e)
{
alert('Your browser does not support AJAX!');
return false;
}
}
}
var url = '../wp-content/plugins/TagRank/xmlPosts.php';
url = url + '?value1=' + value1;
url = url + '&value2=' + value2;
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
}

Can you think of what is going wrong here and the php called returns a status 0 when reaching state 4?

Thanks a lot!

P.S.: I hope this is the last time I have to ask you something...

methode

4:05 pm on Jan 15, 2009 (gmt 0)

10+ Year Member



First of all, Get rapidly Firebug (Firefox developer extension or plugin or addon or what the heck), it will help you a lot. Just google "firebug"

What do you mean by status 0 when reaching state 4?
XHR state 4 means the request was completed as it should. On the other hand I think you do talk about XHR state because there's no HTTP 0 status code, even if there's no content. Yay me, I got confused.

In your example: <input type='button' onclick='somefunct(value1, value2); return false;'> or something like this, put the two values in doublequote. Or if you want to grab the values from another source use getElementById('some_element'). value or .innerHTML, depends on the element.

I'm sorry but at the moment I can't respond as fast I would like because I made the mistake to install Windows 7 and now I have no mail client, yet /*slap*/

I don't mind if you ask. At least you will learn something and I have the time to answer anyway.

tasios

7:47 pm on Jan 15, 2009 (gmt 0)

10+ Year Member



var url = 'http://' + window.location.hostname + '/wordpress /wp-content/plugins/TagRank/addnewtag.php';

url = url + '?myvalue1=' + value1;
url = url + '&myvalue2=' + value2;
alert(url);

xmlHttp.open('GET', url, true);
xmlHttp.send(null);

xmlHttp.onreadystatechange = function check()
{
if (xmlHttp.readyState == 0) alert(\"0\" + xmlHttp.status + xmlHttp.responseText);
else if (xmlHttp.readyState == 1) alert (\"1\" + xmlHttp.status + xmlHttp.responseText);
else if (xmlHttp.readyState == 2) alert (\"2\" + xmlHttp.status + xmlHttp.responseText);
else if (xmlHttp.readyState == 3) alert (\"3\" + xmlHttp.status + xmlHttp.responseText);
else if (xmlHttp.readyState == 4) alert(\"4\" + xmlHttp.status + xmlHttp.responseText);
}

I 've changed the initial javascript a little, so it would give some feedback about the progress made. As far as I can tell, the url appears to be fine with myvalue1 and myvalue2 taking the values of value1 and value2.

You are right about readyState and status. I tested other php files and, although it returns on readyState == 4 the status is still 0. So, 0 status is not important. It does not mean that the variables don't take their values, as I have been initially thinking. A google search showed me that status 0 may be returned if you are working on a localhost(!). Anyway, that is now my main worry.

I 've been meaning to ask you this:
The button I press, the one with the onclick handler that triggers the function making the xmlHttp request, does not always yields the effect I want.

And the odd thing here is that it does sometimes. If it were not to do it all the time I would think that something is going wrong with the php file. But it works sometimes.

Allow me to explain myself... I want that button to add a new tag to the current post. So, the function called with the onclick event handler calls a php file that changes wordpress's tables to include the new tag.

The problem is that, although the name of the new tag, the id of the current post and the id of the current user (the variables I need) are assigned the correct values, and these values are passed to the values of the url used for the xmlHttp request correctly, the tag is not added, all the time.

E.g., I have come accross the situation where I use, let's say, the tag name "pentium" and press the "Add" button. The tag is not added. Immediately after that I give as a tag name the name "pentium", again. And, alas, it is added and appears along with the current tags.

I call this function from a function that I added to single.php of wordpress.

My question is what am I doing wrong? The variables are passed correctly, the url is good, there is no if statement at the php file responsible for the addition of the new tag (so to blame for not making the addition all times)... I can't think of something I am doing wrong.

This evil wordpress is to blame for :-)

Thanks for all your help, methode.

P.S.: I tried putting double quotes around the variable but did not achieve anything :-(

P.S.: Is it possible that there is something wrong with another php called by my main file that creates this kind of mess?

methode

10:41 am on Jan 21, 2009 (gmt 0)

10+ Year Member



OK, first of all sorry for being late to the party.

On localhost the XHRs are acting weird almost all the time, i'd recommend it to test it on a server. I guess you do have a server or a hosting account where you can test it live, if you do not, let me know and I'll set an account up on my (US based) server till you finish the plugin. Of course it would be free, and my only request is to not use it for hosting purposes.

WP is not evil, you have to understand it than it's like a baby sheep ;)
I'm almost sure that not WP is the issue

If you want to check whether there's issue with your PHP file or not, look for a file named error_log or in the Apache dir for the logs. There you should find entries which may enlighten the situation.