The conditional logic in AngularJS is not functioning as expected

https://i.sstatic.net/RvqYQ.pngMy code seems to have an issue with the if/else statement. I am checking the value of data.success which should contain either true or false. However, when I use (data.success === true) in the if statement, the else block executes and vice versa. Can anyone spot the mistake in my code?

$scope.verifyMobile = function () {
   var otp = {
      "otp": $scope.mobile.otp
   };
   $http({
      method: 'POST',
      url: 'verify_mobile',
      data: otp,
      headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
      }
   }).success(function (data, status, headers, config) {
      if (data.success) {
          $scope.verified = true;
          $scope.sms_sent = false;
      } else {
          alert(data.message);
      }
   }).error(function (data, status, headers, config) {
   });
};

Answer №1

To ensure the correct handling of the response data, it is recommended to update the variables data.success and data.message to data.success[0] and data.message[0] respectively. Since the response is in array format, it is crucial to treat it as such. The following code snippet illustrates this point:

$scope.verifyMobile = function () {
        var otp = {
            "otp": $scope.mobile.otp
        };
        $http({
            method: 'POST',
            url: 'verify_mobile',
            data: otp,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function (data, status, headers, config) {
            if (data.success[0]) {
                $scope.verified = true;
                $scope.sms_sent = false;
            } else {
                alert(data.message[0]);
            }
        }).error(function (data, status, headers, config) {
        });
};

Answer №2

The reason for this issue is that the variable data.success does not contain a boolean value. To determine the type of data.success, you can add a console log statement before the if-else block.

console.log(typeof data.success);

Check if the type is boolean, if not, make sure to handle it appropriately.

Answer №3

Swap out the use of .success() with .then() for better results.

Upon receiving a response, remember to examine the object returned.

$scope.fetchData = function() {
  $http({
    method: 'GET',
    url: 'http://jsonplaceholder.typicode.com/posts/1',
  }).then(function(success) {
    if (success.data.userId === 1) {
      $scope.name = 'Jason Statham';
    } else {
      $scope.name = 'Cristiano Ronaldo';
    }
  }, function(error) {
    console.log(error);
  });
}

SEE IT IN ACTION

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

Execution of scripts upon completion of document loading via AJAX

When loading a portion of HTML through AJAX, my expectation was that the JavaScript code inside would not run because it is dependent on the DOM being ready. However, to my surprise, the code within document.ready is still executing. I have even placed a ...

The `Route` component is expecting a `function` for the `component` prop, but instead it received an `object`

For a while now, I've been grappling with an issue that seems to be unique to me. The problem lies within my component and container setup for the start screen rendering at the initial route. components/DifficultySelection.jsx import React from &apo ...

Select2 using AJAX: chosen option disappears upon receiving AJAX response

Despite going through numerous questions and answers, the issue persists. Here is an excerpt of the code in question: <div class="col-md-2"> <label for="wh_location">{{ __('reports.warehouse_movement.location') ...

Does ng-show trigger the expression after each model change in AngularJS?

Here is a simple controller markup with an ng-controller directive and an input field: <div ng-controller="TestCtrl" ng-show="isVisible()"> <input type="text" ng-model="smth"/><br> <span>{{smth}}</span> </div> ...

Encountering an issue while attempting to transfer information between screens, receiving the error message: TypeError - undefined is not an object when evaluating 'route.params.item'

Currently facing an issue with my home screen where I am trying to navigate to the reviews screen with title, rating, and body. Previously, everything worked fine using const { item } = route.params;, but now I am encountering a TypeError: undefined is not ...

How to create a thumbnail hover effect with CSS3 and javascript, overcoming the z-axis issue

Currently, I am working on creating a set of thumbnails that enlarge when hovered over. The initial setup achieves the zoom effect using CSS3 transform:scale and ease-in-out. However, the issue is that the enlarged images overlap each other due to sharing ...

Enhance global variable by appending a line from a local function in Javascript

In my js files, I have some global functions that are used in all modules of the application. Currently, I am working on a module that requires modifying one of these global functions to run a local script every time it is called. The issue is that the g ...

Content must be concealed following the third paragraph

Dealing with an API that generates content in p tags, which can become excessively long. Considered hiding the content after 400 characters, but it poses a risk of cutting through HTML tags. Instead, looking to hide the excess content after 3 paragraphs a ...

Upgrading to React Router v6: Implementing Loader Functions with Context API

Having issues implementing loaders in React-Router V6 while making a request for a page through a function located in the context file. Unfortunately, I can't access the context from main.js where the router is defined. Main.js import ReactDOM from & ...

Retrieving information through a loop in Next.js

My goal is to utilize the data retrieved from one endpoint to make a call to another endpoint, filtered by ID. I intend to fetch both calls using getServerSideProps and then pass the data to a different component. The initial call will result in an array ...

How AngularJS setValidity function can prevent the modelValue from updating

I've encountered a challenge with a form that I can't seem to figure out. Here's what's going on: To address the issue, I came across an interesting directive from this source: https://github.com/TheSharpieOne/angular-input-match This ...

Utilizing jQuery to Trigger a JavaScript Function in a Separate File

Here is my question: I currently have 2 files: //File1.js function TaskA() { //do something here } //File2.js function TaskB() { //do something here } $(function() { TaskA(); }); The issue I am facing is that the TaskB function in File2.js ...

Enhancing Rails functionality with drag-and-drop to modify object attributes

I work with two main models: Collections and Images Collection Model class Collection < ActiveRecord::Base has_many :images, dependent: :destroy accepts_nested_attributes_for :images end Image Model class Image < ActiveRecord::Base belongs_ ...

Exploring node-validator's capabilities with asynchronous validation

Currently tackling my initial Node.js venture and facing a roadblock. Utilizing node-validator for input validation and working with Sequelize as an ORM. The Dilemma of Async Validation Striving to create custom validation to verify username availability ...

What is the best way to trigger a jQuery function when an option is selected from a Select2 dropdown menu?

I have implemented Select2 for custom dropdown styling. The options are structured like this: <option value="001,100">Option 001</option> <option value="002,200">Option 002</option> <option value="003,300">Option 003</opti ...

Is there a way to eliminate the surplus 2 download icons from this Angular code when there are a total of 3 users?

Here is some HTML code snippet: <tr *ngFor="let user of users"> <td> <h6 class="font-medium">{{user.id}}</h6> </td> <td> <h ...

Is there any benefit to making the SVG elements width and height 100%?

The Angular Material documentation app features an SVG Viewer that is able to scale the SVG content to fit the container using the following function: inlineSvgContent(template) { this.elementRef.nativeElement.innerHTML = template; if (this.sca ...

Conceal element when unchecked

There is a checkbox pre-selected labeled "Use profile address" with the address displayed below. If the customer unchecks the checkbox, the address that was shown before will disappear and a new input field for adding a different address will appear. I a ...

Generate JSON dynamically using a foreach loop

I am utilizing the jquery flot charts library to visualize my data. Take a look at this example JSFiddle I created demonstrating how the JSON structure required for the chart should be. The data I am working with is sourced from a MySql stored procedure a ...

Seeking help on modfiying div content with AJAX - any tips for showing navigation using hash or anchor?

Looking to create a dynamic page that updates content within a div asynchronously while also providing users with direct access to specific content within the div by using anchors (e.g. www.website.co.uk/#page1). I've successfully implemented the upd ...