Natedog
Natedog

Reputation: 53

accessing data from JSON using jQuery

Need help on code to provide iteration of this JSON response:

JSON Response:

[{"id":"1","FK_country":"USA","FK_state":"Arizona","FK_city":"Phoenix","zip":"85001","update_by":"SYSTEM","update_when":"0000-00-00 00:00:00"},
{"id":"2","FK_country":"USA","FK_state":"Arizona","FK_city":"Phoenix","zip":"85002","update_by":"SYSTEM","update_when":"0000-00-00 00:00:00"},
{"id":"3","FK_country":"USA","FK_state":"Arizona","FK_city":"Phoenix","zip":"85003","update_by":"SYSTEM","update_when":"0000-00-00 00:00:00"}]

The code I have UPDATED with assistance from suggestions below is

function test3 () 
{

    var myCriteria = "";

    var key = "mykey";

    myCriteria = $( "#city" ).val();

    $('#myTestDiv').empty().append(myCriteria);

    var myDataRequest = $.ajax({
                url: 'ajx_zip.php',
                type: 'POST',
                dataType: 'json',
                data: {city:myCriteria, api_key:key},
                success: function(myData)
                {
                    alert( "Data Request Success!" );

                    $('#zip')
                    .find('option')
                    .remove()
                    .end();

                    $( "#myTestDiv" ).append( "<p>" + myData + "</p>" );

                    var myNewData = $.parseJSON(myData);

                    $( "#myTestDiv" ).append( "<p>" + myNewData + "</p>" );

                    $.each(myNewData, function(i, value) 
                    {
                    $('#zip').append($('<option></option>').val(value.FK_city).html(value.FK_city));
                    });
                }

        });

    myDataRequest.fail(function(jqXHR, textStatus)
    {
    if (jqXHR.status === 0)
    {
        alert('Not connect.n Verify Network.');
    }
    else if (jqXHR.status == 404)
    {
        alert('Requested page not found. [404]');
    }
    else if (jqXHR.status == 500)
    {
        alert('Internal Server Error [500].');
    }
    else if (exception === 'parsererror')
    {
        alert('Requested JSON parse failed.');
    }
    else if (exception === 'timeout')
    {
        alert('Time out error.');
    }
    else if (exception === 'abort')
    {
        alert('Ajax request aborted.');
    }
    else
    {
        alert('Uncaught Error.n' + jqXHR.responseText);
    }
    });

 }

The HTML code I have UPDATED from suggestions for this is:

<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<script language="javascript" src="select.js"></script>
</head>

<body>

<h3>Test Address for Javascript</h3>

<FORM name="address" action="testresult.php" method="POST" >

<SELECT  ID="country" NAME="country" >
<Option value="">Select Country</option>
<Option value="USA">United States</option>
<Option value="CAN">Canada</option>
</SELECT>

<br><br>

<SELECT id="state" NAME="state">
<Option value="Arizona">Arizona</option>
<Option value="California">California</option>
</SELECT>

<br><br>

<SELECT id="city" NAME="city" onchange="test3();">
<Option value="Phoenix">Phoenix</option>
<Option value="Glendale">Glendale</option>
<Option value="Chandler">Chandler</option>
<Option value="California">California</option>
</SELECT>

<br><br>

<SELECT id="zip" NAME="zip">
<Option value="Select Zip">Select Zip</option>
</SELECT>

</form>

<div id="myTestDiv"></div>
</body>

</html>

In addition, I have created a simple html-form POST test from same server to PHP processing page and I produce now a limited data-set speeding client-side performance created to test the API - all works well in producing expected results as demonstrated at the top of this post (an echo of the 'results' page). However the error now occurs with processing of the JSON object within the Javascript function at the $.parseJSON level. In the test output DIV my appended output is as follows...

Chandler
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Upvotes: 0

Views: 101

Answers (3)

Natedog
Natedog

Reputation: 53

The answer to this question was solved by both @lazel and @dancer and a previous post found here... Ajax success function returning [object, object] ...the JSON response was already parsed as one commentator suggested, but the data returned had already processed as objects within an object.

Solved and working with this updated code.

Hopefully this will help other JQuery newbies. Thank you contributors!

function slct_zip () 
    {

        var myCriteria = "";

        var key = "yourAPIkeyhere";

        myCriteria = $( "#city" ).val();

        var myDataRequest = $.ajax({
                    url: 'yourphpqueryscriptinJSON.php',
                    type: 'POST',
                    dataType: 'json',
                    data: {city:myCriteria, api_key:key},
                    success: function(myData)
                    {
                        alert( "Please Select Zip" );

                        $('#zip')
                        .find('option')
                        .remove()
                        .end();

                        for (var i=0;i<myData.length;i++) 
                            {
                            $( "#zip" ).append($('<option></option>').val(myData[i].zip).html(myData[i].zip));
                            }
                    }

            });

        myDataRequest.fail(function(jqXHR, textStatus)
        {
        if (jqXHR.status === 0)
        {
            alert('Not connect.n Verify Network.');
        }
        else if (jqXHR.status == 404)
        {
            alert('Requested page not found. [404]');
        }
        else if (jqXHR.status == 500)
        {
            alert('Internal Server Error [500].');
        }
        else if (exception === 'parsererror')
        {
            alert('Requested JSON parse failed.');
        }
        else if (exception === 'timeout')
        {
            alert('Time out error.');
        }
        else if (exception === 'abort')
        {
            alert('Ajax request aborted.');
        }
        else
        {
            alert('Uncaught Error.n' + jqXHR.responseText);
        }
        });

     }

Upvotes: 0

Matthew Eskolin
Matthew Eskolin

Reputation: 658

Try adding this to the ajax parameters

$.ajax({
                  datatype: "json",
    });

and try calling this in your success function before the each.

       var newMyData = $.parseJSON(myData);

and then use the new variable.

Upvotes: 0

Iazel
Iazel

Reputation: 2336

Replace this:

<SELECT id="city" NAME="city" onselect="AddZipOptions();">

with this:

<SELECT id="city" NAME="city" onchange="AddZipOptions();">

onSelect is an event fired when you select some text with the mouse!

You should also clean the zip select before appending the results:

$("#zip").children(':not(:first)').remove()
$("#zip").append($('<option>', {text: result.zip, value: result.zip}));

Upvotes: 3

Related Questions