www.webdeveloper.com
Results 1 to 3 of 3

Thread: XMLHttpRequest help

  1. #1
    Join Date
    Aug 2013
    Posts
    2

    XMLHttpRequest help

    Hello. I have this code:

    Code:
    <script>
            var xhr = new XMLHttpRequest();
            params = {language:"test"};
            xhr.open('POST', '1.php', false);
            xhr.send(params);
    		alert(xhr.responseText);
    </script>
    and the 1.php:

    Code:
     <?php echo $_POST["language"]; ?>
    in the alert I'd want to get the language value, which in this case is "test".
    what's wrong with my code?

  2. #2
    Join Date
    Aug 2013
    Posts
    2
    got it working like this:

    Code:
    <script>
    var xhr = new XMLHttpRequest();
    var params = "language=test";
    xhr.open('POST', '1.php', false);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send(params);
    alert(xhr.responseText);
    </script>

  3. #3
    Join Date
    Jun 2008
    Posts
    106
    I don't think you need that Content-type header. Maybe someone can clarify on that a bit, though, because I'm not 100% sure. I know you need it in some cases, but not sure about this instance.

    But yeah, just pass the xhr.send() method a string containing your parameters. I see you figured this out.
    Just to add, in-case you didn't figure this out yet, too: you can send more than one parameter by joining then with the ampersand symbol (&).
    e.g., language=english&region=north&browser=firefox

    If you wanted to, you could make an xhr function of your own that took a url and some parameters as its (your function's) parameters. This way, you could pass in an object like with your first example.
    Here's some example code for that.
    Code:
    function post(url, obj) {
        var xhr = new XMLHttpRequest(),
            params = '', p;
    
        for (p in params) {
            params += p + '=' + encodeURIComponent( params[p] ) + '&';
        }
    
        xhr.open('POST', url, false);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send( params.slice(0, -1) ); // be sure to remove the & on the end with slice
    
        return xhr;
    }
    
    post( '1.php', {'language' : 'test'} );

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles