XMLHttpRequest.Open not working

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dragon52
    New Member
    • Jun 2009
    • 72

    XMLHttpRequest.Open not working

    Hi, I need help to understand how to send data from javascript client to php server.

    I want to save some data (a large table) from a web page to a mysql database. I thought the following js and php codes will do that. But it doesn't work so may be I don't understand the concept at all.

    The way I understand it is the javascript sends the string "555" to the file 'test.txt' on the server, and the php reads the string from the same file where I can do something with it, eg save to database.

    I know the php part works because if I manually create the file test.txt then its content is displayed on the web page. But the javascript code is not updating the file test.txt

    javascript
    Code:
    request = new XMLHttpRequest();
    request.open("POST", "./test.txt", true);
    request.setRequestHeader("Content-type", "application/json");
    request.send("555");
    php
    Code:
    $arr = file_get_contents("./test.txt");
    var_dump($arr);
    I am new to the interaction between javascript and php, so any help would be greatly appreciated.

    I am using localhost to test this code
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    The way I understand it is the javascript sends the string "555" to the file 'test.txt' on the server, and the php reads the string from the same file where I can do something with it
    the only correct part here is that JavaScript sends something to the destination file. every other assumption is plain wrong.

    - files are read-only over HTTP
    - PHP doesn’t automatically know if some file has changed
    - you declare your sent data to be JSON, but it’s plain text (a number)

    if you want to send data to PHP, then you have to send the data to a PHP script file.

    Comment

    • dragon52
      New Member
      • Jun 2009
      • 72

      #3
      Hi Dormilich,

      Thanks for your reply.

      I am not sure what you are telling me. What do you mean php script? The 'file_get_conte nts' bit is in php code. See below.

      From my debugging, the php can read the content of the file 'test.txt' but the javascript is not updating it. I thought that is where the problem is. The file is actually on my pc because I am using the localhost server.

      May be I need to give you more of my code. The data I need to save to the database is a table of checkboxes. That is why I use js to gather the data into a json object. But it is the mechanism of sending data (any data) from js to php that I need to sort out.

      Basically when the button btnSave is clicked the js function xx() is executed sending data off and the php function temp() (part of Attendance class) is also executed getting the data and save it to the db. That is what I am trying to achieve.

      html markup
      Code:
      <form id="attend" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
      <?php
          if (isset($_POST["btnSave"])) {
              $attend = new AttendanceClass();
              [B]$attend->temp()[/B];
          }
      ?>
          <input type="submit" name="btnSave" value="Save" [B]onclick="xx()"[/B]/>
      </form>
      
      <script src="script.js"></script>

      php code
      Code:
      class AttendanceClass
      {
          public function temp()
          {
              $arr = file_get_contents("./test.txt");
              var_dump($arr);
          }
      }

      javascript
      Code:
      function xx() {
          var car = { type: "Fiat", model: 500 };
          var str_json = JSON.stringify(car);
      
          request = new XMLHttpRequest();
          request.open("POST", "./test.txt", true);
          request.setRequestHeader("Content-type", "application/json");
          request.send("555");
      }
      in the request.send() function I can use the json object str_json instead of "555" but I am trying to make things easier to follow.

      Hope I have made myself clearer.

      Thank you so much for you time!!
      Last edited by dragon52; Jun 19 '15, 03:34 PM. Reason: err

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        What do you mean php script?
        a file that is run through PHP. test.txt is a simple text file, which 1) does not get written (forbidden by webserver) and 2) it does not trigger a PHP script that could process the text file’s content.

        the least you should change is
        Code:
        request.open("POST", "./test.php", true);
        additionally, for your case JSON is not suitable because you would have to read it off the input stream, instead of the usual $_POST variable.

        so the least working code should look like
        Code:
        var request = new XMLHttpRequest();
        request.open("POST", "./test.php", true);
        request.send('type=FIAT&model=500');
        and test.php
        Code:
        <?php
        if (!isset($_POST['type'], $_POST['model'])) {
            header('HTTP/1.0 400 Bad Request');
            echo 'Missing "type" and/or "model".';
            exit(0);
        }
        // do something with the passed data
        Last edited by Dormilich; Jun 19 '15, 04:00 PM.

        Comment

        • dragon52
          New Member
          • Jun 2009
          • 72

          #5
          Hi Dormilich,

          Can you help me further? I can't get it to work.

          I have made changes as you have suggested. It doesn't seem to be going through the php script.

          It doesn't crash, it doesn't give me an error. I can't tell what it is doing.

          The javascript part seems to be working ok because I can see the console.log() traces. If I deliberately use the wrong php file name in the .open() then it tells me that file is not found which is as it should be, for example

          Code:
              request.open("POST", "./xxtest.php", true);
          Other than that I can't tell what it is doing inside the php script. To debug, I have tried to log it. I have tried to write to db. I have tried to write to html local storage. Can't see a thing from the php script!

          How do I debug this?

          this is the javascript
          Code:
          function xx()
          {
              var request = new XMLHttpRequest();
              console.log("11");
              request.open("POST", "./test.php", true);
              console.log("22");
              console.log("33");
              request.send('type=FIAT&model=500');
              console.log("44");
          }
          this is the php script
          Code:
          localStorage.setItem("lastname", "wow");
          error_log("Big trouble!", 1,  "xx@yahoo.com.au");
          
          if (!isset($_POST['type'],$_POST['model'])) {
              header('HTTP/1.0 400 Bad Request');
              echo 'Missing "type" and/or "model".';
              exit(0);
          }
          
          //here I write text to db.

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #6
            if there is no opening php tag (<?php) it will be treated as text, not as PHP script.

            besides that JS console calls don’t make sense in a non-JS environment such as PHP.

            Comment

            • dragon52
              New Member
              • Jun 2009
              • 72

              #7
              I did have the <?php ?> tags but haven't shown it to you and the console.log() are in javascript.

              When I run this all I can see are the console.log() traces in js. Nothing else happens. Any other suggestions?


              HTML
              Code:
              <input type="submit" name="btnSave" value="Save" onclick="xx()" />

              javascript
              Code:
              function xx()
              {
                  var request = new XMLHttpRequest();
                  console.log("11");
                  request.open("POST", "./test.php", true);
                  console.log("22");
                  console.log("33");
                  request.send('type=FIAT&model=500');
                  console.log("44");
              }

              test.php script
              Code:
              <?php
              
              if (!isset($_POST['type'],$_POST['model'])) {
                  header('HTTP/1.0 400 Bad Request');
                  echo 'Missing "type" and/or "model".';
                  exit(0);
              }
              
              // code to write some data to db which does not work
              
              ?>

              Comment

              • Dormilich
                Recognized Expert Expert
                • Aug 2008
                • 8694

                #8
                since your AJAX code does not process the response (i.e. it only sends off the data) there is nothing further to happen.

                Comment

                • dragon52
                  New Member
                  • Jun 2009
                  • 72

                  #9
                  Hi Dormilich,

                  I have solved the problem. I have you to thank for pointing me in the right direction.

                  Here are the codes, in case someone else wants to do something similar.

                  javascript

                  Code:
                  //str_json = string in json format
                  //e.g. str_json = '{"persons":[{"name":"xxx"},{"name":"yyy"}]}'
                  
                  var request = new XMLHttpRequest();
                  request.open("POST", "./test.php", true);
                  request.setRequestHeader("Content-type", "application/json");
                  request.send(str_json);

                  test.php script
                  Code:
                  <?php
                  
                  //retrieve json string
                  $str_json = file_get_contents('php://input');
                  
                  //convert string to json object
                  $json = json_decode($str_json);
                  
                  //loop through records in object
                  foreach ($json->persons as $obj) {
                      //do something with the data
                      // eg save $obj->name to database
                  };
                  ?>

                  Comment

                  Working...