0

Good day!

What I want to achieve is when user clicks the link, it will pass the parameter to javascript, which then using ajax to call the php file where my API is. The API will process the parameter and return a json result.

My code works when the parameter values are given correctly. However I'm stuck at the part where the values are incorrect/invalid and I need to catch the error.

The API document says that if the RESPONSE is 200, then it's a success. Else there is error. My issue is I have no idea how to get this "RESPONSE == 200". Any advise is appreciated!

function callMS_API(addr, cur)
{
    $.ajax({
        type:'POST',
        url:'merklescienceAPI.php',
        data:{
        WalAddr:addr,
        CryCur:cur,
        wrapper:"testing"
        },
        
        success: function(res) 
        {
            if(res!=200)
            {
                alert("Invalid Wallet Address!");
            }
            else
            {
                alert(res);
            }
        }
    });// ajax
    
} //end callMS_API

merklescienceAPI.php

<?php
    $addr=$_POST['WalAddr'];        //Wallet Addr
    $cur=$_POST['CryCur'];          //Cryptocurrency
    $cur_code; 
    $result = "";
    
    switch ($cur) {
      case "Bitcoin":
        $cur_code = 0;
        break;
      case "Ethereum":
        $cur_code = 1;
        break;
      case "LiteCoin":
        $cur_code = 2;
        break;
      case "Tether USD":
        $cur_code = 10;
        break;
    } 

    require_once('../vendor/autoload.php');
    $client = new \GuzzleHttp\Client();
    $response = $client->post('https://api.merklescience.com/api/v3/addresses/', [
      'body' => '{"identifier":"'.$addr.'","currency":"'.$cur_code.'"}',
      'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
        'X-API-KEY' => '<API KEY>',
      ],
    ]);
    
    $data = json_decode($response->getBody());
    $result = "SCREENING: " . $data->identifier . "\n\nAddress Risk Level : " . $data->risk_level_verbose;

    //Whatever you echo will go to javascript success: function(res), and you can do alert(res)
    echo $result;

?>

==================================================================== Edit + Solution

I read and tested further on the Guzzle thingy, and came across this thread. I implemented the Try Catch in the API.php and got my result.

Javascript function

function callMS_API(addr, cur)
{
    $.ajax({
        type:'POST',
        url:'merklescienceAPI.php',
        data:{
        WalAddr:addr,
        CryCur:cur,
        wrapper:"testing"
        },
        
        success: function(res) 
        {
            alert(res);
        }

    });//ajax
} //end callMS_API

API.php

try{
        $client = new \GuzzleHttp\Client();
        $response = $client->post('https://api.merklescience.com/api/v3/addresses/', [
          'body' => '{"identifier":"'.$addr.'","currency":"'.$cur_code.'"}',
          'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
            'X-API-KEY' => '<API KEY>',
          ],
        ]);
    }catch(Exception $e){
        $error = true;
    }
    
    if($error == false)
    {
        $data = json_decode($response->getBody());
        $result = "SCREENING: " . $data->identifier . "\n\nRisk Level : " . $data->risk_level . " - " . $data->risk_level_verbose;
    }else
    {
        $result = "Invalid Wallet Address!";
    }
    
    echo $result;

Thank you everyone for your help!

user2741620
  • 305
  • 2
  • 7
  • 21
  • you can pass a callback error handler, making `callMS_API(addr, cur)` become `callMS_API(addr, cur, fnToFireIfFailed)`, then call fnToFireIfFailed() from the IF branch in success(). or promisify it. in short, bring the work to the data, not the data to the work. – dandavis Jan 22 '22 at 04:31
  • Sorry I don't understand what you are saying...you mean like: success: function(res) { if(fnToFireIfFailed(res)) { alert("Invalid Wallet Address!"); } else { alert(res); } } – user2741620 Jan 22 '22 at 05:49

2 Answers2

0

If you mean status code or HTTP status code 200 you could try add this line to your ajax option:

...
$.ajax({
... 
    statusCode: {
      200: function() {
      alert( "200 reaced" );
    },
     error: function(response) {
       if(response.status != 200)
          alert(" status code is " + response.status);
    }
...
   
0

in Ajax

    $.ajax({type:'POST',
    url:'somefile.php',
    data:{
    a name:"a value"
    } ,
  success: <<THIS EXECUTES WITH A 200 RESPONSE>>,
  error: <<THIS EXECUTES IF IT GOES BAD>>
});

The success: runs ONLY if the response is 200. for everything else you capture it with error:

A. Guattery
  • 113
  • 8