1

I have a php (history.php) that creates a json

$i=1;
 $q=mysql_query("select * from participants where phone='".mysql_real_escape_string($_GET['phone'])."' limit 10");
 while($rs=mysql_fetch_array($q)){
      $response[$i] = $rs['code'];
$i++;   
    }
    print json_encode($response);
    exit;

In js I access this file:

var req=$.get("history.php", { phone: "" + phone + ""},

                        function(data) {
        //data="1":"code1","2":"code2","3":"code3","4":"code4","5":"code5"};
                            var msg = "";
                            for(i=1;i<=5;i++){
                                msg+= "<li>"+data[i];
                            }
                            $(form_message).html(msg);

                        })

After this code is executed my output is

  • "
  • 1
  • "
  • :
  • "
  • which means that 'data' is not passed as an array.. it's passed like a string. But if I uncomment the data var in js everything is ok. The output is:

  • code1
  • code2
  • code3
  • code4
  • code5
  • Can you please tell me what am I doing wrong when passing the data from php.

    Thanks in advance

    1 Answer 1

    2

    As in your case returned content is interpreted as text, not as json, you need to use $.getJSON instead of $.get:

    var req=$.getJSON("history.php", { phone: "" + phone + ""}, function(data) {
        var msg = "";
        for(var i in data){
            msg+= "<li>"+data[i]+"</li>";
        }
        $(form_message).html(msg);
    });
    
    Sign up to request clarification or add additional context in comments.

    3 Comments

    Yes that was it. Thanks very much. Could you also please tell me how to determine the length of data... I've tried data.length but returns undefined:(
    @MihaiStancioiu What do you mean, by 'length'? The amount of keys(e.g. 1,2,3,4,5) in data object?
    @MihaiStancioiu I think,you don't need it...Use for in to interate through all elements of data, instead of for.See my update.

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.