/    Sign up×
Community /Pin to ProfileBookmark

OnClick PHP Function

Hello,

Im just wondering if anyone knows of a way to do this with PHP.

I have an option box with a list of values corresponding to pages. If the user selects any of these pages, I would like to run a query to MySQL depending on the pageid associated with the selection, and display it without navigating away from the current page.

This will then give them the contents of the page they are trying to edit as a guide with the form beneath for any changes they wish to make. Once they make the changes the form can then navigate away from this page.

Any ideas?

Thanking you in advance

a.g.r.c

to post a comment
PHP

19 Comments(s)

Copy linkTweet thisAlerts:
@scragarJan 26.2008 — this is effectivly known as ajax. It needs javascript to work. There are tons of functions available that all do the task.

sorry I havn't said much, but since ajax is such a broad topic it's kinda hard to say much without an exact question to answer.
Copy linkTweet thisAlerts:
@a_g_r_cauthorJan 26.2008 — Ajax..... Exact question.... Where do I start?

?
Copy linkTweet thisAlerts:
@scragarJan 26.2008 — well, it's javascript function, but you should be able to set up this file(include it externaly via:
[code=html]<script src='ajax.js' type='text/javascript'></script>[/code] and be sure to read it first):
[code=php]/************************************************************************************************
* *
* CustomAjax.js by Scragar *
* *
*************************************************************************************************
* *
* see FAQ for information on usage and help. *
* *
*************************************************************************************************
* *
* This script is released with a licence that dictates: *
* *
* Any and all variations of this code fall under the same licence *
* *
* You may never charge for information or copies of this script, *
* either in it's orrigional or an modified form. *
* *
* You must not use this script, or any derivative there of to encrypt *
* or otherwise attempt to obscure information *
* *
* If requested you must provide a link to the home page of this script *
* *
*************************************************************************************************
* *
* If you choose to agree to these rules you may use or modify any code contatined *
* as detailed by the rules of the licence. This header may be removed, however *
* the licence must stay intact or all rights to this and variations of the script *
* are withdrawn. *
* *
************************************************************************************************/

/*
<script>
var SID = "<? echo ini_get("session.name")."=".session_id(); ?>&";
</script>

copy the lines above into your page to enable SIDs from PHP, if you have no idea what it is, or how to use it then the odds are you don't want it. You may want to avoid indiscriminate interpritation of query strings with this enabled.
*/

var reverseparam = false;
var defaultpage = "";
var apendqry = "";
var multiquery = false;
// do not remove next 3 lines!
var lookingfor = new Array();
var fillin = new Array();
var rptmode = new Array();
// a rptmode of 0 is to ignore all elements in the case of a repeat. DEFAULT
// a rptmode of 1 is to use only the first element.
// a rptmode of -1 is to use only the last element.
// a rptmode of 2 is to compound results in order.
// a rptmode of -2 is to compound results in reverse order.

// standard assignment of wanted variables.
lookingfor[lookingfor.length] = "";
fillin[fillin.length] = "";
rptmode[rptmode.length] = 0;


var onfailure = true;
var errofunc = false;
var onbusy = false;
var busyfunc = false;
var defaultReturn = false;
var resultfunc = false;

var loadingelement = "";
var loadingDelay = 0.75;

// anything I'm missing? let me know :P


/****************************************
* *
* end easy edit. feel free *
* to look, but I'd advise *
* you not to touch unless *
* you have a backup *
* :P *
* *
* PS. sorry if it's hard to read *
* *
****************************************/
if(!multiquery){
var ajaxResponse = false;
}
var numRs = 0;

