-1

OK so i have this script that submits the input of a search box to a .php and gives back a JSON object in jquery. How can i now change the content of a div. The JSON object that is returnd looks like this:

{"0":"Aardappelen rauw","voedsel":"Aardappelen rauw","1":"88","calorien":"88"}

How can i say that 'Aardappelen rauw' should be in div1 and 88 in div 2 for example? I tried with data.voedsel and data.calorien but that doesn't work..

in head:

<script type="text/javascript">
function contentDisp()
{

$.ajax({
  type: 'POST',
  url: 'getFood.php',
  data: {'foodnametextbox' : $('#food').val() },
  datatype: "json",
  success: function(data){ 

    $('.second').replaceWith(data);

  }
});


}
</script>

in body:

<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>
1
  • OK problem solved! But now another problem: when I perform the search and update the div it only does it once.. if i change my query and press the button again the DIV change doesn't work anymore, why is this? Commented Jan 14, 2011 at 15:56

3 Answers 3

2

The dataType: 'json' should automatically call parseJSON. Then you should be able to do data['0'] (or data.voedsel) to get 'Aardappelen rauw'.

EDIT: Change datatype: "json" to dataType: "json". The 't' in 'type' needs to be capital.

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

3 Comments

@Javaaaa: You're welcome. It's sometimes hard to spot these stupid little errors.
oeps wrong edit: But now another problem: when I perform the search and update the div it only does it once.. if i change my query and press the button again the DIV change doesn't work anymore, why is this?
@Javaaaa: Try changing $('.second').replaceWith() to $('.second').html(). replaceWith changes the ENTIRE element, html just changes the data IN the element.
1

You can use .parseJSON() http://api.jquery.com/jQuery.parseJSON/

2 Comments

No. Change datatype: 'json' to dataType: 'json'.
ah yes, thats the mistake, thanks, no need for.parsoJSON() indeed now!
1

replaceWith takes a HTML string, DOM element, or jQuery object. A JSON data object is neither of those. My guess is you want something like this:

$('.second').text(data["0"]);

EDIT: Don't use eval. Your ajax option is wrong. It needs to be dataType: 'json'. Note the capital T.

Comments

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.