Cross Domain AJAX Requests

Introduction

Now on the web AJAX calls are becoming more and more common, they can be very useful to create a better user experience on your web applications. But on most modern browsers they will block anycross domain AJAX calls mainly for security reasons and the fact that AJAX uses client side scripting which might not work on another domain. If you are using jQuery to make your AJAX calls you can't post data to another domain, but PHP can post data to other domains by using the cURL extension. So to get around the cross domain AJAX problem, post data to your own PHP page and let cURL post this to the required URL.
In this article I will show you how to use cURL to post data from a jQuery post.

Change The jQuery POST Function

In this tutorial I am going to use PHP cURL to post data to another domain.
In jQuery to make an POST AJAX call you use the following.
var data = "parameters=1&para=2";             

             $.ajax({
    url: "http://www.example.com/post_url.php",
    data: data,
    type: "POST",
    success: function(data, textStatus, jqXHR){
   console.log('Success ' + data);
    },
    error: function (jqXHR, textStatus, errorThrown){
   console.log('Error ' + jqXHR);
    }
  });
This will post 2 parameters to http://www.example.com/post_url.php, but when this is sent you will get cross domain AJAX errors which means you aren't allowed to POST data to a different domain.
To get round this we are going to post to a page on our domain and then use this page to post the data.
var data = "url=http://www.example.com/post_url.php&parameters=1&para=2";             

             $.ajax({
    url: "our_domain_url.php",
    data: data,
    type: "POST",
    success: function(data, textStatus, jqXHR){
   console.log('Success ' + data);
    },
    error: function (jqXHR, textStatus, errorThrown){
   console.log('Error ' + jqXHR);
    }
  });
Notice it is the same AJAX call but I have changed the URL to a page on our server and moved the previous URL into data as a separate parameter. This is so we can get in from our PHP page and use this URL parameter to post the data.

Create A PHP Page To Post Data

Create a new PHP file and paste the following into the file.
//set POST variables
$url = $_POST['url'];
unset($_POST['url']);

$fields_string = "";
//url-ify the data for the POST
foreach($_POST as $key=>$value) { 
 $fields_string .= $key.'='.$value.'&'; 
}
$fields_string = rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($_POST));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);
This will first grab the URL out of the POST variable and then save this in a local variable this is so we can use this to send the data to. We need to then remove the URL from the POST variable to make sure we don't send this through as well.
Then we can loop through the POST variable and create our own query string.
Now we use cURL to post the data through to the URL.
That's it we have performed a cross domain AJAX call using jQuery and cURL.

PHP Debug In Browser Console

When debugging in PHP there are a few techniques you can use, you could use something likeXdebug which will allow you to step through your code at run time and you can see exactly what the code is doing. Xdebug will allow you to step into function and make sure the variables are being set as the should be.
Your other option is to output the code in the browser and exit the script so it just displays what you want to debug and nothing else, something similar to this.
<?php
echo '<pre>';
print_r($debug_array);
echo '</pre>';
exit;
?>
This will allow you to see exactly what is in this variable at a certain time of running your code.
But what if you want to view the rest of the page and debug at the sametime, you can simply print the variable without the exit in your code. But then you get the problem of the print being on the page which could either break your design or the debug will be displayed in the design.
Your other option is to write debug into a log file, this can be done with a debug class which writes to a debug log file, allowing you to view all your variables and not breaking your design.
If you don't want to send your data to a log file you can also try this neat little trick and output debug data into the browser debug console.
console
Here is a snippet of a function you can use to output PHP data to the browser console.
<?php
/**
 * Send debug code to the Javascript console
 */ 
function debug_to_console($data) {
    if(is_array($data) || is_object($data))
 {
  echo("<script>console.log('PHP: ".json_encode($data)."');</script>");
 } else {
  echo("<script>console.log('PHP: ".$data."');</script>");
 }
}
?>

Access Database Outside Of WordPress

Sometimes I've needed to build a new page outside of WordPress but still have the ability to access the WordPress database from this new page. This would normally use custom tables you've created.
To access the WordPress database normally you would just need to use the global variable $wpdb. This object connects to your database using the credentials found in the wp-config.php in the constant variables DB_NAME, DB_HOST, DB_USER, DB_PASSWORD.
function access_db()
{
   global $wpdb;
}
The $wpdb object has a number of methods that you can use to interact with the database, you are able to use the following:
  • query() - To run a custom SQL query on the database.
  • get_var() - Get a single value from the database and add as a variable.
  • get_row() - Get the single row from the database.
  • get_col() - Get the column information from the database.
  • get_results() - Get all the results from SQL query.
  • insert() - Insert a row into the database
  • replace() - Replace the data in the row.
  • update() - Allows you to update a row in the database.
  • delete() - Allows you to delete a row from the database.
  • prepare() - Used for SQL escaping when processing the SQL query.
If you're using custom database tables in your application then you will be able to access them by using the $wpdb object and writing your own custom queries.
For more information on creating custom tables in WordPress use this tutorial.
If you're creating a page outside of the WordPress application you won't have access to the $wpdb object, so you will need to instantiate the WordPress application before you can access it. To do this in WordPress it's very easy. If you look at the .htaccess file you will see some code like this.
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
This will send all requests on the domain to go through the index.php file, then if you look inside the index.php file you will see how WordPress will be loaded, simply by loading the file wp-blog-header.php.
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
When this is loaded it will create the WordPress application and instantiate all the variables that you will need. You will have access to the $wpdb object which will automatically connect to the datbase in the wp-config.php file.
Now you will be able to use this variable in your new page outside of the WordPress application.
Create a new file, this example is a new file at the root level of your WordPress files. First require the wp-blog-header.php file and this will instantiate WordPress outside of the application.
<?php
// Get access to WordPress
require( dirname( __FILE__ ) . '/wp-blog-header.php' );

// Get all posts
$posts = $wpdb->get_results('SELECT * FROM '. $wpdb->prefix.'posts');