Home > Back-end >  Woocommerce functions returning 500 when called by Ajax
Woocommerce functions returning 500 when called by Ajax

Time:01-12

I have created custom plugin that includes a function that sends a GET call to a third party API to get a list of products. It then loops through the list and sends another GET request(using the sku #) for each products details. Then it checks for an existing product and updates the details, if there is no existing product it adds the product to Woocommerce.

The function I have created works just fine when I just add it to a page but I have put it into a separate file to make calls to it with ajax I get a 500 error.

I have narrowed it down to the breaking point and it's whenever a Woocommerce function is called (wc_get_products(), $NewProd = new WC_Product_Simple(), etc.).

Is this some sort of server timeout thing I can adjust? Or maybe something I can change in the WordPress config file? May be wishful thinking. Hopefully, someone can help.

Custom Loop Function in Separate File:

<?php
const bb_lAPI = 'https://sca1.furnguy.com/sca1web/oecgi3.exe';
const bb_tAPI = 'https://sca1.furnguy.com/sca1play/oecgi3.exe';

if (isset($_GET['sec55135'])):
    $bbwdVerify = strval($_GET['sec55135']);


     $bb_curl = curl_init();
   // OPTIONS:
   if( $bbwdVerify == 'Live'):
       $bb_url = bb_lAPI;
   else:
       $bb_url = bb_tAPI;
   endif;
   curl_setopt($bb_curl, CURLOPT_URL, $bb_url . '/inet_website_product_lookup?searchkey=Aluminum');


   curl_setopt($bb_curl, CURLOPT_HTTPHEADER, array(
      'Authorization: Bearer CannotShowThis123',
      'Content-Type: application/json'
   ));
   curl_setopt($bb_curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($bb_curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
   // EXECUTE:
   $result = curl_exec($bb_curl);
   if(!$result){die("Connection Failure");}
    curl_close($bb_curl);
    $bbwd_json = json_decode($result);
    if($bbwd_json->errors):
        echo '<h1>API Error</h1><p >'.$bbwd_json->errors->system.'</p>';
        echo '<p>requested url = <strong>' . $bb_url . '/inet_website_product_lookup?priceslist=SCA1</strong></p>';
    else:

        echo '<h1>No errors!!!</h1>';
        echo '<p>requested url = <strong>' . $bb_url . '</strong></p><hr style="margin-bottom: 50px;">';
        $bbwdItemArr = $bbwd_json->itemlist;
        $bbwdItemArrCount = (int) $bbwd_json->totalresults;
        $bbwd_Product = array();

    for($bbwdI = 0; $bbwdI <= $bbwdItemArrCount; $bbwdI  ):
        $bbwdProdSS =  $bbwd_json->itemlist[$bbwdI]->skuserial;
        if($bbwdProdSS):
            
            echo "Product ".$bbwdI." SKUSerial = ".$bbwdProdSS."<br>";
            bbwdItemApiLook($bbwdProdSS, "Live");
        endif;
        echo "<hr>";
     endfor;
    endif;//end if errors









endif; // end if isset $_GET['sec55135']




function bbwdItemApiLook($bbwdItemSS, $bbwdTest){
    

       // OPTIONS:
       if($bbwdTest == 'Live'):
           $bb_url2 = bb_lAPI;
       else:
           $bb_url2 = bb_tAPI;
       endif;

        echo $bb_zurl2.'/inet_website_item_detail?item='.$bbwdItemSS."<br>";
    //$bb_url2.'/inet_website_item_detail?item='.$bbwdItemSS
         $bb_curl2 = curl_init();
        curl_setopt($bb_curl2, CURLOPT_URL, $bb_url2.'/inet_website_item_detail?item='.$bbwdItemSS);
    
    
       curl_setopt($bb_curl2, CURLOPT_HTTPHEADER, array(
          'Authorization: Bearer CannotShowThis123',
          'Content-Type: application/json'
       ));
       curl_setopt($bb_curl2, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($bb_curl2, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
       // EXECUTE:
       $result2 = curl_exec($bb_curl2);
       if(!$result2){die("Connection Failure");}
       curl_close($bb_curl2);
        $bbwd_json2 = json_decode($result2);
        if($bbwd_json2->errors):
            echo '<h2>API Error = <u>'.$bbwd_json2->errors->system.'</u></h2>';
        else:
                $bbwdMapped = bbwdMapProduct($bbwd_json2);
                echo "<h3>".$bbwdMapped->ssku."</h3>";
                bbwdCheckProd($bbwdMapped);
            
        endif;

}

function bbwdMapProduct($bbwdArr){
        $bbwdTitle = $bbwdArr->factsrec->shortdescription[0];
        $bbwInStock;
        $bbwdSku = $bbwdArr->sku;
        $bbwdSSku = $bbwdArr->skuserial;
        $bbwdPrice = $bbwdArr->inventoryrec->retail;
        $bbwdSalePrice = $bbwdArr->inventoryrec->retail3;
        $bbwdDescription = $bbwdArr->inventoryrec->description;
        if($bbwdArr->availability == "In Stock"):
            $bbwInStock = "instock";
        else:
            $bbwInStock = "outofstock";
        endif;
        $bbwdPolishedProd = ["title"=>$bbwdTitle, "instock"=>$bbwInStock, "sku"=>$bbwdSku, "price"=>$bbwdPrice, "sale_price"=>$bbwdSalePrice, "description"=>$bbwdDescription, "ssku"=>$bbwdSSku];
        return $bbwdPolishedProd;
}

/*=====================================================================
 *                     Manage Woocommerce Products
 * ==================================================================*/
/******** Check if product exists ***********/
function bbwdCheckProd($bbwdTheProd){
        $bbwdProdName = $bbwdTheProd["title"];
        $bbwdNameAdj = strtolower($bbwdProdName);
        $bbwdProdSlug = str_replace(" ", "-", $bbwdNameAdj);
        $bbwdProdSku = $bbwdTheProd["ssku"];
        $bbwdProdPrice = $bbwdTheProd["price"];
        $bbwdProdSPrice = $bbwdTheProd["sale_price"];
        $bbwdProdDesc = $bbwdTheProd["description"];
        $bbwdProdStock = $bbwdTheProd["instock"];
        $bbwdExProds = [];


/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/

                            THIS IS WHERE THE CODE IS BREAKING!!!
if you a just leave "bbwdOurProducts2" as an empty var the code breaks at the $bbwdNewProd = new WC_Product_Simple(); function located on the ELSE half of the if statement just below.

/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
        $bbwdOurProducts2 = wc_get_products( array('sku' => $bbwdProdSku) );

        if(!empty($bbwdOurProducts2)):
            foreach($bbwdOurProducts2 as $bbwdSProduct):

                if($bbwdSProduct->sku == $bbwdProdSku):
                    $bbwdProdID = get_the_id($bbwdProdSku);
                    $bbwdSProduct->set_name( $bbwdProdName );
                    $bbwdSProduct->set_slug( $bbwdProdSlug );
                    $bbwdSProduct->set_regular_price( $bbwdProdPrice );
                    if($bbwdProdSPrice > 0):
                        $bbwdSProduct->set_sale_price( $bbwdProdSPrice );
                    else:
                        $bbwdSProduct->set_sale_price( $bbwdProdPrice );
                    endif;

                    $bbwdSProduct->set_stock_status( $bbwdProdStock );
                    $bbwdSProduct->save();
                endif;
            endforeach;
        else:
                $bbwdNewProd = new WC_Product_Simple();
                $bbwdNewProd->set_name( $bbwdProdName );
                $bbwdNewProd->set_slug( $bbwdProdSlug );
                $bbwdNewProd->set_sku( $bbwdProdSku );
                $bbwdNewProd->set_regular_price( $bbwdProdPrice );
                $bbwdNewProd->set_sale_price( $bbwdProdSPrice );
                $bbwdNewProd->set_stock_status( $bbwdProdStock );
                $bbwdNewProd->set_short_description( 'short description here...' );
                $bbwdNewProd->set_description( 'long description here...' );
                $bbwdNewProd->set_image_id( 21 );
                $bbwdNewProd->set_category_ids( array( 30 ) );
                $bbwdNewProd->save();
        endif;
echo "Complete!!!";

}


?>

Ajax request

<script type="text/javascipt">
let bbwdLoader = document.createElement('img');
let resultDiv = jQuery('#bbwdResults');
bbwdLoader.src = "https://scanhome.brightbridgeweb.com/wp-content/plugins/bright-bridge-product-api-functions/assets/img/Rhombus-Loader.gif";

/**************************************************************************************************/
/**************************************************************************************************/
          The "syncProds()" function is the "onclick" function attached to a button.

I use jQuery in place of $ because of variable errors when using jQuery with WordPress
/**************************************************************************************************/
/**************************************************************************************************/
function syncProds(){
    let resultDiv = jQuery('#bbwdResults');
    resultDiv.html(bbwdLoader);
    console.log('Script Working!!!');
    
    
    
    
    bbwdTheCall();
}

async function bbwdTheCall(){
    let bbwdRes;
    await jQuery.ajax({
        url: "https://scanhome.brightbridgeweb.com/wp-content/plugins/bright-bridge-product-api-functions/syncAllProducts.php", 
        type: "GET",
        async: true,
        timeout: 0,
        data: {'sec55135': 'Live'},
        success:function(result){
                resultDiv.html(result);
                bbwdRes = result
                },
        error:function(error){
            resultDiv.html("<h2>There was an error!!!</h2><h4>"   error.status   " "   error.statusText   " </h4>");
            console.log(error);
        }
    });
    console.log(bbwdRes);
}
</script>

CodePudding user response:

If I got this correctly, first you added the code in a plugin and it worked but when you moved the code into a separate file,it didn't work. Correct? Did you load the WordPress in your https://scanhome.brightbridgeweb.com/wp-content/plugins/bright-bridge-product-api-functions/syncAllProducts.php file? Probably not. So you can either load a wordpress in your file with include "path to wp-load.php" or use a proper way of running ajax in WordPress using ajax actions. WordPress has a really good support for ajax. Whatever you do, before you run your custom code, WordPress and plugins must be loaded and ready to use.

  • Related