tags:

views:

38

answers:

1

Hi All,

Im having a bit of trouble getting my JSON to be recognised by my web page. I have validated JSON that im getting returned from server, so i know that is correct, however my javascript function is not doing anything with it. My succes function is as follows:

success: function(data) {
  $('input[name=customer_name]').val(data.name);
  $('textarea[name=customer_address]').text(data.address);
  $('input[name=customer_email]').val(data.email);
  $('input[name=customer_tel]').val(data.tel);
  $('input[name=user_id]').val(item.id);
}

Yet the fields are not being repopulated with the data that is returned, if it helps, a sample of my JSON data:

{
    "name": "Terry O'Toole",
    "address": "Terrys House\nTerry Street\nTerrysville\nTerrytown\nTT1 6TT",
    "email": "[email protected]",
    "tel": "05110000000"
}

Any help would be appreciated.

[EDIT]

Expanded ajax call:

$.ajax({
  url: "<?php echo site_url('user/users/ajax'); ?>",
  type: 'POST',
  data: {"userid": item.id},
  success: function(data) {
    $('input[name=customer_name]').val(data.name);
    $('textarea[name=customer_address]').text(data.address);
    $('input[name=customer_email]').val(data.email);
    $('input[name=customer_tel]').val(data.tel);
    $('input[name=user_id]').val(item.id);
  }
 })
});
+6  A: 

I take it you're using jQuery (from the val function you're using). Are you specifying the dataType parameter to $.ajax? E.g.:

$.ajax({
    url: "blah",
    dataType: "json",
    success: ...
});

If not, it may not be guessing correctly (perhaps you're not sending back the right content type?) and you'll have to use JSON.parse on it. But best to A) Set the correct content type on the response, and B) use dataType to express your intent in the code.

Edit Just saw your edit. Definitely try adding dataType.

T.J. Crowder
Ha got it. Adding the datatype worked a treat. Thanks for the help
richzilla
@richzila: If this answer worked for you, tick it as accepted.
Matt Ellen
@richzila: No worries, glad that was it.
T.J. Crowder