0

PHP

$table = mysql_real_escape_string($_REQUEST['table']);

$query  = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = '$table'";
$result = mysql_query($query);
$arr1 = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $arr1[] = $row['COLUMN_NAME'];
}
echo json_encode($arr1);

}

Javascript/Jquery

$("#verticalSelect").change(function() {
    var table = $("#verticalSelect option:selected").attr('value');

    $.post(PROCESSORFILE, {"task": "getTableDupeFields", "table": table}, function(data) {
        $.each(data, function(key, value){
            $("#test-area").append(key+' is: '+value+'<br/>');
        });
        alert(data);
    });
});

Now with the alert of the returned JSON variable I get the result I expect.

["lead_id", "callcenter", "monkey" ...]

But with the Jquery.each() function I get this:

0:is: [
1:is: "
2:is: l
3:is: e
4:is: a
5:is: d
6:is: _
7:is: i
8:is: d
9:is: "
10:is: ,
11:is: "
12:is: c
13:is: a
14:is: l
15:is: l
16:is: c
17:is: e
18:is: n
19:is: t
20:is: e
21:is: r

Every character of the returned array is looped instead of every discreet value. What is the proper way of handling JSON returned arrays?

1
  • The proper way is to convert the string into native data types ;) Commented Sep 3, 2012 at 22:53

2 Answers 2

3

You either need to set your response header to application/json or specify the dataType in $.post to be 'json'

Sign up to request clarification or add additional context in comments.

4 Comments

Does $.post() detect the Content-Type? That's nice if so :-) I know that $.ajax() doesn't but I guess it would kind-of make sense for the "convenience" version to be convenient.
@Pointy just tried it with $.ajax() and it worked, though I used the latest version of jQuery
I thought $.post() assumes json datatype if not explicitly set. I tried it and it worked. Strange, I thought json was set implicitly.
@Musa hmm ... that's interesting; I'm not on 1.8 yet. I've got a hybrid system with JSON responses and I'm having to parse it myself. I'm not telling $.ajax() that the response type is JSON but I am setting the Content-Type (and I know I'm doing that because that's how my code tells the difference).
1

The result of $.post() won't be parsed for you.

$.post(PROCESSORFILE, {"task": "getTableDupeFields", "table": table}, function(data) {
    data = $.parseJSON(data);
    $.each(data, function(key, value){
        $("#test-area").append(key+' is: '+value+'<br/>');
    });
    alert(data);
});

edit — oh and you can also pass a fourth parameter to $.post() but I'm not personally certain that passing "json" tells it to parse the result; it probably does.

Comments

Your Answer

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