Check if the URL is correct (server response = 200)

Is it possible to validate the URL provided by a user in a form by checking if the server's response is 200?

I aim to perform this validation when the user enters information in the field and when it loses focus. Due to the same origin policy, I execute the check on the server side:

Client-side code snippet:

// Test the URL when input loses focus
angular.element(document).ready(function () {
    $('#target_url').focusout(function() {
        if ($('#target_url').hasClass('ng-dirty')){
            $http.post('/test-url', { target_url: scope.newJob.target_url }).success(function(response){
                if (response === 'valid url'){
                    console.log('Valid URL');
                }else{
                    console.log('URL not valid');
                }
            });
        };
    });
});

Server-side implementation:

// Route for testing URL
app.post('/test-url', function(req, res) {
    request(req.body.target_url, function (err, response) {
        if (response && response.statusCode === 200) {
            res.send('valid url');
        }else{
            res.send('URL not valid');
        }
    })
});

The issue here is that the response is only displayed in the console when I start typing in another input box, not when I lose focus. What am I doing incorrectly?

Note: I am using angular 1.1.5 which is why I didn't utilize 'ng-focus'.

Answer №1

In brief: to resolve the issue, make sure to enclose the focusout callback within $scope.$apply.

To elaborate further: Utilizing $.focusout in jQuery operates independently from Angular's digest cycle. As a result, Angular does not receive the necessary signal to initiate the $http.post function. Only when you switch to another field does the digest cycle conclude and finally trigger the $http.post request.

Here is a recommended adjustment:

$('#target_url').focusout(function() {
    $scope.$apply(function() {
        ...existing code remains unchanged...
    });
});

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 Hooks encountering issues with keydown/up events functionality

Currently, I am in the process of implementing arrow-based keyboard controls for a game that I have been developing. In order to stay updated with React, I decided to utilize function components and hooks. To showcase my progress, I have put together a dem ...

How to call two functions in React, passed as props, one after the other

I am currently working with two React class components. Component1 acts as the parent of Component2, where two functions (functionA and B) are passed in props from Component1 to Component2. Within the nested structure of Component2, there is a function cal ...

When a DOM object is passed in JavaScript, its value becomes indeterminate

I am currently working on creating a table that can change its background color based on an RGB value. Each row in this table contains clickable <td> cells that contribute to the RGB value. For example, the first row might be +/- 123, the second row ...

Whenever I use knex, I am faced with the error message: ER_NO_TABLES_USED - indicating that no tables

My MySQL database is running smoothly and I recently executed the following migration, which completed successfully: exports.up = function (knex, Promise) { return knex.schema.createTable('posts', function (t) { t.increments('id ...

In React Native, what is the method for utilizing index.js rather than separate index.ios.js and index.android.js files to create a cross-platform app?

Thank you for the help so far, I am new to React Native, and I'm trying to develop a cross-platform app. Here is my index.js file: import React from 'react'; { Component, View, Text, } from 'react-nativ ...

Using Vue with Webpack and PapaParse for efficient data parsing

I have encountered an issue while trying to implement PapaParse's worker option () with Vue's webpack template (https://github.com/vuejs-templates/webpack). The error message I'm receiving is: Uncaught ReferenceError: window is not #defi ...

What causes the unexpected behavior of JQuery's .animate() function?

I am currently working on a project that involves creating a div element for the purpose of dragging and dropping files. My goal is to have the height of the div increase when a file is dragged into it, and decrease when the file is dragged out. To achiev ...

Display multiple selection using JavaScript based on the element ID

I have a task to display the selected id using JavaScript, but currently, only the first select id is shown. Here is my HTML and JavaScript code: <tr> <td> <select name="jens_id[]" id="jens_id" required="" > <option ></op ...

Example of VPAID pre-roll ads

I've been searching for a VPAID code example to use in a sample preroll ad for quite some time now, but I haven't had any luck finding one. If anyone has a working example, could you please share it with me? Thank you! By the way, I am using vid ...

Passing a selected option in a select box to another website is achievable using JavaScript

I'm still learning JavaScript and I would like to have a user be directed to another page when they select an option from a dropdown menu. Any suggestions on how to accomplish this? ...

How can I retrieve a password entered in a Material UI Textfield?

My code is functioning properly, but I would like to enhance it by adding an option for users to view the password they are typing. Is there a way to implement this feature? const [email, setEmail] = useState(''); const [password, setPassword] = ...

What is the maximum character limit for jQuery?

Here's a code snippet I'm working with: $.get("url") .done(function(data){ alert("success"); alert(JSON.stringify(data)); }) .fail(function(data){ alert("fail"); alert(JSON. ...

What is the proper way to utilize the toISOString() function in JavaScript?

My current code uses currentDate.toISOString() to output the date in this format: "2013-01-15T12:08:54.135Z". However, I actually need the date to be formatted like this: "2013-01-15T12:08:54-06:00". The "-06:00" represents the timezone. ...

Encounter an HTTP error through Ajax triggered by an asynchronous click event using ZombieJS

I am currently working on a webpage that utilizes knockout.js and has a click handler. When the button is clicked, it triggers an AJAX request to an API server, which then responds with a contextual HTTP status result. For instance, if the user is unautho ...

Having issues with setTimeout on Chrome for Android when the browser is out of focus. Any ideas for resolving this?

I developed a web application that functions as a messaging system, where users can submit messages and others can receive them. The system operates through AJAX, with the front end using JavaScript to interact with a PHP backend. Everything runs smoothly ...

Determining if an emitted event value has been altered in Angular 4

I am currently working on an Angular 4 project. One of the features I have implemented is a search component, where users can input a string. Upon submission of the value, I send this value from the SearchComponent to the DisplayComponent. The process of ...

Employ the attributes of rowspan and colspan for effective table formatting

Looking for help with my table layout: I'm trying to insert two buttons in each cell, like this How can I achieve this using rowspan and colspan? You can check out this Fiddle for reference. This is my HTML code snippet: <table ng-controller="P ...

Lacking the knowledge on establishing range for amCharts

I am currently utilizing the amcharts plugin to generate visually appealing charts. While browsing through its features, I came across a few interesting ways to add ranges. However, I noticed that the structure of the code for these charts is different fro ...

Connecting event listeners to offspring elements, the main element, and the entire document

My request is as follows: I have multiple boxes displayed on a webpage, each containing clickable divs and text. When a user clicks on a clickable div, an alert should appear confirming the click. Clicking on the text itself should not trigger any action. ...

I am experiencing issues with the functionality of the submit and clear buttons on my form

Hello, I am a beginner in the world of coding and recently encountered an issue while working on a project. I attempted to create a form with both submit and reset buttons, but unfortunately, the form does not seem to be functioning properly on either de ...