0

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]
Natedog
  • 51
  • 1
  • 9

3 Answers3

3

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}));
Iazel
  • 2,296
  • 19
  • 23
  • give us some other insight :) Some error? No match for the results? No results? – Iazel Oct 18 '14 at 22:05
  • Sorry no results - will check output of myData – Natedog Oct 18 '14 at 22:07
  • Is your site in the same domain of the request? – Iazel Oct 18 '14 at 22:22
  • Yes same domain - and was able to remove the '.each' block and display the AJAX rendered JSON data in a HTML DIV call from function (myData) - however cannot iterate. - Will try Dancer's suggestion - but also wondering if we need to truncate another function - as this example...http://stackoverflow.com/questions/733314/jquery-loop-over-json-result-from-ajax-success – Natedog Oct 19 '14 at 04:36
  • You should also call `header('content-type: text/json');` on the server that generate the list, or parse the text to json on the client side, as @Dancer321 suggested – Iazel Oct 19 '14 at 14:41
0

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.

Matthew Eskolin
  • 558
  • 1
  • 5
  • 20
0

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);
        }
        });

     }
Community
  • 1
  • 1
Natedog
  • 51
  • 1
  • 9