Home > other >  django-Ajax Does not work on some button clicks
django-Ajax Does not work on some button clicks

Time:01-10

Iam having a webpage which contains Multiple Buttons Generated using django.Using ajax,When I click a button the is value send to server randomly.The button value is set according to value passed through context from django.Heres's the Code:

<button name="date" type="submit" value={{d}} ">
            

Ajax Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> 
</script>
<script>
     function sendData(event){
     event.preventDefault();
     $.ajax({
     type : "POST", 
     url: "",
     data: {
       date : event.target.value,
        csrfmiddlewaretoken:'{{ csrf_token }}',

     },
     success: function(data){
             
            },
     
            failure: function() {
                
            }

      });
    }
  </script>

When i try to print the request.POST on views.py it sometimes show only csrftoken instead of both date and csrftoken,I have tried giving alert box in the success function and alert always pops up when i click a button even though only csrf token is passed to server Thanks In Advance

CodePudding user response:

You can somthing like this to job done

<button type="submit" onclick="return sendData('{{d}}')">
  <p>{{y}}</p>
  <p >{{d}}</p>
</button>

I've remove some code to look clean you can add it later

function sendData(date){
  $.ajax({
    type : "POST", 
    url: "",
    data: {
      date : date,
      csrfmiddlewaretoken:'{{ csrf_token }}',
    },
    
    success: function(data){
      
    },
    failure: function() {
      
    }
    
  });
  return false
}

I'll suggest not to use id inside loop because it repeates same id multiple time

The id attribute specifies its element's unique identifier (ID). The value must be unique amongst all the IDs in the element's for more info check this

  •  Tags:  
  • Related