使用ajax检测数组

I have a document on PHP retrieving the postal codes via form and it gives back an array. If the postal code is used on more than one citie, it creates a multidimensional array, otherwise it stores everything just in one. I have three scenarios:

  1. If the postal code doesn't exist it gives an array with 2 values "Doesn't exist" and output it on the form.
  2. If the postal code exists it gives you an array with the city and the state and output them on the form.
  3. If the postal code exists and is used on more than one citie it stores every result on an array and all of them into a another array (Array => Array [0] => Array([city]=>city1 [state]=>state1) Array [1] => Array([city]=>city2 [state]=>state2)... and then outputs a popup.

I managed to do everything but I still have some problems. Here's my code:

Script PHP

include_once('../../../connect.html');
//perform lookup
$title = ($_GET['postal_code']);
$statement = $connection->prepare ("SELECT city, state FROM cities, states WHERE cities.state_id = states.state_id AND cities.postal_code = ?");
$statement->execute(array($title));
$statement->setFetchMode(PDO::FETCH_ASSOC);

$items = array();
while ($r = $statement->fetch()) {
    //$arrayName = array($r = $statement->fetch());
    $items[] = $r;
}

if (count($items) == '1'){
    $newArray = $items[0];
    echo $newArray['city'].",".$newArray['state']; 
}elseif (count($items) == '0'){
        echo "Doesn't exist".","."Doesn't exist";
    }else{
        $varios = array($items);
        print_r($varios);
}

AJAX code

var ajax = getHTTPObject();

        function getHTTPObject()
        {
            var xmlhttp;
            if (window.XMLHttpRequest) {
              // code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
            } else if (window.ActiveXObject) {
              // code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            } else {
              //alert("Your browser does not support XMLHTTP!");
            }
            return xmlhttp;
        }

        function updateCityState()
        {
            if (ajax)
            {
                var zipValue = document.getElementById("postal_code").value;
                if(zipValue)
                {
                    var url = "get_cities.php";
                    var param = "?postal_code=" + escape(zipValue);

                    ajax.open("GET", url + param, true);
                    ajax.onreadystatechange = handleAjax;
                    ajax.send(null);
                }
            }
        }

        function handleAjax()
        {
            if (ajax.readyState == 4)
            {
                if( ajax.responseText.length ) {
                    if (ajax.responseText[2]) {
                        centerPopup();
                        loadPopup();
                    }
                    citystatearr = ajax.responseText.split(",");
                    city.value = citystatearr[0];
                    state.value = citystatearr[1];
                }else{
                }
            }
        }

Problems are:

  1. It calls the function centerPopup and loadPopup everytime, regardless the result (it should be called only when the PHP script gives back a multidimensional array.
  2. I don't know how to detect via AJAX when the script is sending the normal array or the multidimensional array.

It's basically those two problems but solving one, the other one is solved.

Any help is appreciated!!

ajax.responseText is a string, in JavaScript string[n] return the nth letter of the string.

You must encode your data in PHP then decode it in JavaScript, the best way to do it is with JSON. Both PHP and JavaScript provide support for JSON (json_encode/json_decode and JSON.stringify/JSON.parse) so it's easier!

So this is the code in JS:

var ajax = getHTTPObject();

        function getHTTPObject()
        {
            var xmlhttp;
            if (window.XMLHttpRequest) {
              // code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
            } else if (window.ActiveXObject) {
              // code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            } else {
              //alert("Your browser does not support XMLHTTP!");
            }
            return xmlhttp;
        }

        function updateCityState()
        {
            if (ajax)
            {
                var zipValue = document.getElementById("postal_code").value;
                if(zipValue)
                {
                    var url = "get_cities.php";
                    var param = "?postal_code=" + escape(zipValue);

                    ajax.open("GET", url + param, true);
                    ajax.onreadystatechange = handleAjax;
                    ajax.send(null);
                }
            }
        }

        function handleAjax()
        {
            if (ajax.readyState == 4)
            {
                if( ajax.responseText.length ) {
                    try {
                        var data = JSON.parse(ajax.responseText); // = $items
                    }
                    catch(e) {
                        //json parse error
                    } 
                    if (data[2]) {
                        centerPopup();
                        loadPopup();
                    }
                    citystatearr = ajax.responseText.split(",");
                    // ^^^^^^ I think you'll need to change this
                    city.value = citystatearr[0];
                    state.value = citystatearr[1];
                }else{
                }
            }
        }

And PHP :

include_once('../../../connect.html');
//perform lookup
$title = ($_GET['postal_code']);
$statement = $connection->prepare ("SELECT city, state FROM cities, states WHERE cities.state_id = states.state_id AND cities.postal_code = ?");
$statement->execute(array($title));
$statement->setFetchMode(PDO::FETCH_ASSOC);

$items = array();
while ($r = $statement->fetch()) {
    //$arrayName = array($r = $statement->fetch());
    $items[] = $r;
}

if (count($items) == '1'){
    $newArray = $items[0];
    echo $newArray['city'].",".$newArray['state']; 
}elseif (count($items) == '0'){
        echo "Doesn't exist".","."Doesn't exist";
    }else{
        $varios = array($items);
        die(json_encode($varios));
}