Andrea Rose Andrea Rose - 4 months ago 165
PHP Question

BigCommerce API - PHP AJAX on Cart for Weight Returns

I'm trying to return product weights so they display on the cart for my customers.

In the cart template, I'm calling this external JS file from the cart template in BigCommerce

or backend template:

$(document).ready(function () {

var url = '';
var prodWeights;

$(".prod_SKU").each(function () {

url: url,
method: 'POST',
dataType: "json",
data: {sku: $(this).text()},
contentType: "application/json; charset=utf-8",
async: false,
crossDomain: true,

success: function (result) {
prodWeights = result;
error: function (request, textStatus, errorThrown) {



So it passes the SKU properly to the PHP file, "cartProduct.php":


$sku = $_POST['sku'];

$api_url = '' . sku;
$ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $api_url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array ('Accept: application/json', 'Content-Length: 0') );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_USERPWD, "xxxxx:xxxxxxxxxxxx" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$response = curl_exec( $ch );
$result = json_decode($response);


I believe there might be an authorization issue, when I try to hit my PHP as just "http://", I get this error:

When I try "https://" I get this:
error 2


I assume that cartProduct.php and the cart template making the XMLHttpRequest reside on the same domain. e.g. ->
XmlHttpRequest to ->
cURL SSL-Request to ->
output to browser

Otherwise see Same-Origin Policy and configure a JSONP request insead.

Ensure you set the Content-Type of the response header when jQuery uses dataType: "json". JQuery applies an accept application/json, text/javascript request header when it is used.

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason.

You should be sending the encoded value, and not the decoded variable output from print_r as it applies PHP specific formatting to the output.


$json = '{"a": "b"}';

Will output

stdClass Object
    [a] => b

Which is not valid JSON syntax.

So in cartProduct.php

 $sku = $_POST['sku'];

 $api_url = '' . sku;
 $ch = curl_init();
 header('Content-Type: application/json');
 $response = curl_exec($ch); 
 echo $response;

Be sure to remove the ending php script tag, as any line endings or include files afterward will render an additional line break in the output, and cause extra data to be submitted.

Your console.log(prodWeights); Needs to be inside your success function calls, as the variable will not become available to the javascript until after the ajax call is made.

eg ajaxRequest -> console.log(prodWeights) -> success -> declare prodWeights

So the script would need to be changed to

 success: function (result) {
    var prodWeights = result;

Your url can be easier translated for the client's current protocol by using a relative URI var url = '/cartProduct.php'; Otherwise if you are not wanting to support both protocols, be sure to redirect the user to the correct protocol if you're not already.

Last but not least, you should invest some researching into jQuery .queue and .deferred methods instead of using async: false. non-asynchronous requests are depreciated and will eventually be removed from browsers (like Java and npapi), which your developer window warns you about at the top of the console output. See: XMLHttpRequest Spec

Example: (asynchronous ajax chain, with realtime ticker, view XHR status in console to validate requests are being chanined)

var def = $.Deferred();
var promise = def.promise()
$('.prod_SKU').each(function() {
  var sku = $(this).text();
  //this creates the chaining
  promise = promise.then(function() {
    return $.ajax('/path/to/resource.php', {
      method: 'post',
      dataType: 'json',
      data: {'sku': sku},
      success: function(result) {
    //do something after the last request has completed
def.resolve(); //start the ajax request chain