skip to Main Content

I’m new in using Ajax and javascript. I have an HTML page which will show the shopping status from customers. Like the picture below.
shopping status
I would like to use Ajax and jquery to implement something like when the customer gets more products or put products back, the database will be updated, and the webpage will display immediately without refresh the webpage by using ajax. Also, it will calculate the total price.
And when the new customer comes in or checks out, the new column will be added or removed.

I have google how to use long polling:

test.js

    $(document).ready(function(){
    pollServer();
});

var url='127.0.0.1:8000/test/'
var isActive = true;
function pollServer()
{
    if (isActive)
    {
        window.setTimeout(function () {
            $.ajax({
                url: "http://127.0.0.1:8000/test/",
                type: "POST",
                success: function (result) {
//                    alert('TTTT');
                    pollServer();
                },
                error: function () {
//                     alert("FFFFFFF");
                    pollServer();
                }});
        }, 3000);
    }
}

test.html

    <div class="container custom-container-width" style="text-align=center;" >
  <div class="row gap-buffer"  >
    {% for customer in Customer %}
    <div class="col-sm-3 p-3  gap-buffer colsize " style="background-color:white;box-shadow: 10px 10px 5px grey; "  >
        <div class="profilesize">
            <img src="{{ MEDIA_URL }}/{{customer.uuid}}/{{customer.uuid}}.jpeg" width=192 height=108 >
        </div>
        <br>
          <div>
            <div class="table-responsive" >
               <table >
                  <thead class="thead-dark " >
                    <tr >
                      <th>Product</th>
                      <th>Count</th>
                      <th>Price</th>
                      <th>Subtotal</th>
                    </tr>
                  </thead>
                   <tbody >
                    {% for cart in Cart %}
                     {% if customer.id == cart.customer_id %}
                         {% for good in Good %}
                           {% if cart.id == good.cart_id %}
                          <tr>
                            <td>{{good.name}}</td>
                            <td>{{good.count}}</td>
                            <td>{{good.price}}</td>
                            <td> XXX</td>
                          </tr>
                            {% endif %}
                          {% endfor %}
                    {% endif %}
                   {% endfor %}

                      </tbody>
                    </table>
                <br>
                <P><strong>Total:</strong></P>
            </div>
        </div>
    </div>
    {% endfor %}
  </div>
</div>

views.py

def test(request):
context_dict = {}

customers = Customer.objects.all()
carts = Cart.objects.all().select_related('customer').order_by('customer_id')
goods = Good.objects.select_related('cart__customer').order_by('cart_id')

context_dict['Cart'] = carts
context_dict['Good'] = goods
context_dict['Customer'] = customers

return render(request, 'test.html', context=context_dict)

I don’t know how to combine it without using php. The problem is I don’t know how to get objects in Ajax part.

please give me some advice about how to do it. thanks!!

2

Answers


  1. hi، if you’re not going to refresh the page, I have an idea for you.
    by using ajax you can update your database simply ajax will send data to a defined url, and in the backend you will grab data and do so. but django will force you to return a response. so you will, that response could be anything but it’s very helpful if a json response it be. again in the same ajax function there is already a success function exists and that function will catch the response then update the page content. but another way of doing this is regarding you aren’t going to refresh the page. simply handle any change by javascript just in the client side without waiting for server side response. but still sending data to server side and doing the update. just no need for response from database.

    an example:

    $.ajax({
        url: url,
        type: "POST",
        data: {
              'total_stuff': number
        },
    
       success: function(res) {
              document.getElementById('total_price').html = res['total_price'];
       }
    });
    

    suppose you returned a json response contains the total price key.

    Login or Signup to reply.
  2. Your view returns the html rendered with your object’s values. What you now want is a bit of rendering on the browser’s side. First step, you should create a view that returns the same data but as JSON.

    To do that, you typically return an HttpResponse(data, "application/json") with data being your JSON (for example a dictionnary dumped as JSON with json.dumps)

    Your javascript function would then be able to parse this JSON and build your table. You can for example reuse your ajax call, but typically with a GET request, not POST :

           ...
           $.ajax({
                url: "http://127.0.0.1:8000/your_json_view/",
                type: "POST",
                success: function (result) {
           ...
    

    Then in this function, in the result you have your JSON produced by your Django view so you can loop over the data and add a row for each object.

    As the rendering will now be handled by javascript, your Django template’s tbody will now be empty.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search