Generate a JSON request based on user input

I need to implement a JSON request to the TMDB database based on user input for searching. The search request URL format is similar to this, where "Bond" is used as an example query.

For this functionality, I have a search function:


      $scope.search = function() {
    
        var base = 'http://api.themoviedb.org/3';
        var service = '/search/movie';
        var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
        var search = searchquery
        var callback = 'JSON_CALLBACK'; 
        var url = base + service + '?api_key=' + apiKey + search + '&callback=' + callback;
    
        $http.jsonp(url).
          success(function (data, status, headers, config) {
    
            if (status == 200) {
              $scope.movieList = data.results;
              console.log($scope.movieList)
            } else {
              console.error('Error happened while getting the movie list.')
            }
    
          }).
          error(function (data, status, headers, config) {
            console.error('Error happened while getting the movie list.')
          });
      }
      
      var searchquery = "Bond"
  

In the code snippet above, there's a placeholder variable named searchquery that needs to be populated with user input instead of a hardcoded value.

Below is the corresponding view:


      %h1
        Logo
      %li
        = link_to('Logout', destroy_user_session_path, :method => :delete)
    
      %div{"ng-app" => "app.exampleApp"}
        %div{"ng-controller" => "exampleCtrl"}
    
          %input{"ng-change" => "search(searchquery)", "ng-model" => "searchquery", "ng-model-options" => "{ debounce: 2000 }"}
          %span
            {{ searchquery }}
    
          %div{"ng-repeat" => "movie in movieList"}
            {{ movie.original_title }}
    

Currently, the view displays all movie titles retrieved from the JSON data. How can I utilize the user-provided input for making the appropriate search requests?

Answer №1

If you have bound searchquery to the ng-model of your input, you can retrieve this value in your controller using $scope.searchquery

Another recommended approach is to utilize the params object for setting the URL query parameters:

var apiKey = 'a8f7039633f2065942cd8a28d7cadad4';
var url = base + service;

$http.jsonp(url,{
  params: {
    "api_key" : apiKey,
    "search" : $scope.searchquery,
    "callback" : callback,
  }
}).success()

This method should work well and is much easier to comprehend (compared to manually constructing the URL)

I hope this explanation was helpful.

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

React: Obtain the sequence of components within the hierarchy

I am currently working on implementing helper components for CSS Grids. Here is a snippet of what I have so far: <ColumnContainer columns={[ "1em", "1fr", "auto", "auto", "1em", "auto"]}> <ColumnContainer.Row> { rowIdx => ( < ...

What features come with a Themeforest template?

Searching for ways to enhance my UI using an HTML/CSS template. Currently utilizing AngularJS with Bootstrap and have some custom functions integrated into my web/mobile app. I am in need of professional-looking html/css that can easily be copied and paste ...

Setting up Webpack for react-pdf in a Next.js application

In my Next.js application, I am utilizing the react-pdf library to generate and handle PDF files on the client side without involving the server. However, I am facing challenges in setting up Webpack for Next.js as I lack sufficient expertise in this area. ...

The table in React does not update after sorting the elements in the state, causing the list to not re-render

I'm encountering a problem with React where the data is not rendering properly after sorting the table. Even though I am updating the state variable using setState, the new updated data does not appear on the screen. Here's the snippet of my code ...

How can I determine in JQUERY when all ajax requests on a page have finished processing?

Is there a way in JQUERY to determine when all ajax calls on a page have finished? I need to run a specific method once all the ajax calls are done. ...

Place two buttons next to each other on the same row

Is there a way to align Native Base buttons so they both appear on the same line? Currently, the second button is positioned correctly on the right, but it seems slightly lower than the first button. How can I adjust this alignment? <View sty ...

Revive the JavaScript library for handling mouse wheel events

Utilizing the wheel-indicator JavaScript library, I am looking to revert the mouse wheel event back to its original state after it was initially set to preventDefault(). Despite attempting to use indicator.setOptions({preventMouse:"false"}) as suggested b ...

Filtering options in a webpage's dropdown menu

I am developing a website that includes a dropdown menu with approximately 60 options listed in alphabetical order. I am interested in finding a way to efficiently filter through the options by pressing a specific key on the keyboard, such as 'e' ...

Issue with overflowX:visible not functioning properly in react-infinite-scroll-component

After implementing the infinite scroll using the second method, I encountered an issue where the content I was displaying had overflow on width/x. I attempted to override the infinite scroll style with overflowX:visible, but unfortunately, it did not work. ...

Extracting text from an array within Meteor

I am currently utilizing Meteor along with the ajduke:bootstrap-tagsinput plugin for managing tags on my platform. Check out the ajduke:bootstrap-tagsinput example page here For inserting tags as arrays, I am using the True Multiple Value feature mention ...

The effectiveness of mouseup and mousemove events diminishes when employed in an external module

Currently, I am immersed in a three.js project that incorporates standard orbit controls on an object, specifically a particle cloud. Everything runs smoothly when this logic is embedded within my root class along with all the three.js code. However, my go ...

Selecting the most popular post from a Facebook group

Here is the JSON file that I am currently using JSON.parse(); in Google Apps Script. Currently, I have found a temporary solution with this code by selecting posts that have more than 15 likes. However, my goal is to be able to select the post with the ...

I'm struggling to create the third level of my dijit.Tree component

I attempted to construct a 3-level dijit.Tree structure, like this: -root | --level1 | --level2 Initially, it seemed like a straightforward task as there's a snippet of code in this guide (example 1). However, I encountered difficulties in impleme ...

Placing miniature vessels within a larger vessel, where two small containers fit on one level of the larger container (refer to images)

I am looking for a way for users to input text in the "your text" container and then click "add". This action should create a new container within the larger red-lined container with the information provided by the user. I know how to do this already, but ...

Replace a portion of text with a RxJS countdown timer

I am currently working on integrating a countdown timer using rxjs in my angular 12 project. Here is what I have in my typescript file: let timeLeft$ = interval(1000).pipe( map(x => this.calcTimeDiff(orderCutOffTime)), shareReplay(1) ); The calcTim ...

Exploring an array in Angular 2 using TypeScript

Just starting out with typescript and angular2 and working through some issues. I have a form that needs to display results from an array of changing items, so I don't know the exact index of each result. Here is my scenario: In my form.html file: ...

Should one declare a module for each file, or utilize the app module for all files?

As I delve into learning angularjs, I am encountering two different approaches to module usage that are leaving me a bit perplexed. I am struggling to grasp the rationale behind when to use one method over the other. For example: var app = angular.module ...

Utilize the HTML File Selector to access files from the server side

Is there a way to use the HTML file selector <input type="file"> to browse files that are stored on my server rather than locally? I understand that JS is client-side, and despite researching different approaches, I have not come across any suitable ...

No information is being emitted by the subject

In my application, I have a feature where users input data that needs to be validated in a form. Once the validation is successful, a button is enabled allowing the user to submit their order. However, I'm facing an issue with this specific component ...

Is it feasible to add on to an existing object in the database? (Using Node.js and Mongoose

After saving an object to the database using the following code: var newObject = new PObject({ value : 'before', id : 123456 }); newObject.save(function(err) { if (err) ...