Search code examples
jqueryajaxget

Print AJAX response data (from error return)


I have an AJAX request script where, for whatever reason, it returns the data but also thinks the response is an error. I have contacted the creator of the API and they are looking into it, but for the time being, I'm trying to create a workaround for the response.

Here is my script:

 <script type="text/javascript">
        $(document).on('click', '#pullDetails', function() {
             $.ajax({
                type:'GET',
                url: 'https://webservices.rrts.com/TrackWebApi/api/values/'+$('input[name=proNumber]').val(),
                success: function(data) {
                    $('.errorTitle').addClass('hidden');
                    $('.errorContent').addClass('hidden');

                    $('#carrierReturnData').removeClass('hidden');
                    $('#carrierReturnData').html(Shipment.Origin.Name);
                },
                error: function(request, status, error) {
                    console.log(request);
                    console.log(status);
                    console.log(error);
                    $('#openInvoicesOverlay').html('');
                    $('#openInvoicesOverlay').removeClass('overlay');
                    $('#freightBillDetails .box-body').html(data.SearchResults[0].SearchItem);
                }
            });
        });
</script>

Now, the success portion doesn't work, even though data is successfully returned to my GET request. So where the "error: function..." is is where things work (even though the shouldn't).

So based on this return JSON:

enter image description here

How would I print the details? As in the SearchItem field that is returned. The script does work for the .html and .remove class, but the .html portion of the error:function doesn't work and it's likely because of how I am trying to print out the response data.

Update with response

enter image description here

Update with new response

failed

Object { details: "{\"SearchResults\":[{\"SearchItem\":\"****\",\"DisplayType\":0,\"Shipment\":{\"DRAvail\":false,\"ProNumber\":\"****\",\"PickupNumber\":\"Not Found\",\"CustomerNumber\":\"****\",\"BillToAccount\":\"****\",\"BillToNumber\":null,\"BOLNumber\":\"\",\"BOLReceived\":true,\"PODReceived\":false,\"PONumber\":\"SEE BELOW\",\"OrderNumber\":null,\"OperationalStatus\":null,\"Status\":null,\"InspectionAvailable\":false,\"ProDateTime\":\"2018-02-13T00:00:00\",\"DeliverDateTime\":\"0001-01-01T00:00:00\",\"SpecInst1\":\"RESIDENTIAL DELY CFA 1\",\"SpecInst2\":\"LIFTGATE DELY REQUIRED\",\"SpecInst3\":\"ANY ??'S CALL:CUST SERV\",\"TotalAmount\":\"145.38\",\"Scac\":\"COEP\",\"ReadyTimeString\":\"\",\"Pieces\":1,\"Weight\":381,\"ApptDateTime\":\"0001-01-01T00:00:00\",\"DeliveredDateTime\":\"0001-01-01T00:00:00\",\"ProjectedDeliveryDateTime\":\"2018-02-19T00:00:00\",\"HAWB\":null,\"Origin\":{\"Name\":\"ATLAS INTL\",\"Address1\":\"400 W WARNER AVE\",\"Address2\":\"\",\"City\":\"SANTA ANA\",\"State\":\"CA\",\"PostalCode\":\"92707\"},\"Consignee\":{\"Name\":\"LEANNE FRANKE\",\"Address1\":\"783 HUNTINGTON DR\",\"Address2\":\"\",\"City\":\"HIGHLANDS RANCHO\",\"State\":\"CO\",\"PostalCode\":\"80126\"},\"PickupStop\":null,\"OriginTerminal\":{\"TerminalName\":\"Commerce\"],\"AuthUser\":{\"CanViewBOL\":false,\"CanViewInvoice\":false,\"CanViewInspection\":false,\"CanViewPOD\":true,\"CanViewWI\":false,\"FBAUserID\":\"\",\"SharedSecret\":\"\",\"UserAuthenticated\":false,\"WebUser\":{\"Site\":null},\"AccountGroup\":{\"GroupCode\":null,\"MasterAccountCollection\":null},\"PermissionMask\":0,\"ManualAccount\":false}}" }

Update

enter image description here


Solution

  • Your ajax is success, because it return json instead ajax error response, but your syntax is not correct.

     success: function(data) {
    $('#carrierReturnData').html(Shipment.Origin.Name);
    },
    

    Shipment is undefined.

    What you need is to get the return of success callback, which is data.

    This means data == your JSON in the screenshot

     success: function(data) {
    $('#carrierReturnData').html(data['SearchResults'][0]['Shipment']['Origin']['Name']);
    },
    

    UPDATE:

    Your data is cross domain, you need working with jsonp instead json. But because you need to know where the callback first (need waiting site owners answer), so instead force doing ajax cross domain. I really prefer this way.

    index.html

    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
     $(function() {
             $.ajax({
                type:'POST',
                url: 'http://localhost/process.php',
                data: {num: $('input[name=proNumber]').val()},
                dataType: 'json',
                success: function(data) {
                    if(data.SearchResults != undefined) console.log('success');
                    else console.log('failed');
                    console.log(data);
                },
                error: function(data) {
                    console.log('error');
                    console.log(data);
                }
            });
        });
    
    </script>
    

    process.php

    <?php
    $json = file_get_contents('https://webservices.rrts.com/TrackWebApi/api/values/'.$_POST['num']); //or you can use curl
    echo $json;
    ?>
    

    UPDATE 2:

    I copy your json to json hosting service.

    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <div id="carrierReturnData" ></div>
    <script>
    $(function(){
    	$.ajax({
    		url: 'https://api.jsonbin.io/b/5a8ede2aa671850974694f16/2',
    		type: 'GET', 
    		dataType: 'json',
    		success: function(data) {
    			/*
    				result: 
    ignore this->	AuthUser: Object { ManualAccount: false, PermissionMask: 0, UserAuthenticated: false, … }
    your JSON->	details: Array [ {…} ]
    ignore this->	__proto__: Object { … }
    
    So we need to do below
    			*/
    			if(data.details.SearchResults != undefined) {
    				console.log('success');
    				console.log(data.details.SearchResults[0].Shipment.Origin.Name); //result: ATLAS INTL
    				$('#carrierReturnData').html(data.details.SearchResults[0].Shipment.Origin.Name);
    			}else{
    				console.log('failed');
    				console.log(data);
    			}
    			
    		},
    		error: function(data) {
    			console.log('error');
    			console.log(data);
    		}
    	});
    	
    })
    </script>

    jsonbin.io is enabled CORS, but your target website is not allow CORS, so we need to hack this using PHP (curl or file_get_contents), which I mentioned above.