Jump to content

Archived

This topic is now archived and is closed to further replies.

capnH00K

Change PHP variable with AJAX/Javascript?

Recommended Posts

Howdy folks.

 

I've been curious about this for a few hours now... And i googled a bit, but couldn't find anything about it. So please helo me :-)

 

 

I'm trying to create somekind of online folder. and so far i can add folders to my parent folder (which opens as a dialog based on a variable, which contains the dir parth).. But when I create a new dir, I want to be able to change the Php variable (which tells the browser what folder to deal with).

 

If i can change this variable using AJAX then, I can acess the other folders.

 

 

 

So what i need, is a AJAX/javascript thing, that, when i click a link changes a PHP variable.. 

 

 

 

Here's the part of the code..

 

 


                        $dir = "uploaded/".$id."/music"; //THIS IS THE ONE I NEED TO CHANGE WHEN I CLICK A LINK
                        

 

 

If some of you knows the online dropbox file system, check that out, Im tryying to do something like that...

 

 

Please help me :-)

 

 

 

 

[attachment deleted by admin]

Share this post


Link to post
Share on other sites

Well, the way i have done things similar, is to include the information in my http request srcs prior to my actual ajax request.  then in the php file, retrieve that info from the $_REQUEST var.

Share this post


Link to post
Share on other sites

Okay thanks! But this is the first time I try using AJAX so maybe you can provide me with a bit of code if so i can see what, and how thing's is done  ? ;)  :)

Share this post


Link to post
Share on other sites

Well, mine is going to be a bit different because im using the prototype engine atm to do all my ajax handling.  at least on this site..  but it'll give you at least a basis of how i do mine so you can format yours to work like mine, but using your style..

 

function doUpdate(formID, url, query)
{

var myRand = parseInt(Math.random()*99999999);
var query = query;
var url = url;
var srcs = url+"?pg="+query+"&ints="+myRand;
var pars = Form.serialize(formID);	

$('TransMsgDisplay').innerHTML='<img src="../templates/admin/img/indicator.gif" align="center">';
var myAjax = new Ajax.Request(
srcs,
{
	method: 'post',
	parameters: pars,
	onComplete: processUpdate
});
}



function processUpdate(originalRequest)
{
 if(originalRequest.responseText == 0) {
	document.location.href="index.php";
 } else {
 $('TransMsgDisplay').innerHTML=originalRequest.responseText;
 }
}

 

then in the php file you call with this, you would simply access all of the information via the $_POST[] var.

Share this post


Link to post
Share on other sites

Damn, i don't even know how to set it up lol xD

 

this is def not my element lol :P

Share this post


Link to post
Share on other sites

i'll pick it apart for ya...

 

we create our function in Javascript..  called DoUpdate or whatever we want to name it.

 

We're going to need some parameters though. such as FormID, the url we wish to visit, and optional query (could dispose of the query and just use the url for that too).

 

so now, we want to beat the cache, so we setup the random number...

 

then we setup our request url

 

var srcs = url; or var srcs = url + "?pg=" + query; depending on which method you go.

 

the var pars doesnt really apply to you unless your using the prototype engine. so in this case, pars doesnt matter truely.  but you could do pars = FormID; just to ensure its there ;)

 

the $('transmsgdisplay') is a span i use in my layout to display all my content via ajax (where its possible)...  so since we're starting the query, lets display the 'hold tight, im working' image.

 

now is where the fun stuff comes into play...

 

now my ajax var is Ajax -- as thats what prototype.js has depicted in that.

 

you could set yours up the same way but with setting the send like this:

 

req1.onreadystatechange = processGeneral;
req1.open("POST",url,true);
req1.send(pars);

 

this code above is from an ajax handler function custom to myself outside of ajax..  to where I set req1 = new AjaxHandler();

 

if you use the req1 type ajax sending, the processing function is a little different...

 

function processLogout()
{
if(req.readyState == 4) {
	if(req.status == 200) {
		document.location.href="index.php";
		//alert(req.responseText);
	}
}
							   
}

 

that is the type of handling you want for that.  It can be expanded upon, but it works pretty good.

 

then in your HTML you would call it like so:

 

<input type="submit" name="button" id="button" value="Save" onClick="doUpdate('form1', 'index.php', 'deals&act=edit&sact=save')" class="rbuttons"/>

 

make sense?

Share this post


Link to post
Share on other sites

Thanks for the answer!!

 

But i'm still not really 100%, how do I grap the updated url from the ajax script, inside the html? :b

i'm feeling kind of silly now lol :P

Share this post


Link to post
Share on other sites

This is my HTML code atm... and

 

                                        <tr class="special"> 
                                                 <td width="23px;"><input type="checkbox" name="hello" /></td> 
                                        	<td width=" 23px"><img src='img/files/folder.png' width='23' height='23' ></td> 
                                       		<td class=""><a href="uploaded/44/music/hello">hello</a></td> 
                                                <td class=""></td> 
                                                <td class="">0 MB</td> 
                                        </tr> 

 

