Use xmlhttprequest function during text input instead of traditional form submission

Is it possible to implement a search form xmlhttprequest that dynamically updates results as the user types, rather than requiring them to submit a form?

function customersController($scope, $http) {
  $scope.search = function() {
    $scope.url = 'http://www.vanmaram.com/json_result.php?en=' + $scope.keywords;
    $http.get($scope.url).
    success(function(data, status) {
      $scope.status = status;
      $scope.data = data;
      $scope.result = data; // Show result from server in <li> element
    }).
    error(function(data, status) {
      $scope.data = data || "Request failed";
      $scope.status = status;
    });
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-csp ng-controller="customersController">
  <form style="position:relative;" ng-submit="search()">
    <input type="search" placeholder="Type english word" ng-model="keywords">
    <input type="submit" value="Search">
  </form>
  <ul>
    <li ng-repeat="word in result | limitTo:9">{{ word }}</li>
  </ul>
</div>

Answer №1

Hey there! Take a look at this demonstration on Plunkr: [link:http://plnkr.co/edit/6kuVR4?p=preview] I hope you find it helpful.

JavaScript

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.selected = "";
  $scope.countries = ["India", "Australia", "Japan"];
});

app.directive('autoComplete', function($timeout) {
    return function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: scope[iAttrs.uiItems],
                select: function() {
                    $timeout(function() {
                      iElement.trigger('input');
                    }, 0);
                }
            });
    };
});

HTML Example

<body ng-controller="MainCtrl">
  <p>Countries {{countries|json}}!</p>
  <div ng-app="MyModule">
    <div>
      <input auto-complete="" ui-items="countries" ng-model="selected" />selected = {{selected}}
    </div>
  </div>
</body>

This example uses the jQueryUI library version 1.8.16 (jquery-ui.js).

Answer №2

Using the ng-change attribute to trigger the same function as form submission

