WordPress Code Snippets

A fresh mix of code snippets and tutorials

Cross domain posting with Ajax

57

Technically cross-domain posting is not allowed, but here is a workaround that may prove useful for your brainstorming sessions. Note that this technique is aimed at advanced developers.

Step 1: PHP

Add the following code to your PHP file named proxy.php:

<?php
$ch = curl_init();
$url = unescape($_GET['url']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
foreach ($_POST as $name => $value){
	$data[$name] = $value;
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
echo $result; ?>

This snippet uses PHP’s cURL to “forward” the POST values to the external domain and then printing the results. Think of your basic proxy service.

Step 2: jQuery

To proxy-post to your external domain, use the following slice of jQuery:

$.post("proxy.php?url=" + escape('http://example.com/api.php?function=proxy'), {
	"url": $("#wpmix_url").val(),
	"desc": $("#wpmix_desc").val(),
	"custom": $("#wpmix_custom").val(),
	"password": $("#wpmix_password").val(),
	"limit": $("#wpmix_limit").val(),
	"terms": 1,
}, function (data) {
	console.log(data);
	if (data.error) {
		alert('Error: ' + data.error);
	} else {
		$(".wpmix_result").html('Result: <a href="' + data.short + '">Link</a>').slideDown();
	}
}, "json");

This instructs the browser to post via proxy.php using the escaped version of our target URL, http://example.com/api.php?function=proxy, which will vary depending on usage.


Show Support

Like our new Facebook Page to show support!