Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 433
  • Last Modified:

JQuery-AJAX- Basic help

Trying to convert ajax calls over to Jquery.  Right now just in experiment mode for learning reasons.


Wanted I'm trying to do is transform the code below to accept returned JSON data and iterate through it (just alert functionality for now).  The click function belongs to an image.  The PHP page returns JSON data.

Or is there a better way in jquery for ajax calls that return JSON data?


                  $('#ok').click(function() {

                              $.ajax({
                                      type: "get",
                                      url: "agents_lookup.php",
                                      data: "term=a",
                                      success: function(msg){
                                          alert(msg );
                                      }
                                    });
                  
                  
                  });
0
carsRST
Asked:
carsRST
3 Solutions
 
Gurvinder Pal SinghCommented:
0
 
leakim971PluritechnicianCommented:
You may use this shortcut : http://api.jquery.com/jQuery.getJSON/

$('#ok').click(function() {
           $.getJSON(
                 "agents_lookup.php",
                 {"term":"a"},
                  function(msg){
                      alert(msg ); // if agents_lookup.php return a JSON object you will alert an [object Object] here, if it return a JSON string your will see it
                  }
           );
});
0
 
hieloCommented:
>>I'm trying to do is transform the code below to accept returned JSON data and iterate through it
Then just add the 'dataType':'json' to your options and internally jquery will convert the result into a javascript obect. Then you can iterate through it using "for - in":

$('#ok').click(function() {
     $.ajax({
          type: "get",
          url: "agents_lookup.php",
          data: "term=a",
          dataType:'json',
          success: function(msg){
               //alert(msg );
               for( var k in msg ){
                    alert( k + "=" + msg[k] );
               }
          }
     });
});

Open in new window

0
 
carsRSTAuthor Commented:
You guys are great.  

Thanks for the help!
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now