function customersController($scope, $http) {
  $scope.suggestword = function(argument) {
    $scope.url = 'http://www.vanmaram.com/ajax_json_suggestion.php?en=' + $scope.keywords; // The url of our search
    $http.get($scope.url).
    success(function(data, status) {
      $scope.status = status;
      $scope.data = data;
      $scope.suggetionresult = data; // Display result from server in <li> element
      $scope.result = null;
    }).
    error(function(data, status) {
      $scope.data = data || "Request failed";
      $scope.status = status;
    });
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-csp ng-controller="customersController">
  <form style="position:relative;" ng-submit="search()">
    <input type="search" placeholder="Type english word" ng-model="keywords" ng-change="suggestword()">
    <input type="submit" value="Search">
  </form>
  <ul ng-if='result.length'>
    <li ng-repeat="word in result | limitTo:9">{{ word }}</li>
  </ul>
  <div id="suggestion" ng-if='suggetionresult.length > 1'>
    Suggestions: <a ng-repeat="word in suggetionresult | limitTo:9">{{ word }}</a>
  </div>
</div>

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 handle a JavaScript POST request in an ASP.NET WebForm?

Although it may seem like a basic question, I am a bit rusty when it comes to webforms. This is my first time using Stripe.js and I would like to utilize it alongside stripe.net for client-side processing. Below is the client code: <%@ Page Title="" La ...

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

Why doesn't WebStorm display TypeScript inspection errors in real-time?

I'm currently utilizing WebStorm 2017.2.4 in conjunction with Angular 4.3 - I am facing an issue where TypeScript errors are not being displayed: https://i.sstatic.net/pcLQX.png Query How can I enable real-time inspections to occur immediately? (I ...

Understanding the concept of event bubbling through the use of querySelector

I am currently working on implementing an event listener that filters out specific clicks within a container. For instance, in the code snippet below I am filtering out clicks on elements with the class UL.head. <div> <ul class="head"> < ...

Sending information from a modal to a separate page using AngularJS

Seeking assistance with passing data from a modal to another page. Can you provide guidance on how to achieve this task? $scope.productdetails = function (size,selectedproduct) { var modalInstance = $uibModal.open({ templ ...

Having trouble with $(document).ready not functioning correctly?

After following the instructions to move my jQuery CDN to the bottom of the page, I encountered a problem. The script below was functioning perfectly when my jquery files were at the top of the page: if ($(window).width() >= 768) { $('.col-l ...

A guide to executing an HTTP request using Frida's JavaScript capabilities

This project is utilized for hooking Android processes. https://github.com/iGio90/FridaAndroidInjector It enables the injection of Frida agents from an Android application. It functions flawlessly. When aiming to hook into this function: com.ex.MediaPl ...

What is the most effective way to attach an ng-click event to the final item in an ng-repeat loop

How can I implement a click event that only triggers on the last item in a list of items? <li ng-repeat="item in items" ng-click="myFunction" >{{item.name}}</li> $scope.myFunction = function(){ // Add your logic here... } ...

Obtaining a complete element from an array that includes a distinct value

I'm attempting to retrieve a specific item from an array that matches a given value. Imagine we have an array const items = ["boat.gif", "goat.png", "moat.jpg"]; We also have a variable const imageName = "boat" Since we don't know the file ex ...

Accessing child value in parent component using React.js

In my project, I have a main Component called [MainLayout] which contains a child component called [ListItems]. The [ListItems] component further has multiple children components called [ListItem]. I am trying to figure out how to extract the value of the ...

Switching Perspective on Live ExpressJS Path -- Node.JS

I previously set up an express route with a template. Here's the code: app.get('/route', function route(req, res) { db.get('db_ID', function compileAndRender(err, doc) { var stream = mu.compileAndRender('theme-file.e ...

What is the most effective way to transfer parameters from an Angular controller or service to a server route and use them to query a

I'm facing an issue with passing parameters to my backend route for querying the database and fetching specific information without duplicating code. The problem is that I'm receiving an empty array as a return without any errors. Any suggestions ...

Tips for applying a jQuery class when the page is both scrolled and clicked

As I work on building a HTML website, I encountered an interesting challenge. I want to create a dynamic feature where, as users scroll through the page, certain sections are highlighted in the navigation menu based on their view. While I have managed to a ...

What is the best way to show a filtered list using a state that was created with useState in React?

Check out my code in CodeSandbox, consisting of 4 divs categorized as "Book" and "Article". There are buttons at the top to toggle between displaying all divs, only books, or only articles. However, clicking on any button currently shows all divs and gives ...

Using Jquery for AJAX validation

I am currently working on setting up error messages for my form using jQuery. However, when I try to view the form, it only requires the email field to be filled out, even though I have specified that the name field is required as well. Below is the code I ...

What is the best way to implement a sidebar closing animation?

Utilizing both react and tailwindcss, I successfully crafted a sidebar menu that elegantly appears from left to right when the user clicks on the hamburger icon. However, my attempts to create a reverse animation as the sidebar disappears from right to lef ...

I am experiencing difficulty with my Glsl shaders not loading properly on either the Liveserver or Github pages

I'm fairly new to the world of web development and I've been experimenting with incorporating 3D images into a webpage. In one of my projects, I'm utilizing .glsl files to load textures and shaders. Everything works smoothly when I run my co ...

Breaking apart paragraphs in a text using JavaScript

Hello, I am working on a code that is supposed to extract paragraphs from text entered into a textarea and create an array containing each paragraph. For example, it should turn text like this: Hello, that's the first paragraph Hello, that's th ...

A JointJS element with an HTML button that reveals a form when clicked

How do I bind data to a cell and send it to the server using the toJSon() method when displaying a form on the addDetail button inside this element? // Custom view created for displaying an HTML div above the element. // ---------------------------------- ...

What is the Next.js equivalent of routing with rendering capability for nested component paths?

I am new to Next.js and so far have been loving the experience. I'm a bit stuck on how to achieve the equivalent of the following code in Next.js These are all client-side routes that render nested components on the user page. The value of ${currentP ...