2

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?

2 Answers 2

6

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.

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

1 Comment

Do you mean .empty instead of .clean?
1

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);

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.