JQuery - Receive an error message when a value is missing

With my Website almost complete, I just need to add an error message for when a movie isn't found. I have an API that returns JSON and if someone enters an invalid movie like "ifeahaef," it returns null. Is there a way to use Jquery to display an error message like "No Movies Were Found!" right below the search bar? Here is how my site currently looks:

https://i.sstatic.net/yujzy.png

This is how I want it to look:

https://i.sstatic.net/n43qj.png

If needed, I can share my code as well. Here's my JavaScript function:

function callAjax(input) 
{ 
var url = "http://localhost:1337/search/" + input;

$.ajax({ 
type:'GET', 
url: url, 
success: function(data) 
{ 
console.log('SUCCESS'); 
$('#title').html("Title: " + data.title);
$('#release').html("Release: " + data.release);
$('#vote').html("Vote: " + data.vote);
$('#overview').html("Overview: " + data.overview);
$('#poster').html('<img src="' + data.poster + '" width=250 height=450 />'); 
$('#trailer').html("Trailer: <iframe width='420' height='315' src='https://www.youtube.com/embed/" + data.trailer + "' frameborder='0' allowfullscreen>");

},
error: function(request, status, err) 
{ 
console.log('ERROR'); 
} 
}); 
} 

$(document).ready(function(){ 

$('#submitButton').on('click', function(e){ 
e.preventDefault(); 

var input = $('#s').val();
callAjax(input); 
}); 

}); 

And here's the HTML template:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MovieTrailerbase</title>

<link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>

<div id="page">

    <h1>The MovieTrailer search</h1>

    <form id="searchForm" method="post">
        <fieldset>

            <input id="s" type="text" />

            <input type="submit" value="Submit" id="submitButton" />

            <div id="searchInContainer">
                <input type="radio" name="check" value="site" id="searchSite" checked />
                <label for="searchSite" id="siteNameLabel">Search movie</label>

                <input type="radio" name="check" value="web" id="searchWeb" />
                <label for="searchWeb">Search series</label>
            </div>

        </fieldset>
    </form>

<aside>
<div id="title"></div>
<div id="release"></div>
<div id="vote"></div>
<div id="overview"></div>
<br>
<div id="trailer"></div>
</aside>

<div id="poster"></div>


</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="script.js"></script>


</html>

Answer №1

When an API returns an error, it can actually be considered a success in some cases. To handle this scenario, you can implement the following solution:

function(response){
    if(response){
        // Implement your logic here
        $("#lblerror").addClass("hide"); // Hide label if movie is found
    }
    else{
        $("#lblerror").text("No Movie found");
        $("#lblerror").removeClass("hide"); // Show Label if no movie is found
    }
}

To make this process easier, add an error label to your HTML:

<label class="error hide" id="lblerror"></label>

Answer №2

Uncertain about the organization of your answer. However, I recommend structuring it as follows:

if(data.length <= 0 || data == null){
    $('#element-to-add-message-to').html('No titles found....');
    return;
}

Answer №3

1) Make sure to have an Error field included in the JSON object returned from your server. The JSON should consist of the following fields:

   title
   release
   vote
   overview
   poster
   trailer
   Error

2) Follow these steps using your server-side language:

  1. Retrieve the movie name from the request
  2. If the movie is found, create a JSON object with movie data and set Error = false, then populate the rest of the JSON with the movie details.

    2.1. If the movie is not found, create a JSON with Error = true. No need to include the other fields.

  3. Send the JSON back to the client side

3) In your Ajax success callback, check for any errors:

$.ajax({ 
 type:'GET', 
 url: url, 
 success: function(data){ 
     if(!data.Error){
       console.log('SUCCESS'); 
       $('#title').html("Title: " + data.title);
       $('#release').html("Release: " + data.release);
       $('#vote').html("Vote: " + data.vote);
       $('#overview').html("Overview: " + data.overview);
       $('#poster').html('<img src="' + data.poster + '" width=250     height=450 />'); 
       $('#trailer').html("Trailer: <iframe width='420' height='315' src='https://www.youtube.com/embed/" + data.trailer + "' frameborder='0' allowfullscreen>");
     }else{ 
         alert("Movie not found");
     }
 },
 error: function(request, status, err){ 
    console.log('ERROR'); 
 } 
}); 
} 

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

How can XML data be effectively showcased on a website?

I have a service that generates XML files every 10 seconds with server information. I am seeking a solution to showcase this data on a webpage. After researching online, it appears that utilizing AJAX would be beneficial as it permits the loading of dynam ...

PHP line breaks are not functioning as expected

I am having trouble formatting the email with line breaks to display as: Name: Email: Message: I attempted adding \r\n but it had no effect. Then I tried including $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n ...

Flipping the order of elements in an array using JavaScript as described in the

