1

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');
        }
    });     
});
Serjik
  • 10,543
  • 8
  • 61
  • 70
click here
  • 814
  • 2
  • 10
  • 24

1 Answers1

1

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)
Dhia
  • 10,119
  • 11
  • 58
  • 69
  • I get the error: `Exception Type: AttributeError` `Exception Value: 'WSGIRequest' object has no attribute 'data'` – click here Dec 16 '15 at 19:33
  • 1
    @clickhere So then use [`jobnum = request.GET.get('jobnum')`](https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpRequest). – binki Dec 16 '15 at 19:51
  • @DhiaTN note that his jQuery.ajax() is specifying `{type: 'get'}`. – binki Dec 16 '15 at 19:53
  • @DhiaTN but he is and `request.GET` works for him ;-) – binki Dec 16 '15 at 20:08
  • See [here](http://stackoverflow.com/a/2428119/429091) for how to set the `Content-Type` HTTP header correctly. – binki Dec 16 '15 at 22:11