up vote 1 down vote favorite
share [fb]

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.

link|improve this question

What does your returning array look like? – alex Mar 24 '11 at 1:02
Can you print the length of the data array on the server and also on the client ? – allthenutsandbolts Mar 24 '11 at 1:03
what is your POST ? what exactly script is returned ? – bensiu Mar 24 '11 at 1:04
feedback

1 Answer

up vote 2 down vote accepted

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.

link|improve this answer
If that's the issue, it's better to do this in PHP and set the Content-Type header to JSON – cwolves Mar 24 '11 at 1:04
@cwolves I hope you mean application/json. I also prefer to explicitly state the return type. – alex Mar 24 '11 at 1:12
yeah, brain fart :) – cwolves Mar 24 '11 at 1:13
setting the dataType worked perfectly :). one more problem - one of the fields is a textarea and this doesn't seem to be passing linebreaks "\n" – scarhand Mar 24 '11 at 1:44
@scarhand You may better off asking a new question with that :) Worked for me with a string. – alex Mar 24 '11 at 1:49
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.