While I am aware there are simpler methods to reverse arrays in JavaScript, I am seeking assistance to fully understand how this particular reverse method works. Your help in clarifying this is greatly appreciated. function reverseArrayInPlace(array) ...

Wait for the definition of a variable before returning in React Native

I am currently receiving data asynchronously and displaying it within the render() function using {data}. My dilemma is how to ensure that the render() function waits until the variable is defined. Currently, the placeholder variable remains the same or d ...

Manipulating front matter metadata when reading/writing a markdown file in Node.js

I have a large collection of markdown files that I need to update by adding new data to their front matter metadata. Currently, the file structure looks like this: --- title: My title here --- Markdown content here My goal is to include an id property ...

Tips for creating dynamic rope animations with canvas and CSS3 styling

Interested in creating a canvas animation, or possibly using CSS3 for the same purpose. Looking to add an automatic rope animation, similar to it swaying gently. I've searched for scripts and other solutions, but haven't found anything suitable. ...

Displaying AngularJS content as text in an HTML file

I have been learning from the AngularJS Tutorial on Code School, but I'm experiencing an issue where my JavaScript code is not rendering properly in the HTML. Below is the snippet of HTML code: <html ng-controller="StoreController as store"> & ...

The compatibility of Cross-Origin Requests with Socket.io in a Nginx + NodeJS setup is functioning incompletely

In my server system, I have an nginx and a nodejs server set up. Depending on the subdomain, requests are forwarded to the appropriate NodeJS app using proxy_pass. However, I am facing an issue when trying to use Socket.io from a different origin. The joi ...

Transforming the setting into redux using setTimeout

I am currently working with the following context: interface AlertContextProps { show: (message: string, duration: number) => void; } export const AlertContext = createContext<AlertContextProps>({ show: (message: string, duration: number) =&g ...

JQuery ajax fails to trigger the success function

Upon using an ajax request to insert data into the database, I encountered an issue where the button message did not update after the submission was successful. Initially, I set the button text to Please wait... upon click, and intended to change it to Don ...

Having trouble sorting data-text values that include colspan cells

Latest Update: Encountered an issue with incorrect sorting and frozen sortings when dealing with a cell containing the colspan attribute. Refer to https://jsfiddle.net/2zhjsn31/12/ where the problem arises for the date 2018-06-24 On https://jsfiddle.n ...

Manipulate numerous documents within MongoDB by updating them with varying data in each

I have a list of unique IDs: idList = ["5ec42446347f396fc3d86a3d", "5ec422d4347f396fc3d86a3c", "5ecefaf0aead3070fbdab7dd"] I want to update the documents that match these IDs with different data in each one: const currentData = await Data.updateMany( ...

After the form submission, my Next.js component keeps rendering repeatedly in a cumulative manner

I am currently working on a memory game application using Next.js, Node.js, and Express.js. I seem to be encountering an issue specifically with the login page. Initially, there are no issues when submitting the form for the first time. However, after the ...

What is the best way to update this payload object?

Currently, I'm developing a route and aiming to establish a generic normalizer that can be utilized before storing user data in the database. This is the function for normalization: import { INormalizer, IPayloadIndexer } from "../../interfaces/ ...

An issue arose when trying to implement react-router within a multi-step registration process

While working on my multi-step registration form, I encountered an error when implementing react router. Clicking on the personal info link led to the following console errors: "Uncaught TypeError: Cannot read property 'ownerName' of undefined" ...

Issues presenting themselves with Material UI Icons

I need some help with a problem I'm having. I'm trying to integrate my React app into an Angular app, and everything is working fine except for the material-ui/icons. They appear, but they are not displaying correctly! I have made sure to use th ...

JavaScript threw an error because it encountered an unexpected or invalid token

I can't seem to identify the error in this code. Can someone please help me correct it? document.write(' <div> <a href=http://www.socialsignal.ir style=\'\\padding:5px;text-decoration: none;border: 1px solid #555;ba ...

The issue I am encountering is that the keyboard controls in JavaScript are not causing the

One of the key elements in my code revolves around JavaScript functionality. I have implemented a feature where objects can be moved by pressing keys such as "down" or "right". However, there seems to be an issue where an object loaded from a .json file is ...

Use the react-loadable library to dynamically import modules from multiple exported classes in JavaScript

Struggling to import CustomButton from a MyButton.js file using react-loadable? Can't seem to make it work in Home.js? Let's figure this out together! Solution for MyButton.js: import { CustomButton, BUTTON_STYLE, BUTTON_TYPE, BUTTON_SI ...

Issue with form action failing to properly refresh

I'm encountering an issue with form submission. I have an HTML form, but the action doesn't seem to be working properly. Could you take a look at it and see if there's anything I'm missing? <form action="add.php" method="post" autoc ...