开发者

array from php to js with ajax

i have this code on the server side:

<?php
header('Content-Type: text/html; charset=utf-8');
require "../general.variables.php";
require "../functions_validation.php";
require "../functions_general.php";
require "../../db_con.php";

$keyword = mysql_real_escape_string($_POST["keyword"]);

$query = mysql_query("

    SELECT user_id, user_fullname, user_area, user_city, user_quarter, user_tmb
    FROM `migo_users`
    WHERE (
        user_fullname LIKE '%".$keyword."%' AND user_id NOT IN (".$superAdmins2string.")
    )
    ORDER BY tmb_set DESC, user_fname ASC
    LIMIT 7;
");

$i = 0;
while ($userInfo = mysql_fetch_array($query)) {

    $area_name = mysql_fetch_array(mysql_query("

        SELECT area_name
        FROM `migo_areas`
        WHERE
            area_id='".$userInfo['user_area']."';
    "));

    $city_name = mysql_fetch_array(mysql_query("

        SELECT city_name
        FROM `migo_cities`
        WHERE
            city_id='".$userInfo['user_city']."';
    "));

    if ($userInfo['user_quarter'] != 0) {

        $quarter_name = mysql_fetch_array(mysql_query("

            SELECT quarter_name
            FROM `migo_quarters`
            WHERE
                quarter_id='".$userInfo['user_quarter']."';
        "));
    }           
    else {
        $quarter_name['quarter_name'] = "";
    }   

    $rsl[$i]['user_id'] = $userInfo['user_id'];
    $rsl[$i]['user_fullname'] = $userInfo['user_fullname'];

    $rsl[$i]['user_area_name'] = $area_name['area_name'];
    $rsl[$i]['user_city_name'] = $city_name['city_name'];
    $rsl[$i]['user_quarter_name'] = $quarter_name['quarter_name'];

    $rsl[$i]['user_tmb'] = $userInfo['user_tmb'];

    $i++;
}

echo json_encode($rsl);
mysql_close();
?>

and this code on the client side:

        $.ajax({

            type : 'POST',
            url : 'php/general.ajax/header_search.php',

            //async : false,
            //cache : false,
            dataType : 'json',
            data: {
                keyword : sb_keyword
            },
            success : function(data) {

                var hs_hits = 0;

                var hs_row_nr = 1;
                var hs_results = "<div class='sb_spacing'></div><div id='sb_rows_cont'>";                   

                if (data != null) {

                    $.each(data, function(index, arr) {

                        hs_hits++;

                        if (arr['user_quarter_name'] != "") {

                            var quarter_text = "&nbsp;&nbsp;-&nbsp;&nbsp;" + arr['user_quarter_name'];

                        }
                        else {
          开发者_如何学C                  var quarter_text = "";
                        }

                        hs_results = hs_results + "<a class='search_links' href=profile.php?id=" + arr['user_id'] + "><div class='sbr_row' row_nr='" + hs_row_nr + "'><div class='sbr_imgFrame'><img src='images/user_48x48/" + arr['user_tmb'] + "' alt=''></div><div class='sbr_name'>" + arr['user_fullname'].replace(regexp_hs_user_fullname, '<span>$&</span>') + "</div><div class='sbr_area'>" + arr['user_area_name'] + "</div><div class='sbr_area'>" + arr['user_city_name'] + quarter_text + "</div></div></a>";

                        hs_row_nr++;                        

                    });                     

                }

                if (hs_hits > 0) {

                    hs_results = hs_results + "</div><div class='sb_spacing'></div><a class='search_links' href='search.php?name=" + sb_keyword + "'><div id='sbr_botttom'>Se flere resultater for <span class='gay'>" + sb_keyword + "</span></div></a>";

                    $("#sb_results").html(hs_results).show();

                    searchSet = 1;
                    total_rows = hs_hits;

                    $("#sb_rows_cont > a:first .sbr_row").addClass('sbr_row_act');

                    on_a = $("#sb_rows_cont > a:first");
                    first_a = on_a;
                    last_a = $("#sb_rows_cont > a:last");
                    sb_url = $(on_a).attr('href');

                    search_navigator_init();                    

                }
                else {

                    $("#sb_results").hide();
                    searchSet = 0;                      

                }

            },
            error : function() {
                alert("ajax error");
            }
        });

one problem tho, if the query gives 0 results, and the each function tries to run on the client side my js code stops working..

so i was wondering what i could do here.

how can i retrieve the amount of hits from the server side, before i run the each loop?


You're instantiating $rsl in the middle of a loop (implicitly), but you aren't entering the loop unless you have at least one entry.

Instantiate $rsl up above your while loop:

...
$i = 0;
$rsl = array();
while ($userInfo = mysql_fetch_array($query)) {
...

And now when you encode it, it is an empty array instead of null. This will also save your HTTP error_log, and generally be happier. : )


I would try json_encode() your PHP array to allow JavaScript to eval it as a native JS object.

echo json_encode($some_array);

Just a note, json_encode() is only available for PHP versions 5.2 and higher.


$.getJSON('ajax.php',{form data}, functon(data){
     if(data == '') return;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