Configuration of HTTP JSONP variable in Angular

I have successfully implemented http.jsonp for making cross-domain calls. Here is the configuration object I am using:

 var config = {
            params: {
                action: "query",
                prop: "revisions",
                format: "json",
                rvlimit: 50,
                titles: 'obama',//works
               // titles: val, //doesn't works
                callback: "JSON_CALLBACK"    
            }           
        };

        var url = "http://en.wikipedia.org/w/api.php?";

        $http.jsonp(url, config).success(function(data) {
            var pages = data.query.pages;

            for (var pageid in pages)
            {        
                $scope.revisions = pages[pageid].revisions;
                break; // expect only one page
            }

            $scope.loaded = true;
        });

While everything functions correctly with a static value of 'obama' for 'titles,' I am facing an issue when I try to dynamically set the value through an input box. I have created a jsfiddle reproducing the issue:

Any suggestions on how to resolve this?

http://jsfiddle.net/L4qZZ/

Answer №1

Once the user presses the "Submit" button, you will need to retrieve the information.

The issue with your current code is that you are using val to assign the title rather than $scope.val.

Make the necessary adjustments to your code so that the HTTP request is triggered when the user clicks the button, resulting in the successful retrieval of your data.

For a visual representation of the solution, you can visit this Fiddle.

Simply input "obama" into the text field and press the button to access your desired data.

Answer №2

because $scope is not being used to retrieve the ng-model values, it is recommended to use $scope.val instead of just val

Give it a try

var settings = {
    params: {
        action: "query",
        prop: "revisions",
        format: "json",
        rvlimit: 50,
        titles: $scope.val,
        callback: "JSON_CALLBACK"    
    }           
};

Answer №3

A suggestion for improving your code structure is to transfer the data loading functionality to a service. Consider the following example:

app.factory('Wiki', function ($q, $http) {
    return {
        loadData: function (title) {

            var deferred = $q.defer(),
            config = {
                params: {
                    action: "query",
                    prop: "revisions",
                    format: "json",
                    rvlimit: 50,
                    titles: title,
                    callback: "JSON_CALLBACK"
                }
            },
            url = "http://en.wikipedia.org/w/api.php?";

            $http.jsonp(url, config).success(function(data) {
                var pages = data.query.pages;
                for (var pageid in pages) {
                    deferred.resolve(pages[pageid].revisions);
                    break;
                }
            });

            return deferred.promise;
        }
    };
});

You can then utilize this service in your controller like so:

app.controller('HistoryController', function($scope, Wiki) {
    $scope.loaded = false;
    $scope.getData = function(val) {
        Wiki.loadData(val).then(function(data) {
            $scope.loaded = true;
            $scope.revisions = data;
        });
    }
    $scope.getData('obama');
});

By utilizing services, your code becomes more adaptable and manageable, especially when handling data-related tasks.

Check out the demo: http://jsfiddle.net/L4qZZ/1/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to iterate through an ID using jQuery?

After pulling the list of doctors in my area from the database and displaying it on my webpage, I now want to load each doctor's "About" content inside a Bootstrap modal. I added an "about" column within the same database table where the doctors' ...

Update Json information within VueJsonCSV and VueJS component

I'm currently using the VueJsonCSV component to export data to a CSV file. The values being exported are retrieved from the Vuex Store. <template> <v-btn depressed> <download-csv :data="json_data"> Export Files </downl ...

Unexpected issue: Angular view is failing to display jade templates

I'm facing an issue while setting up angular with ng-route using JADE. I am unable to connect to my templates where I have stored the HTML files. Below are the steps involved. I know it's a bit lengthy, but I wanted to provide all the details. An ...

Incorporating a remote PHP file into your website using JavaScript

Is it feasible to utilize JS (jQuery) for executing a $.post from any website on any domain to a script on my server? This query stems from my reluctance to disclose my PHP files to clients (and avoid spending money on ionCube or similar solutions). By se ...

Utilizing styled-components or personalized components alongside cypress

