0

I would like to ask how could I convert the following $.getJSON() to $.ajax() please.
I have a set of arrays from var googleApi like this:

Array [Object, Object, Object, Object, Object]

// if stringified
[{"id":"0","name":"user1","type":"mf","message":"bonjour user1"},
{"id":"1","name":"user2","type":"ff","message":"hello user2"},
{"id":"2","name":"user3","type":"mm","message":"konnichiwa user3"},
{"id":"3","name":"user4","type":"mf","message":"ni hao user4"},
{"id":"4","name":"user5","type":"ff","message":"high 5! user5"}]}

I would like to ask how could I identify if the value of a declared variable (eg. content with the value of user1) is the same as a value within the list of name keys in the array?

Below is my attempt and you might find my full code in $.getJSON() here:

$.getJSON():

var googleApi = 'https://api.com/url_here';

$.getJSON(googleApi, function(json){

    console.log(JSON.stringify(json));
    var item = json.result.find(function(e){

    return e.name == content;

    }) || json.result[0];           
    console.log("PRINT ID: " + item.id);

    var name = item.name || content;                    
    $('#nameText').text(name);
    console.log("Name: " + name);
});

Below is my attempt on $.ajax() but I got an error of "TypeError: data.result is undefined";
I have also tried using $(this) to replace data.result but without luck... it would be very nice if someone could identify what have I done wrong please:

var googleApi = "https://sheetsu.com/apis/v1.0/f924526c";
var googleKey = "0123456789";
var googleSecret = "987654321";

var data = [];
$.ajax({
    url: googleApi,
    headers: {
    "Authorization": "Basic " + btoa(googleKey + ":" + googleSecret)
    },
    data: JSON.stringify(data),
    dataType: 'json',
    type: 'GET',

    success: function(data) {

        console.log(data);                      

        var item = data.result.find(function(e){

            return e.name == content;

        }) || data.result[0];           
        console.log("PRINT ID: " + item.id);

        var name = item.name || content;                    
        $('#nameText').text(name);
        console.log("Name: " + name);
});

Merci beaucoup :))) x

Karen Chan
  • 164
  • 1
  • 1
  • 16
  • read this to understant more .. http://www.dotnetbull.com/2012/07/jquery-post-vs-get-vs-ajax.html – Kishore Sahasranaman Nov 03 '15 at 15:57
  • `.getJSON()` is just a shorthand for `.ajax()` as explained [here](http://api.jquery.com/jquery.getjson/) – wahwahwah Nov 03 '15 at 15:57
  • 1
    The error indicates your response object `data` does not have a property called `result`, but that your ajax call is working. What does the expected response object look like? – wahwahwah Nov 03 '15 at 16:00
  • What is `console.log(data);` outputting to your console? – jeffdill2 Nov 03 '15 at 16:02
  • @wahwahwah Hello, the response object 'result' is showing an array of all the objects from `var googleApi`. – Karen Chan Nov 03 '15 at 16:05
  • @jeffdill2 `console.log(data)` prints an array of all the objects from `var googleApi`. – Karen Chan Nov 03 '15 at 16:07
  • @KarenChan An array has no property `result` – A. Wolff Nov 03 '15 at 16:12
  • To expand on @A.Wolff 's comment, an array has no properties at all. :-) – jeffdill2 Nov 03 '15 at 16:15
  • @jeffdill2 There are keys and values within the objects in the array. May I ask if it is possible for me to identify the keys and values within with $.ajax() then? Cos it works with $.getJSON() x – Karen Chan Nov 03 '15 at 16:18
  • @jeffdill2 array has a `length` property :) – A. Wolff Nov 03 '15 at 16:18
  • 1
    @KarenChan May i ask you then what is wrong with using `$.getJSON()` method? – A. Wolff Nov 03 '15 at 16:19
  • @A.Wolff There is nothing wrong with it. I need to use authentication for the api with `$.ajax()` and that is when the code with `$.getJSON()` doesn't work... :((( x – Karen Chan Nov 03 '15 at 16:21
  • @A.Wolff ah, yes! haha, touché...and technically, I guess it has a `prototype` property too. :-) – jeffdill2 Nov 03 '15 at 16:22
  • 1
    @KarenChan yes, you can absolutely get to the values within the objects. You'll just have to `forEach()` over the array to get to each object, or if you knew that there was only a particular object from the array you actually cared about, you could target that specific one - `data[]`. – jeffdill2 Nov 03 '15 at 16:25

2 Answers2

2

...how could I identify if the value of a declared variable ... is the same as a value within the list of name keys in the array?

As per your provided response object you could iterate through it and check the values against your variable content:

var content = "user1";

$.each(response, function(i, v) {
   if (v.name == content) {
      console.log(v.name);
   }
});

Example Fiddle


As for the second part of your question:

but I got an error of "TypeError: data.result is undefined";

The reason you may be getting your error is because find is expecting a jQuery object, you have received a JSON object back from your endpoint, so using dot notation as above will should work as well:

success: function(data) {
    $.each(data, function(i, v) {
        if (v.name == content) {
            console.log(v.name);
        }
    });

}

You can see the answer to this question for a bunch of awesome information on how to access / proccess objects.

Also note your success callback in your code above is not closed, which will create errors.

Community
  • 1
  • 1
Michael Doye
  • 8,063
  • 5
  • 40
  • 56
  • Hi @M.Doye, I have tried it and looked at the amazing answer you mentioned but still getting an error of "undefined"... It would be very nice if you could let me know where have I done wrong please... https://jsfiddle.net/dq5515pd/1/ xxx – Karen Chan Nov 10 '15 at 10:13
  • Here you go - https://jsfiddle.net/dq5515pd/2/ - it seems the response data was slightly different to what it is in the question. This works if a name entered matches one in the response – Michael Doye Nov 10 '15 at 10:23
  • Hello, yes I want to see if a name entered matches one in the response but I couldn't even been able to find data.result cos it keeps having error popping up saying data.result or data['result'] is undefined... x – Karen Chan Nov 10 '15 at 10:53
  • And I also realised, when I stringify the `data` with $.ajax(), the api result doesn't print {"status":200, "success":true,"result":[{}]} as it showed in $.json(), and that is probably the reason why .result is undefined? x – Karen Chan Nov 10 '15 at 11:23
  • It doesn't print `{"status":200, "success":true,"result":[{}]}` even if `data` is not stringified. As you can see in this example - http://jsfiddle.net/dq5515pd/5/ - as such, you can simply iterate over each object which is returned. For example, in [this fiddle](http://jsfiddle.net/dq5515pd/5/) if I enter the name "Dirk" into the text box and click the enter button, I get an alert saying "Dirk" (because it found a match from the data that was returned form the API) - is this not what you are expecting? – Michael Doye Nov 10 '15 at 12:59
0
        function getID(name){

            $.each(data,function(key,value){    //value = object.value (name)

                $.each(value,function(key1,value1){     //value1 = user name (actual names in array)

                    if(value1 == content){
                        console.log(value.id);

                        var name = value.name;                  
                        $('#nameText').text(name);
                        console.log("Name: " + name);

                        return;
                        }
                    });

                });
            }

        getID(data);
        return false;   
Karen Chan
  • 164
  • 1
  • 1
  • 16