3

I am using this question, jQuery Ajax POST example with PHP, to understand how to work with data inside a form before it is submitted.

I have an application without GUI, I build a database and a webapp around it. This application uses fopen() to open xml files. I am using the $GET method to get the xml file with its path from a column on the database.

<?php
$sql = pg_query($conn, "select link, identification from tbl_xml where date='$today';"));
?>
<form id="xmlform" name="xmlform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="GET">
<?php
while ($row = pg_fetch_row($sql)) {
echo "<button type='submit' name='xml' value='$row[0]' class='btn-as-link'>$row[1]</button>"
}
?>
</form>

We are in the index.php.

[...]
ELSE IF( isset($_GET['xml'] )){
    include_once("showXml.php");
    }
[...]

showXml.php:

$url = filter_var($_GET['xml'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
[...]
// $url contains a really long path and the file. Each folder of the path creates exception on how to open the xml file, but in the end i simply open like this:
    // Opening the file
    $myfile = fopen("$xml", "r");
    $xml =  fread($myfile,filesize("$xml"));
    $dom = new DOMDocument;
    $dom->preserveWhiteSpace = TRUE;

    // IF the file has XML format we will arrange it, if not we will print it raw
    IF ( $dom->loadXML($xml) ) {
      $dom->formatOutput = TRUE;
      $xml_out = $dom->saveXML();
      echo "<pre><code class='language-markup'>";
      echo htmlspecialchars($xml_out);
      echo "</code></pre>";
    } ELSE {
      $xml = str_replace('\'','\''.PHP_EOL,$xml);
      echo "<pre><code class='language-markup'>";
      echo htmlspecialchars($xml);
      echo "</code></pre>";
    }

    fclose($myfile);

I wanted to use the $GET method because the webapp have a clock, every X minutes the page refreshes. If I would have used a $POST, I would have seen that window telling me to "resend the data". I don't want that.

The problem I face, is that the path is well visible in the URL, and because the webapp will receive an update soon where it will also open XML file presents in other servers, I am looking for a way to maintain the echo "<button type='submit' name='xml' value='$row[0]' class='btn-as-link'>$row[1]</button>" but converting the form from using $GET method, to a jquery/ajax or any other way to give to showXml.php its xml_file_path.

I added the code from the other question, and I can read the "Hooray, it worked!" on the console. My variable $xml is inside form.php.

form.php

if (isset($_POST['xml']){
    $xml = isset($_POST['xml']) ? $_POST['xml'] : null;
}

From here, it is not clear to me how to trigger the:

ELSE IF( isset($_GET['xml'] )){
    include_once("showXml.php");
    }

of the index.php, to open the variable $xml not from the $GET method rather from $POST used inside form.php

aPugLife
  • 989
  • 2
  • 14
  • 25
  • I'm not sure how you can not have a gui but have a button? – Professor Abronsius Dec 21 '17 at 13:31
  • It is a java application running on Ubuntu server. The application itself have no GUI. It creates folder based on who sent me a file. I build a database and way too many bash script to register inside the database all the file sent and received. the webapp shows me these files – aPugLife Dec 21 '17 at 13:33
  • Possible duplicate of [PHP - include a php file and also send query parameters](https://stackoverflow.com/questions/1232097/php-include-a-php-file-and-also-send-query-parameters) – Serge K. Dec 21 '17 at 13:35
  • @SergeK., well, not really. I use include because this is how I programmed the website long time ago. Now that I have to open xml file outside the same server, I can still use include and $GET, but can you imagine this URL: `index.php?xml=100.100.100.99:5050/rootfolder/basefolder/anotherfolder/evenonemore/dateoftoday/xmlfile.xml` I'm sure there is a proper way for this, I just don't know ): – aPugLife Dec 21 '17 at 13:38
  • `$.get('100.100.100.99:5050/rootfolder/basefolder/anot‌​herfolder/evenonemor‌​e/dateoftoday/xmlfil‌​e.xml', ...` ? – Serge K. Dec 21 '17 at 13:41
  • Ok this is interesting! May I ask you to "convert" my code above with your example, please? I don't want to bother with this, thing is I am not sure how to proceed. I must trigger `showXml.php`, this is the core for opening the file. The variable $xml can be given in any way, preferably not through the url as I did – aPugLife Dec 21 '17 at 13:48

2 Answers2

1

I'm not 100% convinced I have grasped the problem but if you were wanting to use ajax to send the request ( using GET ) perhaps the following might offer some guidance.

Rather than using a submit button a standard button works fine when using ajax - the details of the xml file are held within the buttons data-value attribute and sent as part of the ajax url.

Use the callback function to process the response however you need - this simply pops up an alert with the response data.

<?php
    $sql = pg_query( $conn, "select `link`, `identification` from `tbl_xml` where `date`='$today';"));
    $bttns = array();
    while( $row = pg_fetch_row( $sql ) )$bttns[]="<input type='button' data-value='{$row[0]}' value='{$row[1]}' />";



    echo "<!-- render basic form with all buttons -->
        <form name='xmlform'>
        " . implode( PHP_EOL, $bttns ) . "
        </form>";
?>




<script>
    var url='showxml.php';
    var evtcallback=function(xml){
        alert(xml)
    };

    function ajax( url, callback, payload ){
        var xhr=new XMLHttpRequest();
            xhr.onreadystatechange=function(){
                if( this.status==200 && this.readyState==4 )callback.call( this, this.response );
            };
            xhr.open('GET', url + '?xml='+payload, true );
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            xhr.send(null);
    }

    var col=Array.prototype.slice.call( document.forms.xmlform.querySelectorAll('input[type="button"]') );
        col.forEach(function( bttn ){
            bttn.addEventListener('click', function(event){
                ajax.call( url, evtcallback, this.dataset.value );
            }.bind( bttn ),false );
        });
</script>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • Thank you! I'm impressed. not sure I am able to understand every piece of the code used. I will try and see. Let me upvote this first because I really appreciated your answer! – aPugLife Dec 21 '17 at 14:49
  • `Uncaught TypeError: Cannot read property 'querySelectorAll' of undefined at index.php?`... I can not use `$bttns = array();` nor can I use `. implode( PHP_EOL, $bttns ) .`. Don't know if the problem is here, if so, Can I ask you if you could modify the code to match mine? I know mine is bad, sorry for that :D but there is more on that `while()` than what I showed in the example. – aPugLife Dec 21 '17 at 15:01
  • there was a mistake - it should have been `document.forms.xmlform` ~ hopefully that should clear up that error message. Why can you not use `$bttns=array();` etc? – Professor Abronsius Dec 21 '17 at 15:09
  • Because to build the table I use 4 different SQLs. 1 is the first, the one I posted, which doesn't only get 'link' but also 6 others columns, and some of these columns are processed with other SQLs to nest another table inside each of the `` of the main table. The java application Send and Receives file, for each file there is 1 or more reply. the SQLs work together to dynamically build the table. It's a really bad environment but the best I could do. I fixed with `document.forms.xmlform` but still same error :/ – aPugLife Dec 21 '17 at 15:27
  • The main table (this) have thousands of records (I use the pagination for showing them), `"filename; date; link; sender; receiver; status"` - and for each row a nested table which contains the value of `$SQL3`: `"name; status, link; identification"`. I use the `xmlform` for both opening the link in the maintable and for opening the link in the nested table. One is the file sent, the other the received. It is really long, I would love to explain how I did it, because I am not a webdeveloper (I used to be) but just can't. I converted easily what you wrote to match my code, but error still there – aPugLife Dec 21 '17 at 15:40
  • It's very hard to fully understand how this is all supposed to work without seeing the whole picture ( as it were ) – Professor Abronsius Dec 21 '17 at 16:14
  • It is not different than what I posted, really. I use very basic PHP programming. It is just longer and with more columns. The concept is the same: the main table have a nested table for each row of it. The main row (parentrow) have a button that points to a xml file (my example), the parentrow have a childrow with another button that points to another xml file. If I'm able to use jquery and send the variable not to the GET but to a "hidden" one, I'm done. I was trying with $SESSION, no luck yet – aPugLife Dec 22 '17 at 10:12
  • Ok well, today with a fresh mind I understood why the `Uncaught TypeError: Cannot read property 'querySelectorAll'`. Of course It can not read something if it does not exists yet. `$(document).ready(function(){ [here your code] });` Much better! - New Issue: I was using ` – aPugLife Dec 22 '17 at 10:31
  • It is `setRequestHeader`. The new error is: `GET http://192.168.5.10/function%20(xml)%7B%20%20%20%20%20%20%20%20alert(xml)%20%20%20%20%7D?xml=undefined 404 (Not Found)` – aPugLife Dec 22 '17 at 10:40
  • oops, my bad - there was a couple of mistakes in that line - it should be, as it now is, `setRequestHeader` not `sendRequesHeader` which was blatantly wrong. sorry about that – Professor Abronsius Dec 22 '17 at 10:44
  • No problem (: it is already so kind that you spent time to provide me the code! I added a `console.log(this.dataset.value);` just after: `bttn.addEventListener('click', function(event){`. Now, at the click of my button, I can see that the console prints the path of the file. It is working! ..I just don't know how to send this to showXml.php. [EDIT] without throwing the error wrote before. showXml.php works when index.php include() it, because before the path was in the $GET method – aPugLife Dec 22 '17 at 10:48
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161802/discussion-between-ramraider-and-nihvel). – Professor Abronsius Dec 22 '17 at 10:49
0

Not the best way, but it is working.

I converted the form to $_POST. Assigned the value of $_POST['xml'] to $_SESSION['xml'] and using this to open the file. Emptying the $_SESSION['xml'] after the file was opened. URL is clean.

aPugLife
  • 989
  • 2
  • 14
  • 25