When i press the link which has a href to a folder, i want a javascript to take this href (or whatever) and update my $dir variable...

Share this post


Link to post
Share on other sites

<a href="something.html" onClick="doSomething('uploaded/44/music/hello')"/>

 

function AjaxObjectCreateGeneral()
{
var req;  // The variable that makes Ajax possible!

try{
	// Opera 8.0+, Firefox, Safari
	req = new XMLHttpRequest();
} catch (e){
	// Internet Explorer Browsers
	try{
		req = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try{
			req = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e){
			// Something went wrong
			alert("Your browser broke!");
			return false;
		}
	}
}

return req;
}

function doSomething(url) {
req=AjaxObjectCreateGeneral();
if(req) {
	var url = url;
	$('TransMsgDisplay').innerHTML='<img src="../templates/admin/img/indicator.gif" align="center">';

	req.onreadystatechange = processSomething;
	req.open("GET", url, true);
	req.send();
}

}

function processSomething() {
if(req.readyState == 4) {
	if(req.status == 200) {
		// do something
	}
}
}

Share this post


Link to post
Share on other sites

Let me see if i got this right....

 


function AjaxObjectCreateGeneral()
{
var req;  // The variable that makes Ajax possible!

try{
	// Opera 8.0+, Firefox, Safari
	req = new XMLHttpRequest();
} catch (e){
	// Internet Explorer Browsers
	try{
		req = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try{
			req = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e){
			// Something went wrong
			alert("Your browser broke!");
			return false;
		}
	}
}

return req;
}                                    //everything before is really basic, which is jst something that has to be there...     

function doSomething(url) {          //here it will take the url which is in doSomething from HTML which can be changed (this would be the th elink to the folder)...?
req=AjaxObjectCreateGeneral();
if(req) {
	var url = url;      //sets the var URl to the URL?
	$('TransMsgDisplay').innerHTML='<img src="../templates/admin/img/indicator.gif" align="center">';

	req.onreadystatechange = processSomething;
	req.open("GET", url, true);    //
	req.send();
}

}

function processSomething() {
if(req.readyState == 4) {
	if(req.status == 200) {
		// do something  - Here i have to add some code to make it process the changed url back to the page? 
	}
}
}

Share this post


Link to post
Share on other sites

Okay what I have done now is adding what you have written and THANKS FOR THAT!!

 

 

and to debug it, i've added an alert box which shows the dirreent paths to the folers, when i click them, So now i just have to pass the javasccript var url - back into the same php page, so that it kind of updates the folder...  I guess this is where Ajax comes in handy? :P

 

 

 

Share this post


Link to post
Share on other sites

var url = url;      this is where the URL is set...  my function has the ability for dynamic url's by the use of doSomething('url_here');

 

then req.open("GET", url, true);    is what actually runs it through the script...

 

so say you need to run update.php with the url parameter of uploaded/44/music/hello

 

you would do something like:

 

doSomething('update.php?dir=uploaded/44/music/hello');

Share this post


Link to post
Share on other sites

Yea I know that,

 

But lets say the PHP-var $dir = "uploaded/44/hello";

 

Then i want to run the script (which is executed when i press a link) - and after the script, i want the Php-var to be something else so something else is displayed...

 

 

At the moment, I've been able to call an alert box with the text of what the Php-var needs to be... I just need someway to get the java-var url back into the php... and somehow "refresh" (without asctually refreshing) what is displayed...

Share this post


Link to post
Share on other sites

well if you've got the alert box to display, you just either a. create a new function or b. send it through the same function with that new variable set as 'dir' or whatever.. and then program the handling in php. 

 

and then of course you have the $('yourdiv').innerHTML = $req.responseText; and there ya be.

Share this post


Link to post
Share on other sites

Well that's kinda the problem... I'm still realy javascript/ajax noob :P

 

So I don't know how to get java-scripts sent back to the php ... and i don't know how do refresh without actually refreshing... (you know what i mean?)

 

 

$('yourdiv').innerHTML = $req.responseText  - is this how to sent back variables to php ? Can you explain it this line of code a little, if  it's not too much to ask :)

Share this post


Link to post
Share on other sites

$('yourdiv').innerHTML = $req.responseText is how you take your response from PHP and send it to be displayed in the browser replacing whatever is there..

 

show me the code you have right now so i can better help you get it situated to send the information back to php for handling.

Share this post


Link to post
Share on other sites

Php code

                        <?php
                        $num_music=0;
                        $dir = "uploaded/".$id."/music";      //#######THIS IS WHAT NEEDS TO BE CHANGED - SO YOU CAN JUMP BETWEEN DIR'S
                        $files = scandir($dir); 
		?>
		    
                          <table width="100%" class="fcontent">
              		
                         	<tr class="fcontent_header">
                            	<td width=" 23px"></td>
                                <td width=" 23px"></td>
                                <td><strong>Filename:</strong></td>
                                <td><strong>Format:</strong></td>
                                <td><strong>Filesize:</strong></td>
                            </tr>
