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

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.


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.

What you are missing is the same-domain security policy. The request must be to the same domain making the request.

yeah im learning about that now. thanks

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.

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.

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.


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\
";
    for (var i in obj) {
        s += i + ' : ' + obj[i] + "\
";
    }
    alert(s)
}

// send the request
cesarcesarCOM.send(src, requestId, callback);

an example json_reply.php script


<?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("&#37;s.setResponse('%s', %s)", $_GET['comObjectName'], $_GET['requestId'], $json);

}


the php script will output somethign like


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.

thanks for the reply. i will give it a try and post my results.

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?

heh…in that case just


var img = new Image();
img.src = 'url';

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.

Are you trying to use AJAX to get PHP variables before the page is rendered? If so perhaps CURL would be a better solution.