Search code examples
javascriptphparraysform-post

php or javascript Grab next array on button


Pulling simplexml and parsing them into php variables. I have a form with arrays in them. I want a button outside the form that will "essentially" go to the same form but with the next array number. IE:

<? 
   if( $xml = simplexml_load_file('my.xml') ) {
       foreach( $xml as $SAVED_EXPORT) {
           $mfg = $SAVED_EXPORT->productmanufacturer;
        }
   }
?>

<form id="myform" method="post" action="coderdb.php">
  <input type="text" value="<? echo $mfg[0] ?>" name="MFG" />
  <input type="submit" />
</form>

I'd like to have a button that says NEXT that when clicked it will pull up the next array ie. $mfg[1]. I believe the page would have to be reloaded which is fine. I read somewhere I may have to use $key but have never used and I am not exactly sure its what I need here.


Solution

  • You need some javascript use JQuery.

    <script type="text/javascript">
        $(function(){
            var array = [];
    <? 
        if( $xml = simplexml_load_file('my.xml') ) {
            $i=0;
            foreach( $xml as $SAVED_EXPORT) {
                $mfg = $SAVED_EXPORT->productmanufacturer;
            }
        }
        foreach($mgf as $key=$value) {
            // if $key in not numeric then add iterator for this foreach   
            echo "array[$key]=$value";
        }
    ?>
            iterator = 0;
            $('#nextExport').click(function(){
                var theInput = $('#setExport');
                // theInput.attr('val',array[iterator]);      
                theInput.val(array[iterator]);
                if(iterator==array.length) { 
                      iterator = -1;
                }
                iterator++; 
            });
        });
    </script>
    
    <form id="myform" method="post" action="coderdb.php">
         <input type="text" id="setExport" value="<? echo $mfg[0] ?> name="MFG" />
         <input type="button" id="nextExport" value="Next Export" />
         <input type="submit" />
    </form>
    

    I hope this helps. if something goes wrong check the syntax , logic is right.