JavaScript xmlHttpRequest.Send() issues.
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12

Thread: xmlHttpRequest.Send() issues.

  1. #1
    Join Date
    May 2012
    Posts
    8

    xmlHttpRequest.Send() issues.

    I have the following code in Javascript to talk to my Comet server:

    Code:
                function getXmlHttpRequestObject() {
                    if (window.XMLHttpRequest) {
                        //document.getElementById("_receivedMsgLabel").innerHTML += "Non-microsoft xmlHttpRequest object created.<br/>";
                        alert("Non-microsoft xmlHttpRequest object created.");
                        return new XMLHttpRequest();
                    }
                    else if (window.ActiveXObject) {
                        //document.getElementById("_receivedMsgLabel").innerHTML += "Microsoft xmlHttpRequest object created.<br/>";
                        alert("Microsoft xmlHttpRequest object created.");
                        return new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    else {
                        alert("Status: Could not create XmlHttpRequest Object.  Consider upgrading your browser.");
                        //document.getElementById("_receivedMsgLabel").innerHTML += "Status: Could not create XmlHttpRequest Object.  Consider upgrading your browser.<br/>";
                    }
                }
    
                var sendReq = getXmlHttpRequestObject();
                var receiveReq = getXmlHttpRequestObject();
                var lastMessage;
                var mTimer;
    
                //Gets the server response:
                function getResponse() {
                    document.getElementById("_receivedMsgLabel").innerHTML += "getResponse() called.<br/>";
                    if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
                        //if (receiveReq.readyState == 0) {
                        //receiveReq.open("POST", 'http://tardis:1802', true, "server", "server123");
                        //receiveReq.open("POST", 'http://localhost:1802', true, "server", "server123");
                        //receiveReq.open("POST", 'http://holit109:1802', true, "server", "server123");
                        //receiveReq.open("POST", "http://localhost:1802", true, "server", "server123");
                        receiveReq.open("POST", "http://L45723:1802", true, "server", "server123");  //must use this URL at work.
                        receiveReq.onreadystatechange = handleReceiveMessage;
                        alert("handleReceiveMessage assigned to onreadystatechange event.");
                        receiveReq.setRequestHeader("Content-Type", "text/x-json");
                        receiveReq.timeout = 0;
                        var currentDate = new Date();
                        var sendMessage = JSON.stringify({
                            SendTimestamp: currentDate,
                            Message: "Message 1",
                            Browser: navigator.appName
                        });
                        //receiveReq.send("<?xml version='1.0'?><Request><Command>Queue</Command><User>user1</User><Message>Message 1</Message><Message>Message 2</Message><Message>Message 3</Message></Request>");
                        alert("JSON message created.  About to send...");
                        receiveReq.send(sendMessage);
                        alert("Message sent.");
    
                    }
                }
    
                //function for handling the return message from Comet
                function handleReceiveMessage() {
                    if (receiveReq.readyState == 4) {
                        document.getElementById("_receivedMsgLabel").innerHTML += "Message received!<br/>";
                        var status = receiveReq.status;
                        //document.getElementById("_receivedMsgLabel").innerHTML += "Status received!<br/>";
                        var txt = receiveReq.responseText;
                        var receivedMsg = JSON.parse(txt);
                        document.getElementById("_receivedMsgLabel").innerHTML += receivedMsg.Message + "<br/>";
                        //var receivedTime = new Date();
                        //alert("Got current date.");
                        //alert(receivedTime);
                        //var receivedTime_ms = receivedTime.getTime();
                        //alert("Got time message received in ms.");
                        //alert(receiveReq.SendTimestamp);
                        //var sentTime_ms = getDateFromFormat(receiveReq.SendTimestamp, "dd/MM/yyyy HH:mm:ss");
                        //var sentTime = new Date(receiveReq.SendTimestamp);
                        //alert("Got time message sent in ms.");
                        //var sentTime_ms = sentTime.getTime();
                        //var difference_ms = receivedTime_ms - sentTime_ms;
                        //document.getElementById("_receivedMsgLabel").innerHTML += "Comet took " + difference_ms + " ms.<br/>";
    
                        mTimer = setTimeout("getResponse();", 0);
                    }
    
                    getResponse();
                }
    The xmlHttpRequest.Send() won't run in Firefox. It crashes there.
    In Safari, Opera and Chrome, it runs.
    In Safari the handleReceiveMessage() is never called.
    In Opera and Chrome the handleReceiveMessage() is called, but nothing is returned in the xmlHttpRequest.responseText property.

    This only works in IE.

    What am I doing wrong?
    Last edited by PeejAvery; May 30th, 2012 at 10:34 AM. Reason: Added code tags

  2. #2
    PeejAvery's Avatar
    PeejAvery is offline Super Moderator Power Poster
    Join Date
    May 2002
    Posts
    10,880

    Re: xmlHttpRequest.Send() issues.

    Maybe there's more...but right off the bat...I see an issue.

    The parameter of AJAX's send() method has to be URL encoded...not JSON formatted.
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  3. #3
    Join Date
    May 2012
    Posts
    8

    Re: xmlHttpRequest.Send() issues.

    Do you mean like this:

    encodeURI(sendMessage)

  4. #4
    PeejAvery's Avatar
    PeejAvery is offline Super Moderator Power Poster
    Join Date
    May 2002
    Posts
    10,880

    Re: xmlHttpRequest.Send() issues.

    No. The string format must be the same as though it was passed through a URL, not JSON.

    variable1=value1&variable2=value2&etc=etc
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  5. #5
    Join Date
    May 2012
    Posts
    8

    Re: xmlHttpRequest.Send() issues.

    Did as you suggested but now I get an "Access to restricted URI denied" error on receiveReq.send(sendMessage); call.

  6. #6
    PeejAvery's Avatar
    PeejAvery is offline Super Moderator Power Poster
    Join Date
    May 2002
    Posts
    10,880

    Re: xmlHttpRequest.Send() issues.

    That's because you're doing cross-domain URL referencing. AJAX calls when passing parameters through POST have to be to the same domain as the page referencing it.
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  7. #7
    Join Date
    May 2012
    Posts
    8

    Re: xmlHttpRequest.Send() issues.

    The page which contains the javascript is in http://L45723/TestComet/ShowComet3.aspx

    The Comet server is http://L45723:1802

    Are they in different domains? How do I get them into the same domain?

  8. #8
    PeejAvery's Avatar
    PeejAvery is offline Super Moderator Power Poster
    Join Date
    May 2002
    Posts
    10,880

    Re: xmlHttpRequest.Send() issues.

    Same domain...different port. Take a look at this. It should help.
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  9. #9
    Join Date
    May 2012
    Posts
    8

    Re: xmlHttpRequest.Send() issues.

    Thanks so much for your help! Very informative. And thanks for your patience with an obvious novice like me.

    I followed that link and redid the code:

    Code:
        function getResponse() {
    
            $.getJSON('http://L45723:1802/?callback=testcallback', { SendTimestamp: new Date(), Message: 'Message 1', Browser: navigator.userAgent },
            function (data) {
                $('#_receivedMsgLabel').append(data.Message + '<br/>');
                getResponse();
            });
    
        }
    However, when I run in FireFox, I get this in the output:
    "NetworkError: 401 Not Authorized - http://l45723:1802/?callback=testcallback&Message=Message+1&Browser=Mozilla&#37;2F5.0+(Windows+NT+6.1%3B+WOW64%3B+rv%3A12.0)+Gecko%2F20100101+Firefox%2F12.0"

    What am I doing wrong?

    I also added the following headers to the reply from the Comet server:

    "Access-Control-Allow-Origin", client.Request.Url
    "Access-Control-Allow-Methods", "POST, GET, OPTIONS"
    "Access-Control-Max-Age", "1000"
    "Access-Control-Allow-Headers", "Content-Type"

    Shouldn't this allow cross-domain AJAX now?
    Last edited by PeejAvery; May 31st, 2012 at 03:50 PM. Reason: Added code tags.

  10. #10
    PeejAvery's Avatar
    PeejAvery is offline Super Moderator Power Poster
    Join Date
    May 2002
    Posts
    10,880

    Re: xmlHttpRequest.Send() issues.

    401 error means you need authentication to access the URL.

    http://stackoverflow.com/questions/8...ized-401-error
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  11. #11
    Join Date
    May 2012
    Posts
    8

    Re: xmlHttpRequest.Send() issues.

    Code:
    function getResponse() {
    
    
    
            var currentDate = new Date();
            var sendMessage = JSON.stringify({
                SendTimestamp: currentDate,
                Message: "Message 1"
            });
    
    $.ajax({
                type: "POST",
                url: "http://L45723:1802/?callback=testcallback",
                data: sendMessage,
                contentType: "application/json",
                beforeSend: function(xhr) {
                     xhr.setRequestHeader("Authentication", "Basic " + $.encodeBase64("server:server123")); //May need to use "Authorization" instead
                },
                success: function(data){
                    $('#_receivedMsgLabel').append(data.Message + '<br/>');
                    getResponse();
                }
            });
    
        }
    Changed my code to as above...as in the link, but don't think I understood it because I got this in Firefox:

    $.encodeBase64 is not a function
    beforeSend(xhr=Object { readyState=0, setRequestHeader=function(), getAllResponseHeaders=function(), more...})ShowComet9.aspx (line 39)
    ajax(url=undefined, options=Object { type="POST", url="http://L45723:1802/?callback=testcallback", data="{"SendTimestamp":"2012-...,"Message":"Message 1"}", more...})jquery-1.7.1.js (line 7547)
    getResponse()ShowComet9.aspx (line 41)
    ()ShowComet9.aspx (line 56)
    [Break On This Error]

    ...thentication", "Basic " + $.encodeBase64("server:server123")); //May need to use...

    Where do I get the encodeBase64 jQuery function from?
    Last edited by PeejAvery; May 31st, 2012 at 05:32 PM. Reason: Added code tags

  12. #12
    PeejAvery's Avatar
    PeejAvery is offline Super Moderator Power Poster
    Join Date
    May 2002
    Posts
    10,880

    Re: xmlHttpRequest.Send() issues.

    Notice that you added the $ believing it to be a part of jQuery. But that actual function is not in jQuery. You will need to use the following instead if you want to use jQuery.

    Code:
    $.base64.encode(string)
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

Tags for this Thread

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center