Skip to content
Advertisement

Cannot get my GRAPHQL response into an iterable JSON format

so a bit of background. I am making a GRAPHQL call to shopify’s graphQL api. I am getting data back (yay!) and it is correct (double yay!!), unfortunately I cannot then do very much with the data other than look at it – I cannot iterate through it with regular JSON syntax. My plan is to then have the data be put into javascript generated HTML elements to display to the user e.g. generate a list with the titles/pictures of the products.

Without further ado, my code.

Step 1: a JS function to respond to my keypresses and run an async fetch:

function ajaxProductSearch(shopCode){
    let devSearch = document.getElementById('product_search_dev');
    devSearch.addEventListener("keyup", () => {
        shopCode = document.querySelector(".langTab.active input").value;
        showGraphQL(shopCode, devSearch.value);
    });
}

Step 2: my async fetch call to the php script

async function showGraphQL(shopCode, search){
    const response = await fetch(`../models/ajaxcall.php?shop=${shopCode}&searchString=${search}`);
    const graphQL = await response.json();
     console.log(graphQL);
}

Step 3: my php script itself running the graphQL call, done with curl

3a: The curl function
function graphQLCall($qry, $endpoint, $flag=''){
        $headers = array();
        $headers[] = 'Content-Type: application/graphql';
        $headers[] = 'X-Shopify-Access-Token: '.$authToken;

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_Header, 1);

        $result = curl_exec($ch);
        curl_close($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        
        $graphQL = json_decode($result);
        if($flag == ''){
            return $graphQL;
        } elseif($flag == 'flag'){
            return $result;
        }
    }

3b: the code that preps the query for the graphQL func $query1 uses the $_POST[] to get the $searchString from the front end to the backend

        $query1 = '{
  products(first: 25, query: "title:'.$searchString.'") {
    edges {
      node {
        id
      }
    }
  }
}';
$mediaID = graphQLCall($query1, $endpoint);

$query1 is passed through the graphQLCall() and then its response, which is the id of the product is then passed into a 2nd query to then call the product itself: 3b of the php script:

    foreach($mediaID->data->products->edges as $a){
        // echo $a->node->id;
            $query2 = '{
  product(id: "'.$a->node->id.'") {
    id
    title
    images(first:1) {
      edges {
       node {
         originalSrc
         id
       }
      }
    }  
  }
}';         
            array_push($graphQLArray, $query2);
        }

It then pushes the response into an array, so I am left with an array full of queries with the correct product id. Next that array is iterated through in order to call the products themselves. 4b of php script:

$restCallArray = array();
    foreach($graphQLArray as $t){
        array_push($restCallArray, graphQLCall($t, $endpoint, "flag"));
    }
    $json = json_encode($restCallArray);
    print_r($json);

The final step in my php script is to print_r($json);

after which it is then processed by my async showGraphQL() function; written above.

My async fetch responds with something like this when I post to innerHTML:

{"data":{"product":{"id":"gid://shopify/Product/6736442654756","title":"Cactus Sneaker Women","images":{"edges":[{"node":{"originalSrc":"https://cdn.shopify.com/s/files/1/0009/8421/9684/products/76-10-49321-548_1.jpg?v=1631627733","id":"gid://shopify/ProductImage/28632222433316"}}]}}},"extensions":{"cost":{"requestedQueryCost":4,"actualQueryCost":4,"throttleStatus":{"maximumAvailable":2000.0,"currentlyAvailable":1996,"restoreRate":100.0}}}},{"data":{"product":{"id":"gid://shopify/Product/6736442687524","title":"Cactus Sneaker Men","images":{"edges":[{"node":{"originalSrc":"https://cdn.shopify.com/s/files/1/0009/8421/9684/products/76-10-49322-548_1.jpg?v=1631627827","id":"gid://shopify/ProductImage/28632226070564"}}]}}},"extensions":{"cost":{"requestedQueryCost":4,"actualQueryCost":4,"throttleStatus":{"maximumAvailable":2000.0,"currentlyAvailable":1996,"restoreRate":100.0}}}}

The above response is totally correct but, the problem occurs when I try to place it in a html element like: graphQL[i].data.product.id I receive undefined. That is my problem that I am unable to correctly iterate through what appears to be a JSON.

I am new to graphQL and to using API’s in general so appreciate any help and apologize that its so longwinded, I hope the question/problem is clear and that the code is presented clearly too.

  • Boogabooga

Advertisement

Answer

So in case anyone finds this later and runs into the same problem. Going off of what @morganney said, I was receiving an Object. So by my logic, which is not the logic you want to lead you into battle but whatever, I need to parse this object into a JSON using JSON.parse() so. I did NOT change my PHP script but rather my JS async graphQL() This is my edited async GraphQL() func

async function showGraphQL(shopCode, search){
    const response = await fetch(`../models/ajaxcall.php?shop=${shopCode}&searchString=${search}`);
    const graphQL = await response.json();
     for(let i = 0; i < graphQL.length; i++){
         let graphQLJSON = JSON.parse(graphQL[i]);
         console.log(graphQLJSON.data.product.id);
     }
}

Confusingly, I loop through my graphQL variable, and call JSON.parse(graphQL[i]) on it, I am then able to console.log specific values of the now JSON.

I hope this helps someone someday and thanks to the people who commented.

  • Boogabooga
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement