1

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.

3
  • What does your returning array look like? Commented Mar 24, 2011 at 1:02
  • Can you print the length of the data array on the server and also on the client ? Commented Mar 24, 2011 at 1:03
  • what is your POST ? what exactly script is returned ? Commented Mar 24, 2011 at 1:04

1 Answer 1

2

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.

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

4 Comments

If that's the issue, it's better to do this in PHP and set the Content-Type header to JSON
@cwolves I hope you mean application/json. I also prefer to explicitly state the return type.
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 You may better off asking a new question with that :) Worked for me with a string.

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.