click here
click here

Reputation: 836

Using jquery variable to get specific ajax request

As of right now the current code renders Job.objects.all() in a js alert as to be expected. But I want to be able to pass var jobnum into my view and filter Job.objects.all based off this. In the json there are jobnum key's and their values. I want to be able to pull all the data associated with the jobnum into the ajax request.

I've tried doing something like a = Job.objects.GET(jobnum=jobnum) and a = Job.objects.GET(jobnum=request) and many other things that I can't recall. The closest I've gotten is what I've shown below:

My view:

def api(request):
  a = Job.objects.all()
  data = serializers.serialize('json', a)
  data = json.loads(data)
  if request.is_ajax():  
    return HttpResponse(data)
  else:
    data = serializers.serialize('json', a)
    return HttpResponse(data)

My jquery:

$('.test').click(function(){
    var jobnum = $(this).data('jobnum');
    console.log(jobnum)
    $.ajax({
        url: "api",
        type: 'get', //this is the default though, you don't actually need to always mention it
        data: {'jobnum':jobnum},
        success: function(data) {
            alert(data);
        },
        failure: function(data) { 
            alert('Got an error dude');
        }
    });     
});

Upvotes: 1

Views: 520

Answers (1)

Dhia
Dhia

Reputation: 10619

To get all the jobs based in the jobnum you have to user .filter, because .get return only one object

so in you code add

jobnum = request.GET.get('jobnum')
job_list = Job.objects.filter(jobnum=jobnum)

to serialize your data you just need to do as follow:

job_json = job_list.values()

so your view will look like this :

def api(request):
  jobnum = request.GET.get('jobnum')
  job_list = Job.objects.filter(jobnum=jobnum)
  json_data = job_list.values()
  return HttpResponse(json_data)

Upvotes: 1

Related Questions