Carl Brubaker
Carl Brubaker

Reputation: 1655

jQuery script doesn't work when moved into a file with plain javascript

I have functioning javascript and jQuery files. I tried copying the jQuery AJAX into my other file, but It doesn't work. Instead of AJAXing, it shows me the JSON info returned without the the template it was in. ?

View

def customer_profile(request, pk):
    name = get_object_or_404(CEName, id=pk)
    name_form = NameForm(instance=name)
    return render(
        request,
        'customer/customer_profile.html',
        {'name':name, 'NameForm': name_form}
    )


def update_profile(request, pk):
    if request.POST:
        name = get_object_or_404(CEName, id=pk)
        name_form = NameForm(data=request.POST, instance=name)
        if name_form.is_valid():
            name_form.save()
            updated_name = get_object_or_404(CEName, id=name.id)
            name_json = render_to_string(
                'ce_profiles/name_json.html',
                {'name_json': updated_name,}
            )
            return JsonResponse({'name_json': name_json})

templates

{% extends 'base.html' %}
{% load static %}

{% block content %}
  {% include 'ce_profiles/name_header.html' %}
  <div id="name" class="container d-flex justify-content-between pt-1">
    <div id="name_json">
      {{ name }}
    </div>
    <button id="update_button" class="bold btn btn-main btn-sm button-main">UPDATE</button>
  </div>
  <div id="div_NameForm" class="container" style="display: none;">
    <hr size="3px">
    <form id="NameForm" method="POST" action="{% url 'customer:update-profile' name.id %}">
      {% csrf_token %}
      {{ NameForm.as_p }}
      <br>
      <button id="save_changes" type="submit" class="btn btn-main button-main btn-block">Save Changes</button>
    </form>
  </div>
{% endblock %}

{% block script %}
  <script src="{% static 'ce_profiles/ce_profiles.js' %}"></script>
  <script src="{% static 'ce_profiles/ce_profiles_jquery.js' %}"></script>
{% endblock %}

<div id="name_json">
  {{ name_json }}
</div>

jQuery

$(document).ready(function() {
  $("#NameForm").submit(function(event) {
    event.preventDefault();
    $.ajax({
      url: $(this).attr('action'),
      type: $(this).attr('method'),
      data: $(this).serialize(),
      dataType: 'json',
      success: function(data) {$("#name_json").html(data.name_json)}
    });
  });
});

javascript

$(document).ready(function() {
  $("#NameForm").submit(function(event) {
    event.preventDefault();
    $.ajax({
      url: $(this).attr('action'),
      type: $(this).attr('method'),
      data: $(this).serialize(),
      dataType: 'json',
      success: function(data) {$("#name_json").html(data.name_json)}
    });
  });
});


let updateButton
let toggleNameForm = function(e) {
  e.stopPropagation();
  let x = document.getElementById("div_NameForm");
  let btn = this;
  if (x.style.display === "none") {
    x.style.display = "block";
    btn.innerHTML = "CANCEL";
    btn.classList.replace("button-main", "button-secondary");
  } else {
    x.style.display = "none";
    btn.innerHTML = "UPDATE";
    btn.classList.replace("button-secondary", "button-main");
  }
};


document.addEventListener('DOMContentLoaded', function () {
  updateButton = document.getElementById('update_button');
  updateButton.addEventListener('click', toggleNameForm);
});

When I delete the script link for ce_profiles_jquery.js and attempt to update the name displayed, all that shows in the browser is: name_json: "<div id\"name_json\">\n The Name\n</div>"

???

Upvotes: 0

Views: 72

Answers (1)

MattRowbum
MattRowbum

Reputation: 2192

Check that the correct javascript file is being referenced in your template by checking the source in your browser.

I ran your code in a test environment and everything works correctly. When I commented out your jQuery code, the form submitted normally and the subsequent page displayed:

{name_json: "<div id=\"name_json\">The Name</div>"}

If you are not receiving any errors in your browser console, your reference to {% static 'ce_profiles/ce_profiles.js' %} is probably a different file without the jQuery code.

Upvotes: 1

Related Questions