Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11
  1. #1
    New Coder
    Join Date
    Feb 2013
    Posts
    47
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Passing javascript function variable to PHP

    Hello all,

    I am quite new to Javascript and AJAX. My function is intended to capture an input value (variable name: $value) from a clicked form button and pass it back to the calling PHP program.

    All is working except for returning the value. Part of the logic I am struggling with is that the "prevNext" function is called from the on-click form input. When the value is returned, it would be directed back to the input form (bolded below) from where it was called??? I'll bet my implementation for passing the value is wrong and there is a much better strategy to be employed...

    I realize POST & GET is an option, but I prefer to work with the value passed back from the function to the PHP code.

    Code:
    <?php
    
    class pagination 
    {
    	function page($lastRec,$width,$curRec,$begSet)
    	{
    
    	$limit = 30;
    	$start = 0;
    	$eu = 0;
    	$p_f=0;
    	$eu=$begSet;
    	$this1 = $eu - $limit;
    	$back = $eu - $limit;
    	$next = $eu + $limit;
    	$endSet = $begSet + $limit;
    	$space = " - ";
    	$humanNum = 0;
    	$value="";
    
    	echo "<table align = 'center' " . $width . "><tr><td align='left' width='20%'>";
    	echo "</td><td  align='left' width='20%'>";
    		if($endSet > $limit) 
    		{ 
    		print "<tr><td><font face='Verdana' size='2'><input type = 'submit' value ='PREV'></font></td></tr>";
    		} 
    		echo "</td><td align=center width='20%'>";
    		$humanNum = $begSet +1;echo "<font face='Verdana' size='2'><b> Records $humanNum - $endSet</b></font>";        
    				
    		echo "</td><td  align='right' width='40%'>";
    		if($curRec < $lastRec and $curRec = $endSet) 
    		{ 
    		echo "<input type='button' id='button1' name='Release' onclick='prevNext($value)' value='NEXT $limit'>";
    		}
    
    
    
    		echo "</td></tr>";
    		echo "</table>";
    	}		//end of function page
    
    }			//end of class pagination
    
    ?>
    
    <script type="application/javascript">
    	function prevNext(clicked)
    	{
    	var $value=document.getElementById('button1').value;
    //	document.write($value);
    	return $value;
    	 }
    </script>
    	<p>The value is: $value</p>

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    Quote Originally Posted by geno11x11 View Post
    I realize POST & GET is an option, but I prefer to work with the value passed back from the function to the PHP code.
    It's not an option, it's mandatory for your task. You cannot just "return" a value from Javascript to the calling PHP, because PHP has finished executing at the time Javascript is running.

    So you'll have to request the PHP page again with GET or POST parameters. You can do that by either refreshing the whole page or by starting an AJAX request.

  • #3
    New Coder
    Join Date
    Feb 2013
    Posts
    47
    Thanks
    3
    Thanked 0 Times in 0 Posts
    I see your point - if PHP is finished by the time the button is clicked, it makes sense that a new PHP operation has to be commenced. Thanks for the pointer - I've found an excellent online AJAX tutorial that should help finish this project.
    Last edited by geno11x11; 02-19-2013 at 08:02 PM.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Quote Originally Posted by geno11x11 View Post
    if PHP is finished by the time the button is clicked ...
    PHP is finished before the page even *APPEARS* in the browser.

    Many eons (in computer time) before the user even has a chance to read the page, much less push a button.

    [There are exceptions: If you have a really large page, and if you use buffering with periodic flushes of the buffer, then part of the page *might* appear before PHP is finished, but you should consider that the rare exception. And in any case, JS has no way to influence what PHP is dumping into the rest of the page.]
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    New Coder
    Join Date
    Feb 2013
    Posts
    47
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Thanks for all the helpful comments. I dove into the $_POST function and now have a working program, but I have been unsuccessful at returning variable values back to the calling php program. I normally do this through functions, but I don't know how to structure that in conjunction with the AJAX code. I tried using SESSION variables, but even that fails to return the variable values. I've been working on this so intently I'm probably missing something very basic.

    I have used a separate file, prevNext.php, because that is the only way I have found to accomplish the task. If the AJAX $_POST can be handled in the same file utilizing a function without a great deal of complexity, I would be most interested in that solution.

    Summary: I am unable to return the value $prevNext to the calling program, class.tablePagination.php. Look at the 2nd program, prevNext.php, for the parsed variables. I have posted only the relevant code for brevity, and have bolded a few important lines.

    The calling include program:

    Code:
    <!--   filename: class.table.Pagination.php -->
    <script language="JavaScript" type="text/javascript">
    function ajax_post(){
        var hr = new XMLHttpRequest();
        var url = "prevNext.php";
        var fn = document.getElementById('button1').value;
        var vars = "buttonVal="+fn;
        hr.open("POST", url, true);
        // Set content type header information for sending url encoded variables in the request
        hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        hr.onreadystatechange = function() {
       if(hr.readyState == 4 && hr.status == 200) {
       var return_data = hr.responseText;
    document.getElementById("status").innerHTML = return_data;
       }
        }
        hr.send(vars); // Actually execute the request
        document.getElementById("status").innerHTML = "processing...";
    }
    </script>
    <?php
    
    class pagination 
    {
    	function page($lastRec,$width,$curRec,$begSet,$limit)
    	{
    	$endSet = $begSet + $limit;
    	$space = " - ";
    	$humanNum = $begSet +1;
    			echo "<table align = 'center' " . $width . "><tr><td align='left' width='20%'>";
    			echo "</td><td  align='left' width='20%'>";
    			if($endSet > $limit) 
    			{ 
    			print "<tr><td><font face='Verdana' size='2'><input type = 'submit' value ='PREV'></font></td></tr>";
    			} 
    			echo "</td><td align=center width='20%'>";
    				echo "<font face='Verdana' size='2'><b> Records $humanNum - $endSet</b></font>";        // Show record set displayed
    			echo "</td><td  align='right' width='40%'>";
    onclick='javascript:ajax_post();' value='NEXT $limit'>";
    				echo"<div id='status'></div>";
    			}
    			echo "</td></tr>";
    			echo "</table>";
    echo "Session Variable2= ". $_SESSION['$prevNext'];
    	}		//end of function page
    
    }			//end of class pagination
    ?>
    The $_POST URL PHP file:

    Code:
    <!--    filename - prevNext.php     --!>
    <?php 
    session_start();
    if ($_POST['buttonVal'] == 'NEXT 30')
    	{
    	echo "<button type='button'>It worked</button>";
    	}
    	else
    	{
    	echo 'Oops - Something went wrong<br />';
    	}
    //unset($_POST); 
    $_SESSION['$prevNext']=$_POST['buttonVal'];
    echo "Session Variable1= ". $_SESSION['$prevNext'];
    ?>
    Last edited by geno11x11; 02-24-2013 at 04:17 AM.

  • #6
    Regular Coder
    Join Date
    May 2002
    Location
    Virginia, USA
    Posts
    620
    Thanks
    0
    Thanked 6 Times in 6 Posts
    Rather than using $_SESSION, you could just adjust
    Code:
    var url = "prevNext.php";
    to be something like
    [code]
    var url= "prevNext.php?c=" + <?=$begSet?> + ";"
    [code]

    and then just use
    Code:
    <?php
    ...
    $newStart = $_GET["c"] + $num_items;
    ...
    ?>
    or something similar. Essentially, you change your AJAX query to pass in a URL parameter, and then your php consumes it and returns new data. I admit, however, that in looking at your code, it seems like you may be trying to do more than you should within a single file.

    NetTuts has a good php pagination example here: http://net.tutsplus.com/tutorials/ph...data-with-php/ that is pretty complete.

    HTH,
    -Celt

  • #7
    New Coder
    Join Date
    Feb 2013
    Posts
    47
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Many thanks for the comments and the pagination link... After many hours of unsuccessful work, I discovered that holding a variable value ($_POST) over multiple stateless operations is not possible, not necessary, and is bad coding. I was utilizing a technique I had used in stateful programming to re-use code by changing the variable contents so the statements could be re-used for a variety of purposes - it made for much shorter coding but is not usable for stateless client-server applications -- it is also makes the logic very hard to follow.

    Following the logic of the linked pagination example, I re-coded my project with dedicated variables and all is working perfectly - and I believe it is the best/only way to approach a stateless project.

  • #8
    New Coder
    Join Date
    Feb 2013
    Posts
    47
    Thanks
    3
    Thanked 0 Times in 0 Posts
    I celebrated my success a bit early. Although I have made great progress on this project, the original problem has come full circle and is still rearing it's ugly head...

    In a nutshell, I am still not able to pass a variable to the main php program; it appears that AJAX scripts and the connected php file are totally isolated from the active variables in the main PHP program. AJAX and php do a terrific job of returning HTML within the connected files, manipulate text, do comparisons and the like, but it is all isolated from the main PHP program. I have tried many approaches to pass a value: Passing values through functions, doing comparisons using the output of AJAX, and even just passing a boolean value to give the main PHP program an indicator of the result of a click; but in every case it has failed.

    The pagination programs I have studied all use the GET method which, in all cases, requires a reload of the page. I am stubbornly trying to avoid that.

    What have I missed? There must be a way.......

  • #9
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    Did you read and understand my very first response?

    I reckon that your "main" PHP file is the one that you used to create the "original state" of your page. You have to understand that this PHP file runs once (at the very start), creates some output containing HTML, Javascript etc., and then finishes! Only after your main PHP finished, the HTML will be shown and the Javascript (including Ajax) will be executed. So there is REALLY no way to return some Javascript values to the original "main" PHP.

    The only thing you can do from Javascript (e.g. using Ajax) is to execute this PHP again(!) and transfer some Javascript values in this request. You can then assemble the altered output of this script into your current page.

  • #10
    New Coder
    Join Date
    Feb 2013
    Posts
    47
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Devnull69, I recall your comments. I have noted that other PHP programs call themselves to pass values - I don't think I have a clear understanding of the process. Following tutorials, I have been using a separate php program rather than reloading the original - thus the brick wall passing variables. I suppose it will be necessary to re-initialize all variables, repaint the html page, re-access the database for the needed last record number, etc. which is where my hangup lies. In stateful programming, I have always strived to avoid any unnecessary repetition to be as efficient as possible. I need to adjust my thinking on the stateless process and probably abandon my notions of efficient programming. I will experiment with calling the main php program -- I'll bet that will be the answer.

  • #11
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,462
    Thanks
    0
    Thanked 633 Times in 623 Posts
    PHP pages containing forms call themselves so that they can reload the entire page with the form to display any error messages detected by the server side validation after the form is submitted to the server. If the data passes validation the page generally redirects to another page that handles the situation where the form was filled out successfully.

    JavaScript adds a totally separate layer in that it does not need to reload the entire page in order to interact with the person filling out the form. JavaScript can update the existing page directly using either innerHTML (to make minor changes) or the proper DOM commands (which allow JavaScript to completely rearrange the page in whatever way you like).

    Ajax calls add yet another layer on top of that where the JavaScript can call separate PHP scripts on the server passing it values via GET or POST and receiving back whatever the PHP script echos. Usually you'd have the PHP echo data in either XML or JSON format as those are the two formats that JavaScript can most easily load into variables for further processing.

    Attempting to use the PHP from the first of these layers to process the third of these layers is making things overly complicated. If you do want to do that then make the code from the third layer PHP an include call in the first layer main PHP and have the data echoed if the PHP is called directly and loaded into a variable for subsequent processing if it is included.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •