Unable to process JavaScript function

Still in the process of developing my "mvc/social" PHP project, I am currently focusing on securing user input for the status message. I have created both a PHP and JavaScript function for this purpose, but it seems like the JavaScript function is not being recognized when called.

I have tested the same JavaScript file with another 'project' and confirmed that it works without any issues. However, I am facing difficulty in accessing it for this specific project!

The view file can be found at

(project root)/views/afterloginview.php

While the JavaScript file is located at

(project root)/public/js/application.js

In the afterloginview.php file, the following code is present:

<html>
    <head>
        <script type="text/javascript" src ="public/js/application.js"> </script>
    </head>
    <body>
        <form id = "form_state" action="" method ="POST">
            <input type="text" name="stato"/>
            <input type="submit" value="Aggiorna Stato"onclick="ok_state();"/>
        </form>

Within the application.js file, the following code is present:

var NotAdmitted = /[\|\+=<>()%\*]|(!=)|-{2}/; // 

function ok_state(){
    elem = document.forms[0]["stato"].value;
    if(elem == null || elem.length <= 1 || elem.length > 140){
        alert("Aggiornamento di lunghezza non consentita!Lo stato non verrà aggiornato");
        return false;
    }
    if(NotAdmitted.test(elem)==true){
        alert("Hai usato caratteri non consentiti,impossibile aggiornare!");
        return false;
    }
    else{
        return true;
    }
}

I have already attempted using ../public/js/application.js, but unfortunately, it did not resolve the issue.

Upon checking the console, I encountered the following error:

Uncaught TypeError: Cannot read property 'value' of undefined.

Despite feedback from a user confirming that the code is functional, I am still unable to identify the problem. What could be causing this issue?

Answer №1

When working with PHP, you can utilize the getcwd() function to access the current working directory and construct your file paths. It is recommended to have a more organized way to manage paths when following the MVC architecture.

For example, if the view file is located at (project root)/views/afterloginview.php, calling getcwd() will return (project root)/views/. Similarly, if the js file is located at (project root)/public/js/application.js, and we need to move up to the parent folder (project root), you can include the following in your view:

<script type="text/javascript" src ="<?php echo getcwd(); ?>../public/js/application.js"> </script>

Alternatively, you may define a PHP variable like $rootfolder in your model and handle it within the views for better organization. Happy coding!

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

Issue arises when isomorphic-dompurify is used alongside dompurify in Next.js 13 causing compatibility problems

I am currently facing a compatibility problem involving isomorphic-dompurify and dompurify in my Next.js 13 project. It appears that both libraries are incompatible due to their dependencies on canvas, and I am struggling to find a suitable alternative. M ...

The menu field remains open even after clicking on the menu

I have encountered an issue with my code. Here is a DEMO that I created on jsfiddle.net Currently, when you click on the red div, the menu opens. However, if you click on the menu items, the menu area does not close. What do I need to do in order to clo ...

Changing the background color with a switch function in ReactJS

After clicking a link, a view is rendered based on the "id" from a JSON. To enhance the user experience, I want to add a background color when a particular view renders and also toggle the style. This code snippet illustrates how the crawl is displaye ...

Search results in Eclipse are not displaying the filename

After extensive searching across multiple search engines, it seems like I am the only developer facing this particular issue. It has been affecting my productivity for years now. My problem arises when I perform a File Search in Eclipse 3.7.2 on Centos (a ...

What causes the Invalid Form Body error to appear when using the Discord API?

While developing a Discord bot, I encountered an issue with creating a ping command. The error message received was as follows: (node:37584) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.footer.icon_url: Scheme "flashybot& ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

Is there a way to clear the input value in the otp field?

Here is the codepen link I mentioned earlier: https://codepen.io/santoshch/pen/LYxOoWO <button @click="resetNow(id)"></button> resetNow(id){ this.$refs[`input-${id}`].input.value = ""; //In some cases, you may need to u ...

What is the best method for arranging checkboxes in a vertical line alongside a list of items for uniform alignment?

Trying to come up with a solution to include checkboxes for each item in the list, maintaining even vertical alignment. The goal is to have the checkboxes in a straight vertical line rather than a zigzag pattern. Coffee Nestle ...

I am struggling to make php redirect work using onclick() function

My PHP button is not redirecting properly. Assuming the page destination is correct, is there anything else that could be causing this issue? echo "<button id=\"create\" onclick=\"location.href('/team/teams.php?op=create');&bso ...

What is the best way to divide a single object in an array into multiple separate objects?

In my dataset, each object within the array has a fixedValue property that contains category and total values which are fixed. However, other keys such as "Col 2", "Col 3", etc. can have random values with arbitrary names like "FERFVCEEF erfe". My goal is ...

What is the best way to keep a header row in place while scrolling?

I am looking to keep the "top" row of the header fixed or stuck during page scrolling, while excluding the middle and bottom rows. I have already created a separate class for the top row in my header code: view image description ...

easy method for creating a hyperlink that triggers a "download" pop-up box

Is there a simple and efficient way to have some of my links trigger the 'save file as' prompt (similar to right-clicking) immediately after they are clicked for the first time? ...

Issues with assigning values to a variable in a PHP/MySQL prepared statement?

My PHP code contains a prepared statement with joins that is not assigning values to one of its variables: $dbRating = "x"; $dbFavDate = "x"; if($stmt = $dbcon->prepare(" SELECT i.*, u.username, r.rating, f.date_favorited FROM image i ...

NodeJS Express throwing error as HTML on Angular frontend

I am currently facing an issue with my nodejs server that uses the next() function to catch errors. The problem is that the thrown error is being returned to the frontend in HTML format instead of JSON. I need help in changing it to JSON. Here is a snippe ...

Every time I attempt to launch my Discord bot, I encounter an error message stating "ReferenceError: client is not defined." This issue is preventing my bot from starting up successfully

My setup includes the following code: const fs = require('fs'); client.commands = a new Discord Collection(); const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js')); for(const file of com ...

Unleashing the full power of Node.JS asynchronous operations

I've been struggling to grasp how to effectively manage the asynchronous nature of Node.JS. Despite reading extensively on the topic and experimenting with message passing and callback functions, I can't seem to get my object constructor to load ...

Is it possible for you to enter "1.00" instead of just 1 when using the input type as number?

I am using Polymer paper-input and I would like to ensure that my input with type "number" always displays 2 decimal points, even when it is a whole number. Instead of just displaying as "1", I want it to be shown as "1.00" at all times. I have tried sett ...

jQuery - can you identify which specific object from the entire set this is?

I am curious if there is a simple method to identify which DOM object I have when it is also part of another set of objects. To illustrate, let's consider the following scenario: There are 5 div elements: <div id="1"></div> <div id="2 ...

The br tag in HTML cannot be utilized in conjunction with JavaScript

I am currently working on a project involving HTML and JavaScript. I have a "textarea" where data is inserted into the database upon pressing the "Enter key." However, I am encountering two issues: Currently unable to save data like "Lorem Ipsum" (the ...

Is it possible to modify the value on the src img tag prior to scraping the data

Hey everyone, check out this piece of code I have: foreach ($image as $snimka){ $url = $snimka->src; $ch = curl_init($snimka->src); $fp = fopen('images/' . basename($url), 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp ...