2

In the code below I try to post some data to a table and then retrieve several records from the table afterwards. For testing purposes I have only included a dummy query in the php, which returns a valid xml.

But the Javascript readystate only reach readystate 1 (twice). As the php seems to be working fine I suspect I have scripted the javascript incorrectly. Is it a problem with the "request" variable?

$(document).ready(function() {
  $('form').submit(function(event) { //Trigger on form submit
    $('#name + .throw_error').empty(); //Clear the messages first

    var name = $('input[name=name]').val();
    var request = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
    request.onreadystatechange = function() {

      if (request.readyState == 4 && request.status == 200) {
        var xml = request.responseXML;
        var dynamiclist = '';
        document.getElementById("myLink").innerHTML = '';
        var posts = xml.documentElement.getElementsByTagName("post");
        for (var i = 0; i < posts.length; i++) {
          var Msg = posts[i].getAttribute("Msg");
          alert("test");
          var dynamiclist = dynamiclist + '<article class="middleContent"><header><h2><a href="#" title="Post">' + Msg + '</a></h2></header> </article>';
          document.getElementById("myLink").innerHTML = dynamiclist;
        };
      };
    };
    request.open('POST', 'process.php', true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send('name=' + name);
  });
});

2 Answers2

2

Using jQuery makes sense here.

Simple solution however most probably is to simply remove the last "true" in request.open(), which makes the request an asynchronous, non-blocking one (which it really should be anyway). MDN also states at onreadystatechange that you shouldn't be using it with synchronous requests (aka requests that have "true" as third argument for open())

Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

tom
  • 692
  • 6
  • 12
  • Thanks, it still does not work though, only reaches readystate 1. I am playing around with a jQuery solution instead, but there I am having problems finding the nodes, which I think is due to problems with reading/parsing the php output. – ExiledCactus Jun 04 '15 at 20:46
0

Try preventing the default form event from firing:

$('form').submit(function(event) { event.preventDefault();

This prevents the form element from reloading the browser window.

Harry Theo
  • 784
  • 1
  • 8
  • 28