Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|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

1 Answer 1

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.

share|improve this answer
    
If that's the issue, it's better to do this in PHP and set the Content-Type header to JSON –  zyklus 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 :) –  zyklus 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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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