<?php
                                foreach($files as $ind_file)if($ind_file!="..")  //runs througt the"selected" dir and lists everything in it, as a row in a colum.
                                {
                                    if($ind_file!=".") //makes sure the "." is skipped
                                    {
                                        {
                                        $exploded = explode(".", $ind_file);                     //makes sure the "." isn't posted
                                        $bytes = filesize($dir."/".$ind_file);                       //bytes of file 
                                        $megabytes=round($bytes/1000000, 2);             //convers bytes to megabytes
                                        $link = $dir."/".$ind_file;                                        //Complete link for the file or folder. 
			        $filename = str_replace(" ", "_", $exploded[0]);   //replaces spaces in filename with "_"s
				$filename =str_replace("'","", "$filename");	      //removes " ' "s from the filename		
				$type = $exploded[1];                                          //filetype
				$folder = is_dir($link);		                             // checks weather the link is a folder or a file
                                        ?>
                                        
                                        <tr class="special">
                                            <td width="23px;"><input type="checkbox" name="<?php echo $filename ?>" /></td>
                                        	<td width=" 23px"><?php if($folder=="TRUE"){echo "<img src='img/files/folder.png' width='23' height='23' ";}else{ echo "<img src='img/files/$type.png' width='23' height='23' ";}?></td>
                                       		<td class=""></a><a href="<?php if($folder=='TRUE'){echo '#';}else{echo $link;}?>" <?php if($folder=="TRUE"){echo 'onClick="'; echo "doSomething('"; echo "$link";}?>')"/><?php echo "$filename";?> </td>
                                            <td class=""><?php echo "$type" ?></td>
                                            <td class=""><?php echo "$megabytes MB"; ?></td>
                                        </tr>
                                        <?php 

 

 

Java-script so far... (basicly the code you wrote)

function AjaxObjectCreateGeneral()
{
var req;  // The variable that makes Ajax possible!

try{
	// Opera 8.0+, Firefox, Safari
	req = new XMLHttpRequest();
} catch (e){
	// Internet Explorer Browsers
	try{
		req = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try{
			req = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e){
			// Something went wrong
			alert("Your browser broke!");
			return false;
		}
	}
}

return req;
}

function doSomething(url) {
req=AjaxObjectCreateGeneral();
if(req) {
	var url = url;
	alert(url);  alert box.. 
	$('TransMsgDisplay').innerHTML='<img src="../templates/admin/img/indicator.gif" align="center">';

	req.onreadystatechange = processSomething;
	req.open("GET", url, true);
	req.send();
}

}

function processSomething() {
if(req.readyState == 4) {
	if(req.status == 200) {

		//do something

	}
}
}

 

 

 

Does this help you :)?

 

I'm sorry if it's a little messy :P

Share this post


Link to post
Share on other sites

function AjaxObjectCreateGeneral(){	
var req;  // The variable that makes Ajax possible!		
try{		
// Opera 8.0+, Firefox, Safari		
req = new XMLHttpRequest();	} catch (e){		
// Internet Explorer Browsers		
try{			
req = new ActiveXObject("Msxml2.XMLHTTP");		
} catch (e) {			
try{				
req = new ActiveXObject("Microsoft.XMLHTTP");			
} catch (e){				
// Something went wrong				
alert("Your browser broke!");				
return false;			
}		
}	
}	
return req;
}

function changeNav(url, pars) {
req=AjaxObjectCreateGeneral();	
if(req) {
   $url = url + '?id='+pars;
req.onreadystatechange = processNav;		
req.open("GET", url, true);		
req.send();
}
}

function processNav() {
// everything from here is brought back from echo in php
$('mydiv').innerHTML = req.responseText;
}

 

that would be your javascript..  then you make your php file, create a single string of data, and  you echo that out...

 

and you change $id to $_REQUEST['id'];

 

and you add onclick="changeNav('myphpfile', <?php echo $theid; ?>)" to whatever you're wanting to select or whatever...

 

remember to change $theid to wherever your id number is coming from  and mydiv can be an actual div, or a span, or anything really as long as it has id="mydiv" attached to it.

Share this post


Link to post
Share on other sites

oh forgot something....  return false; is a necessity these days.. as ie8 for some reason doesnt register the onclick command, and will take you to the href after all it said and done which we dont want...  so your onclick would look more like this:

 

onClick="changeNav('myphpfile', <?php echo $theid; ?>) return false;"

Share this post


Link to post
Share on other sites

sure..  im keeping record of this thread so i'll see it.

Share this post


Link to post
Share on other sites

What do i need the $theid (pars) for?

 

All i need to do is actually to change a php variable from the click of a link...?

Share this post


Link to post
Share on other sites

i imagine the parsid would be: $id from: $dir = "uploaded/".$id."/music"

Share this post


Link to post
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.