Sanjay
Sanjay

Reputation: 53

Why page is getting loaded even I use ajax?

def tracker(request):
    if request.method == "POST":
        orderId = request.POST.get('orderId','')
        email = request.POST.get('email','')

        try:
            order = Orders.objects.filter(order_id=orderId, email=email)
            if len(order) > 0:
                update = Updateorder.objects.filter(order_id=orderId)
                updates = []
                for item in update:
                    updates.append({'text':item.update_desc, 'time':item.time_stamp})
                    response = json.dumps(updates, default=str)
                    return HttpResponse(response)
                else:
                    print(len(order))
                    return HttpResponse(f"{len(order)}")
        except Exception as e:
            return HttpResponse(f'exception {e}')
    return render(request,'shop/Tracker.html')
{% extends 'shop/base.html' %} {% block title %}MAC Tracker {% endblock %} {% block body %}


<div class="container">
  <div class="col-md-8 offset-md-2 my-4">
    <h3>Step 1 - Enter your Email address and tracker ID to track your order</h3>

    <form method="post" id="trackerForm" action="#">{% csrf_token %}

      <div class="form-row">
        <div class="form-group col-md-6">
          <label for="name">Tracker ID</label>
          <input type="text" class="form-control" id="orderId" name="orderId" placeholder="Enter tracker ID">
        </div>

        <div class="form-group col-md-6">
          <label for="email">Email</label>
          <input type="email" class="form-control" id="email" name="email" placeholder="Enter Email">
        </div>

      </div>
      <button type="submit" class="btn btn-primary">Track Order</button>
    </form>
  </div>


  <div class="col-md-8 offset-md-2 my-5">
    <h3>Your order status</h3>
    <ul class="list-group" id="items">
      <b>Enter your order Id and Email and click Track Order to find details about your order!</b>
    </ul>

  </div>
</div>

{% endblock %} {% block js %}

<script>
  $('#trackerForm').submit(function(event) {
    $('#items').empty();
    var formData = {
      'orderId': $('input[name=orderId]').val(),
      'email': $('input[name=email]').val(),
      'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
    };
    $.ajax({
        type: 'POST',
        url: '/shop/tracker/',
        data: formData,
        encode: true
      })
      .done(function(data) {
        console.log(data);
        updates = JSON.parse(data);
        if (updates.length > 0 & updates != {}) {
          for (i = 0; i < updates.length; i++) {
            let text = updates[i]['text'];
            let time = updates[i]['time'];
            mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
                    ${text}
                    <span class="badge badge-primary badge-pill">${time}</span>
                </li>`
            $('#items').append(mystr);
          }
        } else {
          mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
                    Sorry, We are not able to fetch this order id and email. Make sure to type correct order Id and email</li>`
          $('#items').append(mystr);
        }
      });
    event.preventDefault();
  });
</script>

{% endblock %}

I am using ajax to submit the form when I try to submit the form it is showing the error jquery-3.4.1.js:9837 POST http://127.0.0.1:8000/shop/tracker/ 404 (Not Found).

I have added event.preventDefault(); still it is not working

$.ajax({ type: 'POST', url: '/shop/tracker/', data: formData, encode: true }) .done(function(data) { console.log(data) updates = JSON.parse(data); if (updates.length > 0 & updates != {}) { for (i = 0; i < updates.length; i++) { let text = updates[i]['text']; let time = updates[i]['time']; mystr = <li class="list-group-item d-flex justify-content-between align-items-center"> ${text} <span class="badge badge-primary badge-pill">${time}</span> </li> $('#items').append(mystr);

I am expecting the html output in the same page but there is no changes occurring.for reference views.py and html page has shown in above sections.

Upvotes: 0

Views: 192

Answers (1)

Sanjay
Sanjay

Reputation: 53

thank you stefan and henrik for your comments I just corrected the url and the page is working properly. The corrected url : '/shop/tracker' earlier it was '/shop/tracker/' one extra slash at the end causing the problem.

Upvotes: 1

Related Questions