Cypress selector made simple: just use cy.get('.myComp') and it will select <input className="myComp" />. But when it comes to styled-components... Perhaps we have to resort to using custom attributes like cy-data or cy-testid. Sadly, it s ...

Console displays null as the attribute value

When I check the console, I notice that the data-postid attribute is displaying 'null'. What could be causing this issue? I would like to view the data-id in the console when clicking on the button with the id modal-save. I have reviewed my cod ...

Arrange jQuery UI elements in descending order

I need to rearrange a list in descending order, starting from the highest value down to the lowest. The values are currently listed as 10,9,8,7,6,5,4,3,2,1 and I need to update the data-ids accordingly. jQuery('.photos').sortable({ stop: f ...

A step-by-step guide to summing two numbers within a list using vue.js

How do I calculate the average of the first 5 numbers in my list taken from the URL, grouped by 5-minute intervals? I have a delay of 1 minute to ensure there are 5 values within the initial 5 minutes. After that, I want to display the averages in 3 differ ...

Using Puppeteer and Scrapy, this innovative Web Crawler with Scraper combines the power of both

As a newcomer to web technologies, I am faced with the task of crawling and scraping numerous websites that utilize a combination of React, JavaScript, and HTML. These sites collectively contain approximately 0.1 to 0.5 million pages. My plan is to use Se ...

What could be causing redux.props.reducer to return undefined?

I recently encountered an issue with my code. I have a function in the actions folder that successfully fetches a URL using axios. However, there seems to be a problem when trying to retrieve the data from the reducer. I have a mapStateToProps function set ...

Exploring the use of @HostListener in Angular for handling drop events

I am currently working on developing a directive for drag and drop functionality with files. I have successfully implemented the dragenter and dragleave events, but for some reason, the drop event is not being recognized. @HostListener('drop', [ ...

Issues with Rock Paper Scissors Array in Discord.js V12 not functioning as expected

I'm currently working on implementing an RPS game in my Discord bot. I want to create a feature where if the choice made by the user doesn't match any of the options in the list, it will display an error message. Here is the code snippet that I h ...

Looking for Efficiency in Basic JavaScript Arithmetic Operations

I'm having trouble figuring out how to display a total price after a selection is made. My goal is to take the selected value, multiply it by 100, and then use the updateTotal function to show the total. // Gather Data & Prices for Updating Dynamic P ...

Tips for configuring jQtree to initially display the tree structure from the HTML source

Up to this point, I have utilized jQuery TreeView for the navigation menus on my website. However, as the main navigation menu has grown significantly in size (40869 bytes out of 67054 bytes), I am seeking a way to streamline it by using AJAX calls to fetc ...

Definition of a Typescript Global.d.ts module for a function that is nested within another function

Simply put, I have a npm module that exports a function along with another function attached to it: // @mycompany/module ... const someTool = (options) => { // do some cool stuff }; someTool.canUseFeature1 = () => { return canUseSomeFeature1(); ...

Utilizing streams for file input and output operations in programming

This unique piece of code allows for real-time interaction with a file. By typing into the console, the text is saved to the file and simultaneously displayed from it. I verified this by manually checking the file myself after inputting text into the cons ...

XPages component retrieval function is malfunctioning

Utilizing an XPage with JQuery dialog and client-side validation adds efficiency to the user input process. However, there seems to be a disconnect between the client-side validation and server-side properties. Although the client-side validation functions ...

Is there a way for me to manually designate certain domains with the rel="follow" attribute while assigning all other external links with the rel="nofollow" attribute?

I'm working on developing a community platform similar to a social network. I've implemented a code that automatically makes all external links nofollow. However, I would like to create a feature that allows me to remove the nofollow attribute f ...

Error message: Unable to load image from local source in Vue application

I am currently working on creating a simple dice roll game in VueJs. However, I encountered an issue with using the dice images as it keeps giving me a 404 error. When I attempted to use require(), it stated that the function was not defined. After some t ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...