I am trying to use the f:ajax tag to fire my validators on an inputText box but I am not having any luck. It just doesn't seem to fire the validators. But the validators do fire on form submit.
This is what I am using.
<td>
<h:inputText id="email" value="#{contactInfo.email}">
<f:validator validatorId="com.tcs.trn.validator.EmailValidator"></f:validator>
<f:validator validatorId="com.tcs.trn.validator.TcsEmailValidator"></f:validator>
<f:ajax execute="#this" event="blur" render="emailMessage"></f:ajax>
</h:inputText>
</td>
<td>
<h:message for="email" warnClass="warningMessage" errorClass="errorMessage" id="emailMessage"></h:message>
</td>
Request Header
Request URL:http://localhost:9080/JSF2Template/javax.faces.resource/jsf.js.xhtml?ln=javax.faces&stage=Development
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:oam.Flash.RENDERMAP.TOKEN=y4ftx6y5q; JSESSIONID=0000N5Uz-oCoU910GNVdCP3M8jc:-1
Host:localhost:9080
Referer:http://localhost:9080/JSF2Template/login/userDetails.xhtml
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11
Query String Parametersview URL encoded
ln:javax.faces
stage:Development
Response Headersview source
Content-Language:en-US
Content-Type:application/x-javascript
Date:Thu, 14 Mar 2013 19:32:10 GMT
Expires:Thu, 14 Mar 2013 19:32:10 GMT
Last-Modified:Thu, 14 Mar 2013 18:33:59 GMT
Server:WebSphere Application Server/7.0
Transfer-Encoding:chunked
This was resolved by adding this to the head. The script link was showing up by default but this actually allowed it to work for some reason.
<h:outputScript name="jsf.js" library="javax.faces" />
Related
The response of my AJAX-request delivers the whole body, so every element/script gets reloaded. I cant figure out why. The only part which needs a reload is content.
I'm using JSF2.3 and Wildfly17.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
>
<h:head>
</h:head>
<h:body>
<h:form>
<f:ajax render="content">
<h:commandLink value="#{msg['menu.1']}" action="#{page1.getLink()}"/>
<h:commandLink value="#{msg['menu.2']}" action="#{page2.getLink()}"/>
<h:commandLink value="#{msg['menu.3']}" action="#{page3.getLink()}"/>
</f:ajax>
<h:commandLink value="#{msg['menu.logout']}" action="#{homeBean.logOut()}"/>
</h:form>
<ui:insert id="content" name="content" >
<!--<ui:include src="/template/common/commonContent.xhtml" />-->
</ui:insert>
</h:body>
</html>
EDIT:
It looks like this:
EDIT2:
The response after pressing one of the commandLinks
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><changes><update id="javax.faces.ViewRoot"><![CDATA[<html xmlns="http://www.w3.org/1999/xhtml"><head id="j_idt2"><script type="text/javascript" src="/bwa/javax.faces.resource/jsf.js.xhtml;jsessionid=2o_BGXk3sRokUbdd2ta2TO_Sl2u-pPduIiijrwtW.pcwer1819?ln=javax.faces"></script></head><body onload="startTime()">
<form id="j_idt4" name="j_idt4" method="post" action="/bwa/user/textSearch.xhtml;jsessionid=2o_BGXk3sRokUbdd2ta2TO_Sl2u-pPduIiijrwtW.pcwer1819" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="j_idt4" value="j_idt4" />
<a id="j_idt4:j_idt5" href="#" onclick="mojarra.ab(this,event,'action',0,'content');return false">Home</a><a id="j_idt4:j_idt6" href="#" onclick="mojarra.ab(this,event,'action',0,'content');return false">Quellcode durchsuchen</a><a id="j_idt4:j_idt7" href="#" onclick="mojarra.ab(this,event,'action',0,'content');return false">Top1500</a>Ausloggen
</form>
<h2>Suche in Quellcode</h2>
<br />
<form id="j_idt10" name="j_idt10" method="post" action="/bwa/user/textSearch.xhtml;jsessionid=2o_BGXk3sRokUbdd2ta2TO_Sl2u-pPduIiijrwtW.pcwer1819" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="j_idt10" value="j_idt10" />
<table>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td><input type="text" name="j_idt10:j_idt12" />
</td>
<td><input type="submit" name="j_idt10:j_idt14" value="Suchen" />
</td>
</tr>
</table>
</form></body>
</html>]]></update><update id="j_id1:javax.faces.ViewState:0"><![CDATA[2371578821549273726:500402066268747694]]></update></changes></partial-response>
Request-header:
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0
Accept: */*
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Faces-Request: partial/ajax
Content-type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 304
Connection: keep-alive
Referer: http://localhost:8080/bwa/login.xhtml;jsessionid=2o_BGXk3sRokUbdd2ta2TO_Sl2u-pPduIiijrwtW.pcwer1819
Request-body
j_idt4=j_idt4&javax.faces.ViewState=2371578821549273726%3A500402066268747694&javax.faces.source=j_idt4%3Aj_idt6&javax.faces.partial.event=click&javax.faces.partial.execute=j_idt4%3Aj_idt6%20j_idt4%3Aj_idt6&javax.faces.partial.render=content&javax.faces.behavior.event=action&javax.faces.partial.ajax=true
The problem was that the action of the commandLinks returned a value and this overwrites the expected behavior with ajax. The solution is to set the a page variable with the url:
<h:form>
<f:ajax render="content">
<h:commandLink value="#{msg['menu.1']}" action="#{sessionData.setPage('/user/1.xhtml')}"/>
<h:commandLink value="#{msg['menu.2']}" action="#{sessionData.setPage('/user/2.xhtml')}"/>
<h:commandLink value="#{msg['menu.3']}" action="#{sessionData.setPage('/user/3.xhtml')}"/>
</f:ajax>
<h:commandLink value="#{msg['menu.logout']}" action="#{homeBean.logOut()}"/>
</h:form>
And later use this variable to load the page:
<h:panelGroup layout="block" id="content">
<ui:include src="#{sessionData.page}" />
</h:panelGroup>
I also replaced my <div> with <h:panelGroup layout="block"> because JSF isn't able to locate it and the changes were not rendered.
See also
How to ajax-refresh dynamic include content by navigation menu? (JSF SPA)
Is it possible to update non-JSF components (plain HTML) with JSF ajax?
I have two drop-down menus in a form, on changing the value on the first menu the second menu is refreshed(AJAX) and then I can submit the form using a button which performs some action in a view scoped bean and on completion redirects to success page, am facing a problem which I can't figure out
that is, when I was using the <f:ajax> tag:
When I submit the form without changing the menus, the action is performed and I get redirected normally.
when I change the menus and click submit button the action is performed but the page is never redirected
when using the <p:ajax> tag it worked as expected, I've been searching for awhile now, I guess the problem is about requesting ajax but I can't figure the specific reason, this is a snippet from the page.
XHTML
<div class="col-xs-12 col-sm-12 col-md-4 col-lg-4">
<div class="form-group arabic">
<h:selectOneMenu id="governorates" required="true"
requiredMessage="#{msgBean.getRequired()}"
styleClass="btn btn-white dropdown-toggle" style="width:100%"
value="#{propertyBean.property.propertyDetails.governate}"
converter="#{governateConverter}">
<f:selectItem itemValue="#{null}" itemLabel="اختر المحافظة"
noSelectionOption="true" />
<f:selectItems value="#{dataBean.availableGovernates}"
var="governateObj" itemValue="#{governateObj}"
itemLabel="#{governateObj.name}"/>
<p:ajax listener="#{propertyBean.setValidCities}"
update="governorate_message cities" />
</h:selectOneMenu>
<h:message id="governorate_message" for="governorates"
infoClass="help-block" errorClass="help-block error" />
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-4 col-lg-4">
<div class="form-group arabic">
<h:selectOneMenu id="cities" required="true"
requiredMessage="#{msgBean.getRequired()}"
styleClass="btn btn-white dropdown-toggle" style="width:100%"
value="#{propertyBean.property.propertyDetails.city}"
converter="#{cityConverter}">
<f:selectItem itemValue="#{null}" itemLabel="اختر المدينة"
noSelectionOption="true" />
<f:selectItems value="#{propertyBean.validCities}"
var="cityObj" itemValue="#{cityObj}"
itemLabel="#{cityObj.name}"/>
<p:ajax update="cities" />
</h:selectOneMenu>
<h:message id="city_message" for="cities" infoClass="help-block"
errorClass="help-block error" />
</div>
</div>
<h:commandButton id="update" value="تعديل"
onclick="if( validate('submitForm')==true){ updateProperty();} else{ return false;}"
action="#{propertyBean.update}"
class="btn btn-green btn-lg arabic"
rendered="#{propertyBean.isNew == false}">
<f:param name="propertyId" value="#{propertyBean.property.id}">
</f:param>
</h:commandButton>
Java class
public String update() {
System.out.println("updating");
return navBean.redirectToSuccess();
}
using <f:ajax> tag
<div class="col-xs-12 col-sm-12 col-md-4 col-lg-4">
<div class="form-group arabic">
<h:selectOneMenu id="governorates" required="true"
requiredMessage="#{msgBean.getRequired()}"
styleClass="btn btn-white dropdown-toggle" style="width:100%"
value="#{propertyBean.property.propertyDetails.governate}"
converter="#{governateConverter}">
<f:selectItem itemValue="#{null}" itemLabel="اختر المحافظة"
noSelectionOption="true" />
<f:selectItems value="#{dataBean.availableGovernates}"
var="governateObj" itemValue="#{governateObj}"
itemLabel="#{governateObj.name}"/>
<f:ajax event="blur" listener="#{propertyBean.setValidCities}" render="governorate_message cities" />
</h:selectOneMenu>
<h:message id="governorate_message" for="governorates"
infoClass="help-block" errorClass="help-block error" />
</div>
</div>
the browser network shows the following when using f:ajax
request:
POST /Newgar_revamp/pages/add.xhtml HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 2207
Pragma: no-cache
Cache-Control: no-cache
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: http://localhost:8080
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryFE3725BjJXsA1xKf
Referer: http://localhost:8080/Newgar_revamp/pages/add.xhtml?propertyId=3
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6,ar;q=0.4
Cookie: JSESSIONID=B81FF21F23988CC8C98D84DA14B36F54
response:
HTTP/1.1 302 Found
Server: Apache-Coyote/1.1
Location: http://localhost:8080/Newgar_revamp/pages/status/success.xhtml
Content-Length: 0
Date: Fri, 20 Nov 2015 21:24:32 GMT
but the browser never redirects to the success page
I have the below code
<h:form enctype="multipart/form-data">
<p:panel id="panelEmployee">
<h:commandButton value="Go" action="#{employee.getFirstEmployee()}">
<f:ajax render="panelEmployee" execute="#form"/>
</h:commandButton>
<p:fileUpload value="#{employee.file}" mode="simple" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
</p:panel>
</h:form>
When i clicked on go button and if the form enctype is multipart/form-data then the first ajax call is ok, the second one gives this javascript error
SCRIPT5007: Unable to get value of the property 'contentWindow': object is null or undefined
Can anyone please suggest?
Thanks.
overflow,
since yesterday I have for unknown reasons following problem:
i have a list of items, and when i delete one of them and let the page refresh by ajax, it stucks after the deletion-procedure and prints me following error:
Jul 28, 2013 3:54:42 PM org.apache.myfaces.context.servlet.ServletExternalContextImpl setResponseContentType
SEVERE: Cannot set content type. Response already committed
the deletion code is called by:
public void deleteEntry(AjaxBehaviorEvent event){...} //runs fine
and the ajax part is:
<h:commandButton value="delete" onclick="closeDialog(deleteDlg);">
<f:ajax event="click" execute="#form" render=":maintable" listener="#{updateEntryMetaDataBean.deleteEntry}"/>
</h:commandButton>
i don't really know why this error occurs, it seems like it only occurs on this specific page, on other pages with the same behaviour it runs fine.
my ajax-status hangs up and keeps running too:
<!-- AJAX-STATUS INFO -->
<p:ajaxStatus style="width:64px;height:64px;position:fixed;right:5px;bottom:5px">
<f:facet name="start">
<p:graphicImage value="resources/images/loading.gif" />
</f:facet>
<f:facet name="complete">
<h:outputText value="" />
</f:facet>
</p:ajaxStatus>
what can I do there?
I am trying to implement a Delete method on a Web API controller. However, I always get a 404 - Not Found. At this point, I have GET, POST and PUT methods that are working just fine. I've been reading a handful of the other SO posts about the same issue - just none of them are working.
The Controller Action
public virtual HttpResponseMessage Delete(string customerId)
{
adapter.RemoveCustomer(customerId);
return Request.CreateResponse(HttpStatusCode.OK, "The customer was deleted.");
}
The AJAX Request
function remove(customer, success, error) {
var url = '/api/Customer';
var data = JSON.stringify({ 'customerId': customer.CustomerId });
$.ajax({
url: url,
type: 'DELETE',
data: data,
contentType: 'application/json'
})
.done(function (data, textStatus, handler) {
success(data);
})
.fail(function (handler, textStatus, errorThrown) {
error(errorThrown);
});
};
The Web.Config
This is my web.config file. Except for the modules section, everything is the same as when I created the project:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<!--<modules runAllManagedModulesForAllRequests="true"></modules>-->
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
I am using IIS Express, but the issue still occurs if I switch back to Visual Studio Development Server.
The Raw HTTP
Here is the raw HTTP request captured by Fiddler:
DELETE http://localhost:63654/TestMvcApplication/api/Customer HTTP/1.1
Host: localhost:63654
Connection: keep-alive
Content-Length: 49
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:63654
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
Content-Type: application/json
Referer: http://localhost:63654/TestMvcApplication/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
{"customerId":"e107e2dc20834545ae209849bff195f0"}
And here is the response:
HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcdHBhcmtzXERvY3VtZW50c1xHaXRIdWJcVGVzdE12Y0FwcGxpY2F0aW9uXFRlc3RNdmNBcHBsaWNhdGlvblxhcGlcQ3VzdG9tZXI=?=
X-Powered-By: ASP.NET
Date: Tue, 02 Jul 2013 13:11:52 GMT
Content-Length: 220
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:63654/TestMvcApplication/api/Customer'.","MessageDetail":"No action was found on the controller 'Customer' that matches the request."}
This is an open source project for teaching myself. I have checked in the latest in case anyone wants to see the complete source.
public virtual HttpResponseMessage Delete(string customerId)
Parameter is a simple type and is bound from URI and not from request body. Either pass the customer ID in query string like this - http://localhost:63654/TestMvcApplication/api/Customer?customerId=123 or change the signature to public virtual HttpResponseMessage Delete(string id) and use a URI http://localhost:63654/TestMvcApplication/api/Customer/123.