tags:

views:

727

answers:

6

I am trying to get the jquery getJSON function to work. The following seems very simple yet it doesn't work.

$("#edit-item-btn").live('click', function() {
    var name = this.id;
    $.getJSON("InfoRetrieve",
       { theName : name },
       function(data) {
       alert(name);
    });
});
+1  A: 

Have you tried using Firebug or Chrome Developer Tools to see what requests are being made?

Does a file called InfoRetrieve exist in the current path of your site? What does it return?

mopoke
I've tried but I can't see any requests being made when I use Firebug, this is one of the main sources of confusion. However the button click is being registered, I previously used an alert to figure that out.
Ankur
Yes InfoRetrieve is a servlet, I won't be using InfoRetrieve once this is working, but for now I just want to get the alert working.
Ankur
+1  A: 

You are using name variable on two places, but this variable is never defined.

Darwin
+2  A: 
  1. Make sure the surrounding code is working with your DOM by replacing the getJSON call with a simple alert
  2. Make sure the "InfoRetrieve" path actually exists. If you replace your file name in the URL bar with InfoRetrieve does it return JSON?
  3. function(data) needs to be closed with a } before you close the click handler.
  4. { theName : theName } makes more sense to me as the data. Are you sure you entered that right?
Michael Greene
Does the servlet have to return a valid JSON message to get the alert to work. I was hoping to sort that out later, once I got the piece of the request in place. Judging from the reading I have been doing it does, so this is what I am working on now.
Ankur
+2  A: 

Shouldn't you be doing alert(data)?

dylanfm
A: 

I'm not convinced your code is correct. Try this and see what happens:

$("#edit-item-btn").live('click', function() {
    var name = this.id;
    $.getJSON("InfoRetrieve",
       { theName : name },
       function(data) {
           alert(data.name);
    });
});

This should work if InfoRetrieve responds with a JSON string like this:

{"name":"Sally Smith"}

A few things to note:

  1. You are sending a request to ./InfoRetrieve in the same directory as the page is located. If you are using a servlet, is that actually correct? Or do you want "/servlet/InfoRequest"?
  2. You are sending data as input to InfoRetrieve with a key of "theName" and a value of whatever is "this.id" is. Does your servlet know how to accept this input?
  3. You are then receiving back a response from InfoRetrieve, and "data" is set to an object that represents the json in the response. You need to then access properties of data to get at values in the response.
Tauren
A: 

Here is an elaborated concept on how jsonp works. Hope this will help you. JSONP First Timer

adnan