Using jQuery with WebMatrix - javascript

I have written an html file using jQuery to read a JSON file. It works fine by itself; I tested it using Safari. However, when I try to use the exact same code in WebMatrix, it gives me an error, saying the JSON file cannot be found. I checked and the file is there.
Here is a simple version of the offending code. (The same comments apply: it works by itself in Safari but says "file not found" when used in WebMatrix.)
Can someone help me?
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
var Email=new Array();
var i=0;
var email;
$.getJSON('MoodMinder.json', function(data) {
$.each(data.User, function(i, f) {
Email[i]=f.Email;
i++;
})
email="<p>" + Email[0] + "</p>";
$(email).appendTo("#email");
});
</script>
</head>
<body>
<div id="email"></div>
</body>
</html>
Here is the JSON:
{
"User":[
{"Email":"cklann999#gmail.com"}
]
}
And here is the Web.config file (added section recommended by Nidzix):
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<customErrors mode="Off"></customErrors>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add invariant="System.Data.SqlServerCe.4.0" name="Microsoft® SQL Server® Compact 4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json"></mimeMap>
</staticContent>
</system.webServer>
</configuration>

You have to have configuration file called Web.config in the root folder, containing this piece fo code:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
</configuration>

Related

How to include external JS file in JSP file in Spring WebMVC framework?

