-2

This is my code (im using codeigniter as my framework and this is the view). This code should write the div named contain's content to the file called newfile.php after the submit button is clicked. But I need to click the button 2 times before it writes the data into the newfile.php. Help please. I don't know what's wrong with my code.

      <!DOCTYPE html>

         <html lang="en">
           <head>
             <meta charset="utf-8">
             <title>Online Lodging Locator</title>
          </head>

        <script>

             function test(){

           var x = document.getElementById('contain').innerHTML;

            alert(document.my_form.my_var.value=x);

        <?php
          $content = $_POST["my_var"];
          $myfile = fopen("newfile.php", "w") or die("Unable to open file!");

          fwrite($myfile, $content);

          fclose($myfile);
           ?> 

           }
            </script>   

         <body>

           <form name="my_form" method="post">
            <input type="hidden" name="my_var">
            <div id="contain">

            <h1>Online Lodging Locator</h1>


            <table cellspacing="0" cellpadding="1" border="1">
         <tr>
            <td>COL 1 - ROW 1222<br />COLSPAN 3</td>
            <td>COL 2 - ROW 1</td>
            <td>COL 3 - ROW 1</td>
         </tr>
         <tr>
          <td rowspan="2">COL 2 - ROW 2 - COLSPAN 2<br /></td>
          <td>COL 3 - ROW 2</td>
         </tr>
         <tr>
          <td>COL 3 - ROW 3</td>
         </tr>

         </table>

          </div>
         <button type="submit" class="btn btn-default" name="SEARCH" id="SEARCH" onclick="test()">WRITE</button>
           </form>

         </body>
         </html>
  • 2
    You know the PHP runs first no matter what right? Are you also aware the first time it runs that my_var contains absolutely nothing? What you need is an ajax call that you feed the data into and and that writes data to the new file. – Royalty Jan 09 '15 at 23:22
  • Try putting $(document).ready(function(){***your js***} at the biginnign of your js – rhill45 Jan 09 '15 at 23:26
  • @Rhillz there is no jQuery being used. That would cause errors to be thrown for both scope issues and the fact that `$` is undefined – charlietfl Jan 09 '15 at 23:29
  • @Royalty I didn't know that. How do I use ajax to feed the data to write it in the new file? – Justin Francis Toral Jan 09 '15 at 23:32
  • $Rhillz I tried putting $(document).ready(function(){my js} but it doesn't work anymore even after 2 clicks. – Justin Francis Toral Jan 09 '15 at 23:33
  • Justin, there are many ways to do an AJAX request. Most people use libraries like jQuery to do them because it makes the whole process simpler. But first steps would be move the php you have now on that page to a new file and set up the form action to post to that new php file You could probably do this without ajax using php, you would have to store html in a variable and write that variable in the input value then post it. – Royalty Jan 09 '15 at 23:45

3 Answers3

1

An explanation to why you need to click the button twice:

@Royalty is correct. The php runs first. The php is in your script block. It returns an error since $_POST['my_var'] is undefined. This is echoed inside the script block causing your page halt scripting because of an error. When you click submit. The form is submitted (actually the page is reloaded) and the post var gets filled this time. So no error in PHP means nothing gets echoed into the script block meaning no error is raised by the browser. Now clicking upon submit executes the function test.

But to follow up on the comments. Your script actually works by incident. If you want to write to a file use the action attribute on the form or perform an ajax call.

Form action

<form name="my_form" action="file.php" method="post">
   <input type="hidden" name="my_var">
   <button type="submit" class="btn btn-default" name="SEARCH" id="SEARCH" onclick="test()">WRITE</button>
</form>

<script>
   function test(e)
   {
       e.preventDefault();
       document.my_form.my_var.value = document.getElementById('contain').innerHTML;
       document.getElementsByName("my_form")[0].submit(); //submit the form.
   }

</script>

AJAX

function sendAjax(e) {
    e.preventDefault(); //prevent the default action of the form.
    var xmlhttp;
    xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {
           if(xmlhttp.status == 200){
               //request is complete and loaded
               //do something with the response.
           }
           else if(xmlhttp.status == 400) {
              alert('There was an error 400')
           }
           else {
               alert('something else other than 200 was returned')
           }
        }
    }

    xmlhttp.open("POST", "file.php", true); //true means asynchronously.
    xmlhttp.send("content="+document.getElementById('contain').innerHTML);
}

HTML

    <button type="submit" class="btn btn-default" name="SEARCH" id="SEARCH" onclick="sendAjax()">WRITE</button>

file.php should be replaced with a php file on your server that runs:

 <?php
      $content = $_POST["my_var"];
      $myfile = fopen("newfile.php", "w") or die("Unable to open file!");

      fwrite($myfile, $content);

      fclose($myfile);
 ?> 
Community
  • 1
  • 1
Mouser
  • 13,132
  • 3
  • 28
  • 54
  • do I need to include this code if i'm not going to use the AJAX method? or this code is only for the AJAX method? – Justin Francis Toral Jan 11 '15 at 12:40
  • @JustinFrancisToral In either cases you need to move that php to a separate file. Then call that file either from post action or ajax. – Mouser Jan 11 '15 at 12:51
0

You need to send your data to controller. You could also send to any php file, but you already have CodeIgniter.

JS

var base_url = '<?=base_url()?>';
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function()  {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)  {
        document.getElementById('contain').innerHTML=xmlhttp.responseText;
      }
    }
    xmlhttp.open("POST", base_url+"path/to/controller",true);
    xmlhttp.send();

With jQuery you have easier control of data type:

var content = $('#contain').html();
var base_url = '<?=base_url()?>';
$.ajax({
  type: "POST",
  contentType: 'html',
  url: base_url+"path/to/controller", //"path/to/file.php"
  data: content
});

PHP

$myfile = fopen("newfile.php", "w") or die("Unable to open file!");

if(isset($_POST['data'] {
    $content = $_POST['data'];
} else {
    $content = 'No data';
}
echo $content;
fwrite($myfile, $content);
fclose($myfile);
lima_fil
  • 1,744
  • 27
  • 34
  • The first Ajax (vanilla) example will not work the way the OP intended. The OP wants to send the table inside the form to the server and store it in a php file. The html gets stored into the hidden input and posted to the server. You need to add this as a variable to the send function. – Mouser Jan 10 '15 at 11:04
  • I'm lost. is all the code above inside the tag and do I need to change my html code? – Justin Francis Toral Jan 11 '15 at 12:48
0

I solved it. I just need to add if(isset($_POST['my_var'] {)){} to my php code. I don't need to click the submit button twice.

  • Yes that is the simplest solution the problem. However I advise to read the other answers and the comments again. They give solid advice in how to implement the functionality you want robustly. – Mouser Jan 11 '15 at 13:25
  • I got a new problem. how do I access the controller function in javascript? – Justin Francis Toral Jan 11 '15 at 13:34