SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Addict
    Join Date
    Jun 2005
    Posts
    196
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    http_request failing between sites

    im trying to call a page on "Server B" from "Server A" using http_request method. the problem is the request fails at http_request.open(). Below is the very basic code im using that can be found everywhere online.

    Code Calling from a page on Server (site) A. Requesting URL is on Server (site) B
    Code:
    makeRequest('http://www.sitename.com/ajax_insert.php?field_name=test&field_value=',this.value);
    This is the code in the makeRequest() function which is on Server (site) A.
    Code:
    function makeRequest(url, parameters) {
    
    	http_request = false;
    	if (window.ActiveXObject) { // IE
    		try {
    			http_request = new ActiveXObject("Msxml2.XMLHTTP");
    		} catch (e) {
    			try {
    				http_request = new ActiveXObject("Microsoft.XMLHTTP");
    			} catch (e) {}
    		}
    	} else if (window.XMLHttpRequest) {// Mozilla, Safari,...xmlHttpReq.overrideMimeType
    		http_request = new XMLHttpRequest();
    		if (http_request.overrideMimeType) {
    			// set type accordingly to anticipated content type
    			http_request.overrideMimeType('text/xml');
    		}else{ alert('Did not create *http_request.overrideMimeType*'); return false; }
    	} 
    
    	if (!http_request) {
    
    		alert('Cannot create XMLHTTP instance');
    		return false;
    
    	}
    
    	http_request.onreadystatechange = alertContents;
    
    	// FOR GET VARS
    	http_request.open('GET', url + parameters, true);
    	http_request.send(null);
    	
    }
    So what am i missing? How can i get the http_request to process a page on another server (site). FYI, outside this application, my code as written works fine.

    Thank you much for all the help.

  2. #2
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,269
    Mentioned
    196 Post(s)
    Tagged
    2 Thread(s)
    What you are missing is the same-domain security policy. The request must be to the same domain making the request.

  3. #3
    SitePoint Addict
    Join Date
    Jun 2005
    Posts
    196
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yeah im learning about that now. thanks

  4. #4
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you need cross domain communication, you can however dynamically load script urls. You can pass arguments in the query string, and have the response be javascript/json data.

  5. #5
    SitePoint Addict
    Join Date
    Jun 2005
    Posts
    196
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you need cross domain communication, you can however dynamically load script urls. You can pass arguments in the query string, and have the response be javascript/json data.
    Can you further describe this or pass some links along. thank you.

  6. #6
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've never actually done this, but heres the general idea. I imagine this is probably what they had to do before xmlhttprequest became prevalent. I'm kinda a javascript novice so take my advice/code lightly.

    Basically, each time you want to send some data to an external server, you create a new script element and set the src of it to pass the data along. So long as this url returns valid javascript, it will execute and will give us a way to get data back as well.
    Code JavaScript:
    function ExternalCom() {
        this._responses = {};
        this._onReadyStateHandlers = {};
     
        this.send = function(src, id, onReadyStateHandler) {
            this._onReadyStateHandlers[id] = onReadyStateHandler;
            var el = document.createElement('script');
            el.setAttribute('src', src);
            el.setAttribute('type', 'text/javascript');
            document.getElementsByTagName('head')[0].appendChild(el);
        }
     
        this.setResponse = function(id, obj) {
            this._responses[id] = obj;
            if (this._onReadyStateHandlers[id]) {
                this._onReadyStateHandlers[id](obj);
            }
        }
     
        // calling this method before the external script loads will result in undefined
        this.getResponse(id) {
            return this._responses[id];
        }
    }
     
    cesarcesarCOM = new ExternalCom();
     
    // make an id for this message exchange
    var requestId = 'foo1';
     
    // the url to load along with the id, the name of the object we decided to use when we initialized ExternalCom(), and any other query string args
    var src = 'http://example.com/json_reply.php?action=getServerTimeHello&comObjectName=cesarcesarCOM&requestId=' + requestId;
     
     
    // define a function to be executed when the response loads, so we can do something with the data
    var callback = function(obj) {
        var s = "heres the variables we got back\n";
        for (var i in obj) {
            s += i + ' : ' + obj[i] + "\n";
        }
        alert(s)
    }
     
    // send the request
    cesarcesarCOM.send(src, requestId, callback);

    an example json_reply.php script
    PHP Code:
    <?php
    header
    ('Content-Type: text/javascript');
    // prob send some no-cache headers too...

    if ($_GET['action'] == 'getServerTimeHello') {
        
    $time date('l jS \of F Y h:i:s A');
        
    $text 'hello!';
        
    $json json_encode(array('time' => $time'text' => $text));
        
        
    printf("%s.setResponse('%s', %s)"$_GET['comObjectName'], $_GET['requestId'], $json);

    }
    the php script will output somethign like
    Code:
    cesarcesarCOM.setResponse('foo1', {"time":"Tuesday 5th of August 2008 02:31:32 PM","text":"hello!"})
    Which the browser will execute. This will load the response into our object and then call the onReadyStateHandler function.

    Hope that helps.

  7. #7
    SitePoint Addict
    Join Date
    Jun 2005
    Posts
    196
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks for the reply. i will give it a try and post my results.

  8. #8
    SitePoint Addict
    Join Date
    Jun 2005
    Posts
    196
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just to confirm. The JS goes on the host server (site). The PHP (json_reply.php) is the data receiving page on the target server (site). I dont need to output anything as Im just sending data for a PHP page to process. I'm guessing i don't do anything with the last part of code correct?

  9. #9
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    heh...in that case just
    Code:
    var img = new Image();
    img.src = 'url';

  10. #10
    SitePoint Addict
    Join Date
    Jun 2005
    Posts
    196
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    var img = new Image();
    img.src = 'url';
    huh. are you now being sarcastic. thanks. I'll figure your code out. thanks for the last bit of help.

  11. #11
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,269
    Mentioned
    196 Post(s)
    Tagged
    2 Thread(s)
    Are you trying to use AJAX to get PHP variables before the page is rendered? If so perhaps CURL would be a better solution.


Bookmarks

Posting Permissions

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