DGDD
DGDD

Reputation: 1390

Jquery response load

A jQuery function receives a string from a database using GET, after that I would like to inject that string into HTML in place of a div. Pretty standard stuff so it seems. However I am not quite managing it.

Here is what I have going on:

  <h1>Whatever</h1>
  <div id="replace_me">

  </div>
  <a id="click_me" href="#">Click Me</a>

<script>
//AJAX
var brand_id = 8
var dataX = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$(function(){
  $("#click_me").click(function(){  
    $.ajax({
      type: 'GET',
      url: '/ajax_request/',
      data: dataX,
      datatype: "json",

      success: function(data) {
          alert(data);
          $("#replace_me").load(data);
      },
      error: function() {
          alert("Nope...");
      }
  });
  });
});
</script>

When the alert is set off I receive my string which shows everything is working fine, but how can I input that string I just received into the div "replace_me" without having to load from another url?

Upvotes: 2

Views: 106

Answers (2)

Alex Pakka
Alex Pakka

Reputation: 9706

You have an error in your success function. Check documentation on jQuery load(). Instead, you should do

  success: function(data) {
      //alert(data);
      $("#replace_me").html(data);
  },

or, slightly better style

  success: function(data) {
      //alert(data);
      $("#replace_me").empty().append($(data));
  },

Also note, that you specified "json" in your datatype option. As a consequence, if your server responds in proper JSON, your data will be a JavaScript object, as jQuery will parse the JSON format for you. If you really want to see the object, you will need to use, e.g. JSON.stringify():

 $("#replace_me").empty().append($(JSON.stringify(data)));

If your server does not produce valid JSON, your success method will not be called in most cases.

Upvotes: 6

Zak
Zak

Reputation: 25237

load() is a convenience method to do the two steps of calling the ajax url, then putting the data into the element all in a single function. Instead of calling .ajax(), just call .load()

i.e.

var brand_id = 8
var data = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$("#replace_me").load('/ajax_request/', data);

Upvotes: 1

Related Questions