function getxml(){
if(ajaxResponse){
if(busyfunc){
var tmp = busyfunc(ajaxResponse.status, ajaxResponse);
if(typeof(tmp) == "undefined")
return onbusy;
else
return tmp;
}else{
return onbusy;
};
};
if (window.XMLHttpRequest){ // firefox, flock, safari, konqueror, opera, netscape...
ajaxResponse = new XMLHttpRequest();
}else
if(window.ActiveXObject){ // IE
try{
ajaxResponse = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try {// more IE :( if only they could do things like normal browsers...
ajaxResponse = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
};
};
if( !ajaxResponse ){
return onfailure;
};
numRs++;
setTimeout("if(numRs > 0 && loadingelement){ document.getElementById(loadingelement).style.display = 'block';};", loadingDelay*1000);
ajaxResponse.open('GET', arguments[0], false);
ajaxResponse.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxResponse.send(null);
numRs--;
if(loadingelement && numRs == 0)
document.getElementById(loadingelement).style.display = "none";
if(ajaxResponse.status == 200){
var xmldoc = ajaxResponse.responseText;
ajaxResponse = false;
return xmldoc;
}else{
ajaxrespose = false;
return false;
};
};

function mkRequest(post, get, uri){
if(reverseparam){
if(!uri)
var tmp = "";
else
var tmp = uri;
uri = post;
post = tmp;
};

if(!uri)
var uri = defaultpage;
if(!get)
var get = "";
if(!SID)
var SID = "";
if(multiquery){
var ajaxResponse = false;
}else{
if(ajaxResponse){
if(busyfunc){
var tmp = busyfunc(ajaxResponse.status, ajaxResponse);
if(typeof(tmp) == "undefined")
return onbusy;
else
return tmp;
}else{
return onbusy;
};
};
};
if (window.XMLHttpRequest){ // firefox, flock, safari, konqueror, opera, netscape...
ajaxResponse = new XMLHttpRequest();
}else
if(window.ActiveXObject){ // IE
try{
ajaxResponse = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try {// more IE :( if only they could do things like normal browsers...
ajaxResponse = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
};
};
if (!ajaxResponse) {
return onfailure;
};
numRs++;
setTimeout("if(numRs > 0 && loadingelement){ document.getElementById(loadingelement).style.display = 'block';};", loadingDelay/1000);
ajaxResponse.open('POST', uri+"?"+SID+get, false);
ajaxResponse.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxResponse.send(apendqry+post);
numRs--;
if(loadingelement && numRs == 0)
document.getElementById(loadingelement).style.display = "none";
if(ajaxResponse.status == 200){
var xmldoc = ajaxResponse.responseText;
if(!resultfunc || resultfunc(xmldoc, ajaxResponse)){
var reg;
var j;
for(var i = 0; i < lookingfor.length; i++){
reg = new RegExp("</?"+lookingfor[i]+">");
j = xmldoc.split(reg);
if(j.length >= 3 && document.getElementById(fillin[i])){
switch(rptmode[i]){
case 2:
document.getElementById(fillin[i]).innerHTML = "";
for(var k = 1; k < j.length-1; k+=2)
document.getElementById(fillin[i]).innerHTML += j[k];
break;
case 1:
document.getElementById(fillin[i]).innerHTML = j[1];
break;
case -1:
document.getElementById(fillin[i]).innerHTML = j[j.length-2];
break;
case -2:
document.getElementById(fillin[i]).innerHTML = "";
for(var k = j.length-2; k > 0; k-=2)
document.getElementById(fillin[i]).innerHTML += j[k];
break;
default:
if(j.length == 3)
document.getElementById(fillin[i]).innerHTML = j[1];
break;
};
};
};
};
ajaxResponse = false;
return defaultReturn;
}else{
if(errofunc){
var tmp = errofunc(ajaxResponse.status, ajaxResponse);
ajaxResponse = false;
if(typeof(tmp) == "undefined")
return onfailure;
else
return tmp;
}else{
ajaxResponse = false;
return onfailure;
};
};
};

function formget(){
var strdata = "";
var x = arguments[0].getElementsByTagName("INPUT");

if(x.length != 0){
for(var i = 0; i < x.length; i++){
strdata += "&" + x[i].name + "=" + webencode(x[i].value);
};
};
var x = arguments[0].getElementsByTagName("SELECT");
if(x.length != 0){
for(var i = 0; i < x.length; i++){
strdata += "&" + x[i].name + "=" + x[i].selectedIndex;
};
};
var x = arguments[0].getElementsByTagName("TEXTAREA");
if(x.length != 0){
for(var i = 0; i < x.length; i++){
strdata += "&" + x[i].name + "=" + webencode(x[i].value);
};
};
return strdata;
};

function webencode(){
arguments[0] = escape(arguments[0]).replace('+', '%2B').replace('%20', '+');
return arguments[0].replace('*', '%2A').replace('/', '%2F').replace('@', '%40');
};[/code]


you can then do things like:
[code=html]<a href='nojs.php' onclick='return mkRequest('meap');'>send the message meap to server</a>[/code]
Copy linkTweet thisAlerts:
@a_g_r_cauthorJan 26.2008 — Thanks for that, :-)

Ok I reference the file. Fine

I have my selects

[code=html]
<select name="pageid">
<option value="" selected="selected">*Choose a page</option>
<option value="">-------------</option>
<option value="1">Home</option>
<option value="">-------------</option>
<option value="2">About</option>
<option value="3">-> Mission</option>
<option value="">-------------</option>
<option value="4">Services</option>
<option value="5">-> Web design</option>
<option value="6">-> Software</option>
<option value="7">-> Graphic Design</option>
<option value="8">-> Hosting</option>
<option value="9">-> V Sec</option>
<option value="">-------------</option>
<option value="10">Portfolio</option>
<option value="11">-> Web</option>
<option value="12">-> Case Studies</option>
<option value="13">-> Software</option>
<option value="14">-> Database</option>
<option value="15">-> Flash</option>
<option value="16">-> Client List</option>
<option value="">-------------</option>
<option value="17">Enquiries</option>
</select>
[/code]


All of these values are being passed to a pretty important script in all of this for validation.

If i use href for these and the onclick event.... I'm still navigating away from the page.

Here is a screenshot of what im trying to do....

Thanks for your help with this

Screenshot

a.g.r.c
Copy linkTweet thisAlerts:
@scragarJan 26.2008 — default param's order: POST, GET, URL

with reverseparam = false; it's URL, GET, POST

only first element in any order is mandatory.

defaultpage is the default URL to load file from if the URL is not specified.

apendqry is used to turn the query: "cheese" into something like "key=cheese" by setting it to "key="
multiquery = true; will allow more than 1 request at once.
[code=php]var onfailure = true;// if function fails follow links?
var errofunc = false; // if function fails execute a javascript function using this.
var onbusy = false; // if multirquery is false and request in process follow links?
var busyfunc = false; // if multirquery is false and request in process execute function by setting it here.
var defaultReturn = false;// when the function finishes follow the link?
var resultfunc = false;// when function is sucsessfull it runs this function if you set one.[/code]

loadingelement is the ID of an element to fill.

loadingDelay is a number of seconds after the query starts to display loading element. do not set to 0 or more than 3 decimal places.

set elements to use via:
[code=php]lookingfor[lookingfor.length] = "";// name of tag to look for
fillin[fillin.length] = ""; // ID of element to fill.
rptmode[rptmode.length] = 0; // repeat mode, as explain in function.[/code]


anything else you want explaining please say.
Copy linkTweet thisAlerts:
@scragarJan 26.2008 — you can use something like:
[code=html]<select name="pageid" onclick="mkRequest(formget(this),'','PAGE.php");">[/code]
then you can just use PHP to pull the info like it normaly would (values would be in $_POST and have the same name as normaly.

you want to return content like so though:
[code=html]<element_to_search_for>
content of div or whatever that you want to fill etc.
</element_to_search_for>[/code]

you will also want to set the header to use "application/xml"
[code=php]header("Content-type: application/xml");[/code]
Copy linkTweet thisAlerts:
@a_g_r_cauthorJan 26.2008 — Ok i got the first part down.... With including the function.php in the onclick....

The next two parts im very unsettled by.

Where does <element></element>

and header go..... ive used header before for returning an error or success page...

Never like this.... :S
Copy linkTweet thisAlerts:
@scragarJan 26.2008 — headers go before you return content, and your returning an xml page to the ajax function, so you only need to return the opening and closing tags for it to pick up and some content between. once you've made a reference to these elements:
[code=php]lookingfor[lookingfor.length] = "element";// just name of element, no < or > needed.
fillin[fillin.length] = ""; // ID of element to fill.
rptmode[rptmode.length] = 0; // repeat mode, as explain in function.[/code]

in the javascript code(you should be able to spot where(copy and paste that as many times as you want btw, if you want to fill multiple tags) you should be good to go.
Copy linkTweet thisAlerts:
@a_g_r_cauthorJan 26.2008 — Now im totally confused....

Ill try something with the tips you have given, and create a folder structure....

Any change you could look at this when its down.

Cheers
Copy linkTweet thisAlerts:
@scragarJan 26.2008 — you can preview an example of it in action if you like:

[url=http://scragar.mybesthost.com/ajax.html]preview here[/url]

source:

[url=http://scragar.mybesthost.com/source.php?f=ajax.html&format=php]html page[/url]

[url=http://scragar.mybesthost.com/source.php?f=CustomAjax.js&format=php]Ajax function(nothing major was edited.[/url]

[url=http://scragar.mybesthost.com/source.php?f=call_me.php&format=php]PHP page[/url]

in the ajax function I marked all 4 lines that I edited with a comment saying so, which should make them easy to spot with any luck.
Copy linkTweet thisAlerts:
@a_g_r_cauthorJan 26.2008 — Hey dude,

I set this up and as expected its not working.

I kind of understand that you need a container for the returned function.

No idea how to implement this.

http://vmstudios.net/ajax

If you could be so kind...

Thanks

a.g.r.c

P.s just saw your last post - thats exactly what im looking for. Deng your good.
Copy linkTweet thisAlerts:
@a_g_r_cauthorJan 26.2008 — function.php

[code=php]

<?php
$pageid=$_POST['pageid'];

echo $pageid;

?>
[/code]
Copy linkTweet thisAlerts:
@scragarJan 26.2008 — firstly you need to edit your page with the dropdown to have an element to fill(give it an ID).

then you need to edit the custom ajax page like I did, lookingfor is the element it finds, fillin is the ID of the element it fills.

then you need to add apropriate headers around your php content.


The function was designed to give the most functionality possible while still being simple. Guess I overshot simple huh?
Copy linkTweet thisAlerts:
@a_g_r_cauthorJan 26.2008 — Stumbling about pretty bad here...

Any chance you could look at this please?

Download
Copy linkTweet thisAlerts:
@scragarJan 26.2008 — [code=html]<span class="style14">
<select name="pageid" onchange="mkrequest(this.options[this.selectedIndex].value);">
<option value="" selected="selected">*Choose a variable to echo</option>
<option value="">-------------</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>

</select>
</span>

<div id='pageid'></div>[/code]

[code=php]<?php header("Content-type: application/xml");

$pageid=$_POST['key'];
echo "<pageid>$pageid</pageid>";
?>[/code]

and it should work.
Copy linkTweet thisAlerts:
@a_g_r_cauthorJan 26.2008 — Still not working....

Could it be the ajax.js?

Here are the edited regions.

[CODE]
var reverseparam = false;
var defaultpage = "function.php";
var apendqry = "key=";
var multiquery = false;
// do not remove next 3 lines!
var lookingfor = new Array();
var fillin = new Array();
var rptmode = new Array();
// a rptmode of 0 is to ignore all elements in the case of a repeat. DEFAULT
// a rptmode of 1 is to use only the first element.
// a rptmode of -1 is to use only the last element.
// a rptmode of 2 is to compound results in order.
// a rptmode of -2 is to compound results in reverse order.

// standard assignment of wanted variables.
lookingfor[lookingfor.length] = "pageid";
fillin[fillin.length] = "pageid";
rptmode[rptmode.length] = 0;
[/CODE]
Copy linkTweet thisAlerts:
@scragarJan 26.2008 — when I test what message your server sends it's the PHP error:
<br />

<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/alistair/public_html/ajax/function.php:2) in <b>/home/alistair/public_html/ajax/function.php</b> on line <b>2</b><br />[/quote]

would I be correct in guessing that something is sent before you change the headers?

incase your curious, that's the power of the getxml function, all I did was type:

javascript:alert(getxml('function.php'));

into the URL bar and instantly I see what PHP is saying, handy for debugging don't you think? ?
Copy linkTweet thisAlerts:
@a_g_r_cauthorJan 26.2008 — Really i'm not sure... This is all very new to me.

I have read half of a book on PHP and we are only 1 month into classes at college.

The function in ajax.js is wayy over me, i can't even follow the things used in there.

Normally you can follow these things through, looking at this though its like mind freeze body shock.

So the headers have already been sent? Thats the only time they are used is in function.php
Copy linkTweet thisAlerts:
@scragarJan 26.2008 — that's bad wording on PHP's part, what it means is that you have finalised your headers by sending some form of content(space or new line are most common), and that headers can no longer be moddified.

since the error is on line 2 remove line 1 if it's not needed(and "<?php" or "<?" is considered needed).
×

Success!

Help @a_g_r_c spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.5,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...