scarhand
scarhand

Reputation: 4337

jquery use json_encoded array from AJAX

I'm just trying to spit the elements of an array into seperate input fields on a form via jquery's AJAX.

Heres my javascript code:

        $('#based').change(function() { 
        if ($(this).val().length > 0)
        {           
            $.ajax({
                type: "POST",
                url: "ajax.php",
                data: "id="+$(this).val(),
                success: function(data){
                    if (data != 'error')
                    {                       
                        $('#keyword').val(data[2]);
                        $('#keyword_slug').val(data[3]);
                    }
                }
            });
        }
    });

Heres my PHP code for 'ajax.php':

$sql = mysql_query("select * from `keywords` where `id`='".mysql_real_escape_string($_POST['id'])."'");

if (mysql_num_rows($sql) == 0)
{
    echo 'error';
}
else
{
    while ($row = mysql_fetch_assoc($sql))
    {
        foreach ($row as $k => $v)
            $data[] = $v;
    }

    echo json_encode($data);
}

Its not working. What do I do here? I've looked into serializeArray but can't get anything to work properly.

Upvotes: 1

Views: 444

Answers (1)

alex
alex

Reputation: 490617

I think you need dataType: 'json' if you are expecting JSON back.

Otherwise jQuery has to guess, and if you are not sending the Content Type application/json, it may guess wrong.

Upvotes: 2

Related Questions