Get the value of input tag for Ajax Request

Get the value of input tag for Ajax Request
0

#1
<input type="text" id="autocomplete">
<ul></ul>
  <script>
    var value;
    var wikiapi;
    $('#autocomplete').on('keypress',function(e){
        if(e.which==13){
            value=$(this).val();
            wikiapi="https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles="+value+"&format=json";
            $.ajax({
                url:wikiapi,
                crossDomain:true,
                dataType:"jsonp",
                xhrFields: {
                    withCredentials: true
                    },
                success: function(data){
                        var links=data.query.pages[171166].iwlinks;
                        var title=data.query.pages[171166].title;
                        $.each(links,function(i,val){
                        $('ul').append('<li><a href='+val.url+'>'+title +'</a></li>');
                    });
                console.log(data.query.pages[171166].iwlinks[0].url);
                }
            });
        }

    });
</script>

Hi, I am trying to retrieve the value from input tag. But It seems the method I’ve tried is not working. The value is not passed to the wikiapi var at all. Hence the ajax request cannot proceed. Can anyone point out the problem please. I’ve also tried "…$(’#autocomplete’).on(‘click’,function(){ …} also but not working.


#2

Hi,

A couple of things here.

When I got into the browser console, I see. “Uncaught TypeError: Cannot read property ‘iwlinks’ of undefined”

Looking in your code I see the offending line:

var links=data.query.pages[171166].iwlinks;

You seem to be assuming that the page will always be 171166. Furthermore, pages is not an array but is an object so must be accessed as pages[‘171166’].

But, how do we access an object property if we don’t know the key? I didn’t know either so I looked it up. Since it is the first (and only) property, we can do it like this: data.query.pages[Object.keys(data.query.pages)[0]]

Put into code, it might look like this.

                success: function(data){
                        var myPage = data.query.pages[Object.keys(data.query.pages)[0]];
                        var links=myPage.iwlinks;
                        var title=myPage.title;
                        $.each(links,function(i,val){
                        $('ul').append('<li><a href='+val.url+'>'+title +'</a></li>');
                    });
                console.log(myPage.iwlinks[0].url);
                }

This seems to give the result you want.

But I question whether or not the iwlinks is the search property you want - that is for links between wiki pages, as I understand it. I used &prop=fileinfo in the url to get the info I wanted.

But maybe you have a different plan.