0

I've got the following code :

$.post("docsel.php", {id : id}, function(data) {
   $('input#titre').val(data.titre);
   $('input#content').val(data.content);
});

docsel.php returns a JSON encoded array with titre and content and their values. I checked that returned data is correct.

Now I'd like to modify input fields with results, but my code doesn't work. What am I doing wrong?

EDIT:

Here is the data (i put auteur and not content to simplify) :

"[{"titre":"Dipt\u00e9rosodomanie et t\u00e9trapilotomie radiaire, pourquoi ?","auteur":"Alex"}]"

I modified my code like this :

$.post("docsel.php", {id : id}, showResult(data));
                });
            });

function showResult(data)

{
  var obj = JSON.parse(data);

  var titre = obj.titre[0];

$('#titre').val(titre);

but it doesn't work, I mean input field "titre" is not modified. Please take into account that I am an absolute beginner in JQuery / Php .

3
  • Not an answer, but you don't need to select the input, because id is always unique: $('#titre'). Or are you saying it isn't unique? Commented Feb 20, 2012 at 17:15
  • What do you mean by "doesn't work"? That doesn't help us at all. Commented Feb 20, 2012 at 17:18
  • Did you edit Mick Hansen's answer with your code? Don't do that. Add it to the question. Commented Feb 20, 2012 at 21:12

2 Answers 2

2
$.post("docsel.php", {id : id}, function(data) {
   $('input#titre').val(data.titre);
   $('input#content').val(data.content);
}, "json");

I believe you do need to specify when you want the returned data to be parsed as JSON. You could test the data returned via console.log(data) if it outputs a string and not an object, it hasn't been parsed.

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

1 Comment

+1, this is (probably) the issue, I've done this myself way too many times.
0
$.post("docsel.php", {id : id}, showResult(data));

This runs the showResult function, and then uses its return value (undefined) as the callback.

It should be:

$.post("docsel.php", {id : id}, function(data){
  showResult(data)
});

Or, better yet:

$.post("docsel.php", {id : id}, showResult);

You don't need to use JSON.parse yourself. Just pass 'json' to $.post and it'll do that for you.

$.post("docsel.php", {id : id}, showResult, 'json');

function showResult(data){
    var titre = data[0].titre; // Data is an array of objects
    $('#titre').val(titre);
}

1 Comment

It works ! For some unknown reason, the syntax : ` $('#titre').val(titre); ` doesn't work for me. I tried $('[name=titre]').val(titre); and my problem was solved. Thank you very much for your help.

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.