I have tried below answer but it didn't work..
How include an external JS file in a JSP page
I have been searching on google but couldn't find anything useful...my JS file is at same level as that of WEB-INF..any help would be appreciated...
Below is the code that I'm using to include my JS file in JSP :-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.18.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/formValidation.js"></script>
below code is in web.xml :-
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
Below code is in dispatcher-servlet.xml file :-
<context:component-scan base-package="com.programcreek.helloworld.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
You might want to add ResourceHandler to resolve your static resources like js/css directory
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/js/**")
.addResourceLocations("/js/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
This method apply for java configuration class extends WebMvcConfigurerAdapter
The xml version should look like this
<mvc:resources mapping="/js/**" location="/js/"/>
This will resolve any .js file under /webapp/js/ directory, using something like below in .jsp file
<script src="js/custom.js"></script>
for help you can see this github link click here
I hope it will help you
and this is the project structure

Spring framework -- no mapping found for a JavaScript file

I'm getting what appears to me to be a strange error when I load my JSP. Spring is a Java framework, so why would I need a mapping for a JavaScript file? The JavaScript in my page is not working.
org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/ghs1986/js/javascript.js] in DispatcherServlet with name 'ghs1986'
For what it's worth, here is my applicationContext.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<mvc:annotation-driven />
<mvc:resources location="WEB-INF/pages/images/" mapping="/images/**" />
<mvc:view-controller path="/" view-name="home" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
This is how I'm trying to access the JavaScript in my JSPs.
<script type="text/javascript" src="js/javascript.js"></script>
And here is my web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app version="4.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd">
<display-name>Granada High School Class of 1986</display-name>
<servlet>
<servlet-name>ghs1986</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ghs1986</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
</web-app>
In much the same way as you have a mapping to allow the spring controller to know about images with
<mvc:resources location="WEB-INF/pages/images/" mapping="/images/**" />
you need to add a similar mapping to let it know about your javascript files. Something like,
<mvc:resources location="WEB-INF/pages/js/" mapping="/js/**" />
The issue is the same in both cases, the front end controller of Spring doesn't know how to find your js files without that.

Unable to remove # in AngularJS

The application is making use of the following:
AngularJS (v1.6.4)
webpack
ui-router
One requires the path to be independent of the # in the url.
For this I have added the following in the code:
In app.js
/* in the config section */
$locationProvider.hashPrefix('');
$locationProvider.html5Mode(true);
In index.html
<!-- under the head section -->
<base href="/">
When fired in the below format from address
'http://localhost/pathName'
it gives the following error:
Cannot GET /pathName
But the same works well when accessed through hyperlinks.
Also, on accessing 'http://localhost/#/pathName', the browser modifies the same to 'http://localhost/pathName'.
Is there a way by which the url can be accessed through GET request, by configuring from webpack (or some other way)?
EDIT 1:
Routing Code:
.config(($stateProvider) => {
$stateProvider
.state('pathName', {
url: '/pathName',
template: '<pathNameTemplate />'
});
})
No html5:
user types www.site.com/#/section in browser
request is sent for www.site.com (#... is ignored)
server return index.html
angular launches and see that there is # -- loads specific view
Html5:
user types www.site.com/section in browser
request is sent for www.site.com/section
server return index.html
angular launches and see that there is / -- loads specific view
So server MUST return index.html for all your paths - i.e. this means that you can not make it work from file system (file://.../). You need server and configure it adding redirects
P.S. you do not need this line
$locationProvider.hashPrefix('');
This is sample to remove # from url using
AngularJs v1.5.7
ui-router v0.4.2
web.config
app.js
var app = angular.module("app", ["ui.router"]);
app.config
var config = function (locationProvider) {
locationProvider.html5Mode(true);
}
config.$inject = ["$locationProvider"];
app.config(config);
index.html
<head>
<base href="/" />
</head
If you don't use IIS Service, and use Apache service such as xamp or etc... for your localhost change it to <base href="/sample/" />
web.config
<rewrite>
<rules>
<rule name="Main Rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
Note: you have to add this config because without it, when # removed after refresh [F5] you lose the state.
Remember In Apache (PHP) configs are different, and users have to add the settings in the .htaccess file.

Azure App Service adding '/' in URL

I'm working on a node.js application deployed on Azure App Service.
The application runs as expected on localhost-
http://localhost:55231/search?q=pink+floyd
But when deployed on Azure, the URL acts weird-
http://<appname>.azurewebsites.net/search/?q=pink+floyd Extra '/' before query string.
My Express.js code is-
app.get('/search', function (req, res) {
response = {
search_text:req.query.q,
};
//Few more code
HTML page serving query-
<form action = "/search" method = "GET">
<input type = "text" name = "q" placeholder=" Search your Favourite Music">
<input type = "submit" value = "Search">
</form>
I can't reproduce your issue on Azure App Service with Express. However, the following is what I tried so far.
My folder structure:
My app.js code looks like:
var express = require('express')
var app = express()
app.use(express.static('public'))
app.get('/', function (req, res) {
res.send('Hello Azure!')
})
app.get('/search', function(req, res) {
res.send(200, 'Test')
})
app.listen(process.env.PORT || 3000, function () {
console.log('Example app listening on port 3000!')
})
My test.html code:
<html>
<head>
<title>Test</title>
</head>
<body>
<form action="search" method="GET">
<input type="text" name="q" />
<button type="submit">Search</button>
</form>
</body>
</html>
web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
This configuration file is required if iisnode is used to run node processes behind
IIS or IIS Express. For more information, visit:
https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
-->
<configuration>
<system.webServer>
<!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support -->
<webSocket enabled="false" />
<handlers>
<!-- Indicates that the app.js file is a node.js site to be handled by the iisnode module -->
<add name="iisnode" path="app.js" verb="*" modules="iisnode"/>
</handlers>
<rewrite>
<rules>
<!-- Do not interfere with requests for node-inspector debugging -->
<rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
<match url="^app.js\/debug[\/]?" />
</rule>
<!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
<rule name="StaticContent">
<action type="Rewrite" url="public{REQUEST_URI}"/>
</rule>
<!-- All other URLs are mapped to the node.js site entry point -->
<rule name="DynamicContent">
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
</conditions>
<action type="Rewrite" url="app.js"/>
</rule>
</rules>
</rewrite>
<!-- bin directory has no special meaning in node.js and apps can be placed in it -->
<security>
<requestFiltering>
<hiddenSegments>
<remove segment="bin"/>
</hiddenSegments>
</requestFiltering>
</security>
<!-- Make sure error responses are left untouched -->
<httpErrors existingResponse="PassThrough" />
<!--
You can control how Node is hosted within IIS using the following options:
* watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
* node_env: will be propagated to node as NODE_ENV environment variable
* debuggingEnabled - controls whether the built-in debugger is enabled
To debug your node.js application:
* set the debuggingEnabled option to "true"
* enable web sockets from the portal at https://manage.windowsazure.com/#Workspaces/WebsiteExtension/Website/aaronexpress/configure
* browse to https://aaronexpress.azurewebsites.net/app.js/debug/
See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options
-->
<iisnode watchedFiles="web.config;*.js" debuggingEnabled="false" />
</system.webServer>
</configuration>
Tested result:
And could you share the web.config file which you are using? My guess is you're missing out on a simple thing there.

IIS outboud rule to match the non-existance of substring in file name

I have the following IIS configuration which forces PDFs to be downloaded as files in the browser instead of opening in the browser window.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<outboundRules>
<rule name="Force Download for PDFs" preCondition="FileIsPDF">
<match serverVariable="RESPONSE_Content-Disposition" pattern=".*" />
<conditions>
<add input="{REQUEST_FILENAME}" pattern="(.*)\\([^/]+)\.pdf$" />
</conditions>
<action type="Rewrite" value="attachment; filename={C:2}.pdf" />
</rule>
<preConditions>
<preCondition name="FileIsPDF">
<add input="{REQUEST_FILENAME}" pattern="\.pdf$" />
</preCondition>
</preConditions>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
However I need it to not apply if the file name is xxx_print.pdf, in other words I want the above rule to match all .pdf files except those that have _print at the end of the file name.
How is this possible? Needs to work for IIS7 and above.
Note you may be able to answer this without an understanding of IIS if you know how to use javascript's regular expression to match a string without a particular substring.
Turned out I just had to add another condition to the rule with the negate="true" attribute:
<add input="{REQUEST_FILENAME}" pattern="(.*)\\([^/]+)_print\.pdf$" negate="true" />

Categories

Resources