0

I need to make an easy JavaScript function that will out put some html to screen by calling a PHP file on a different server.

Something like this:

[JavaScript]
contents = http://www.example.com?clientID=1
print to screen contents;
[/JavaScript]

The PHP file would look up the information based on that clientID that is passed from the javascript call and then return the correct string, in this case an image.

I want to use JavaScript because I want this to be usable by everyone not just people that can add PHP to their websites, for example a basic Wordpress site wouldn't be able to include a PHP file from an outside server without an extra plugin to include the php in the page etc.

Like how you can include twitter & facebook code in your site to show your news feed but I want the server side to be PHP.

2

1 Answer 1

1

If by "different server" you mean a different domain name, then you would want to use AJAX with JSONP. JSONP prevent cross-domain issues by wrapping a JSON string with padding. I wouldn't invent a new markup unless it's absolutely necessary.

With jQuery, you would do something like this:

$.ajax({
    url: "http://www.example.com/api.php",
    dataType: "jsonp",
    success: function(data) {
        alert("JSONP Received");
   }
});

Then your server would be using PHP that would output something like this:

$data = array(
    contents => "http://www.example.com?clientID=1"
);
echo $_GET['callback'] . '(' . json_encode($data) . ')';

There are lots of examples like this. See Simple jQuery, PHP and JSONP example? and PHP, jQuery Ajax and json return over a cross domain for more information

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer... after 4 days of CORS errors and 403 forbidden errors...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.