Sending an integer through an AJAX request without relying on jQuery:

I am having trouble sending an integer named 'petadid' from my JavaScript to the Django view called 'petadlikeview'. The data doesn't seem to be reaching the view, as when I print 'petadid' in the view it displays as 'None'. Can someone please point out what I am doing wrong? I'm new to working with AJAX and Django.

Below is my JavaScript code:

<script>
$(document).ready(function(argument) {
$.ajaxSetup({cache:false});
var element = document.getElementById("likes");
var petadid = $(this).attr("data-petadid");
element.addEventListener("click",function(){
  var req = new XMLHttpRequest();
  req.open("POST",'/petadlike/')
  req.onload = function(){
    console.log(req.responseText);
    console.log(petadid);
    var data = JSON.parse(req.responseText);
  }
  req.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
  var data = {
    'petadid':petadid,
  }
  req.send(data);
});
});
</script>

And here is my Django view code:

def petadlikeview(request):
print("vau")
if request.method=="POST":
    print("vai")
    petadid = request.POST.get('petadid')
    print(petadid)
    petad = PetAd.objects.get(pk=petadid)
    like_count = petad.petadlikes_set.all().count()
    like, created = petadlikes.objects.get_or_create(user=request.user,petad=petad)
    print(created)
    if created is False:
        petadlikes.objects.get(user=request.user,petad=petad).delete()
        like_count -= 1
        liked = False
    else:
        like.save()
        like_count += 1
        liked = True
    dict = {'like_count':like_count}
    return JsonResponse(dict)
    return HttpResponse(str(like_count)+' people have liked this')
else:
    return HttpResponse('Bad Request')

Answer №1

When using XMLHttpRequest, it does not automatically convert an object into POST data like jQuery does. You have to manually create the URL-encoded string yourself.

var data = "petadid=" + encodeURIComponent(petadid);

In addition,

var petadid = $(this).attr("data-petadid");

it is recommended to use

var petadid = $(element).attr("data-petadid");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a problem with the string comparison in my JavaScript code?

I am dealing with various XML files specific to different operating systems. Here is an excerpt from the SunOS XML: <osname>SunOS </osname> This data is extracted using jQuery: var osname = $(this).find('osname').text(); However ...

Issue Detected: The function this.route.params.flatMap is not recognized

Seeking guidance on transitioning to id, or a similar concept that's hard to articulate. Upon clicking a button to navigate to a specific user, encountering the following error: ERROR TypeError: this.route.params.flatMap is not a function at UserSho ...

What is the most efficient way to align a localStorage variable with its corresponding page?

In my current project, I have developed a component that is utilized in an online science lab setting. To ensure continuity for researchers who navigate away from the page and return later, I have integrated the use of localStorage. The goal is to preserv ...

Analyzing Varied Date Formats

I'm looking to create a function in AngularJS that checks if a given date is after today: $scope.isAfterToday= function(inputDate){ if(inputDate > Date.now().toString()){ return true; } else { return false; } } The iss ...

Error in Python Django when using the Post method: MultiValueDictKeyError

When a user chooses a color in a form, I should receive the value, but instead I get a MultiValueDictKeyError and I can't figure out why. This is the code in my views: def primeira_pergunta(request): trans = Tranfer() my_list = trans.shared[ ...

Trigger an event, pause, and subsequently trigger another one within Vue

I have successfully emitted the following events to the parent component: this.$emit('sendToParent1', true); this.$emit('sendToParent2'); this.$emit('sendToParent3'); this.$emit('sendToParent4', true); this.$emit(&ap ...

Service in Angular2+ that broadcasts notifications to multiple components and aggregates results for evaluation

My objective is to develop a service that, when invoked, triggers an event and waits for subscribers to return data. Once all subscribers have responded to the event, the component that initiated the service call can proceed with their feedback. I explore ...

Transforming an Axios image stream into a string by encoding it with Base64?

Currently, this is what I have in place: const Fs = require('fs') const Path = require('path') const Axios = require('axios') var {Base64Encode} = require('base64-stream'); const url = 'https://unsplash.co ...

Unable to Render Data URI onto HTML5 Canvas

I have been attempting for quite some time and feeling frustrated. I am facing issues with my Data URI image not being able to write to my canvas for reasons unknown .... Here's the code snippet ... function addImage() { var allfiles = $("#postAtta ...

Running Bootstrap-select alongside Bootstrap 5 without encountering any errors

Currently working on a project with Bootstrap 5 (template-based) and encountered an issue while trying to add bootstrap-select (version 1.13.14) to the mix. The console is throwing these errors: Uncaught TypeError: Cannot read properties of undefined (rea ...

Chess.js TypeScript declaration file for easy implementation

Currently, I am delving into learning typescript and have taken up the challenge of crafting a declaration file for the chess.js library. However, it seems that I am struggling to grasp the concept of creating one. Whenever I attempt to import the library ...

Does embedding an Iframe for external files from your server enhance the loading speed of the current page compared to directly loading it on the page?

I'm facing an issue with the loading time of a Facebook post on my webpage index.php. The current method of using the embedded post provided by Facebook is taking too long to load. My solution is to create a separate page, post.php, where only the Fac ...

Exception encountered: The 'IntegerField' object does not possess the attribute 'max_length'

I have not set any restrictions on the IntegerField regarding max_length, so I am unsure about the issue at hand. Below is the code snippet from models.py. Can you please advise on what additional information I should provide to gain a better understanding ...

The function is malfunctioning following the alert

I am experiencing an issue with my renumbering list function. I have a delete button on the list that triggers a confirmation alert, but after the alert is shown, the renumbering function stops working. Here is my script: <script type="text/javascript ...

Best practices for timeout in HTTP long polling

As an avid user of Javascript AJAX and long-polling, I am constantly seeking the best value for server response timeout. Despite scouring numerous documents, a detailed explanation for timeout continues to elude me. Some suggest 20 seconds, while others ...

Retrieve the data entered in the submit button field

My question concerns a form with two buttons: <form method="post" action=""> <button type="submit" name="age" value="20">Age 20</button> <button type="submit" name="age" value="30">Age 30</button> </form> When ...

Solving Problems with Inline Tables using Angular, Express, and Mongoose's PUT Method

For the past few days, I've been struggling to figure out why my PUT request in my angular/node train schedule application isn't functioning properly. Everything else - GET, POST, DELETE - is working fine, and I can successfully update using Post ...

The sequence of divs in a language that reads from right to left

Is there a way in HTML to designate a set of divs so that they automatically align from left to right for languages that read left to right, and alternatively, flow from right to left for languages that read right to left? This means that the direction of ...

Struggling to reveal concealed items on a webpage using jQuery and attempting to cycle through an array without success

Looking to display or hide certain sections on a page based on specific conditions. I want to only show the sections of the page that contain words from the conditionsToShow array. function hideWorkflowConditions() { // initially hide the elements ...

Preventing the mysql server called by php from running when the website is refreshed

My local website runs by querying a mysql database using inputs from an html form. The form values are passed to php via jQuery to execute the query. Is there a way to send a command to the mysql server to terminate the query if the web page is refreshed? ...