You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@ofbiz.apache.org by Levenimeux <ya...@gmail.com> on 2010/07/01 10:14:11 UTC

AJAX JSON response

"Hi everybody ;
i'm  an ofbiz framework beginner developper and in the application i'm
developping i need to use AJAX in the client side. i'm now try to use Json
for the response but i get no result . when i fire a request to the
controler , instead of  updating the div i've prepared in the client side
page i get a downlodable file wich content is the following one :
-----------------------------------------------------
{"targetRequestUri":"/testServiceAjax","_CONTEXT_ROOT_":"C:\\workspace\\ofbiz\\hot-deploy\\practice\\webapp\\practice\\","javax.servlet.request.key_size":128,"_FORWARDED_FROM_SERVLET_":true,"javax.servlet.request.ssl_session":"4c2b3a693e0b8204df23eb50f3c5bfe89ab1ae92c9d134be9b3d55fe55f5e284","_REQUEST_FROM_SPIDER_":"N","_SERVER_ROOT_URL_":"https://localhost:8443","_LOGIN_PASSED_":"TRUE","_CONTROL_PATH_":"/practice/control","javax.servlet.request.cipher_suite":"SSL_RSA_WITH_RC4_128_MD5","thisRequestUri":"json"}
--------------------------------------------------------
 then  i suppose that i have this type of response because in my webapp
controller there is no handler for the type Json .so  i search in ofbiz for
any handler of the json  type and i find as reponse the common-controller of
the common component in ofbiz (common
/webcommon/webinf/common-controller.xml). while reading this controller and
looking for any handler of the json type i found this comment :
--------------------------------------------------
<!-- These event handlers have been deprecated, if you need to send json
responses then chain
         the json request from this controller after calling your event
    <handler name="jsonservice" type="request"
class="org.ofbiz.webapp.event.JSONServiceEventHandler"/>
    <handler name="jsonservice-multi" type="request"
class="org.ofbiz.webapp.event.JSONServiceMultiEventHandler"/>
    <handler name="jsonsimple" type="request"
class="org.ofbiz.webapp.event.JSONSimpleEventHandler"/>
    <handler name="jsonjava" type="request"
class="org.ofbiz.webapp.event.JSONJavaEventHandler"/>
     -->
--------------------------------------------------
so i make a copy of the last line in this comment to my app controller but i
get the same response as described before... so now i have no idea of how to
use this Json type in my webapp controller ...
 can anyone explain me the  meaning of the comment i found in the
common-cotroller or 
can anyone explain me the way to use Ajax with the JSON type in the
controller  and some link about the subject will be welcome
thank for advance ....  "

-- 
View this message in context: http://ofbiz.135035.n4.nabble.com/AJAX-JSON-response-tp2274772p2274772.html
Sent from the OFBiz - User mailing list archive at Nabble.com.

Re: AJAX JSON response

Posted by Levenimeux <ya...@gmail.com>.
Hi sasha thanks for your help
i've tried to follow your instructions as you explained in your last post:
i wrote my java event by making it look like  the JSONJaveEventHandler as
you said. In the java event i just parse the resquest parameters to a
JsonString and after i get the writer and write the same parameters out by
using the writer ( the gold in this java event was just to test if the same
parameters receives from the request will be sent by using the json to the
client).
but in the client side after firing a request  i dont have any response
(when triying to update the div ).
ive supposed that im not updating the div the best way so i checked on the
web different way to update a div by a json response but no one of the
results i had help me to have the div  updated on the client side ...
may be my error is in the java event i wrote or even in the js script on the
client side ...
so can  you just tell me about how youve updated your div when youve used
Json  and what you return in your java event after using the writer to put
your json parsed parameters in the response.
i make here a copy of my java event, my js script and my client page may you
can have a look and help me telling me where ive made a mistake....

*the java event 1: using a simple parsing  of the request parameters:
-------------------------------------------------------------------
package src;
import org.ofbiz.webapp.event.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.webapp.control.ConfigXMLReader.Event;
import org.ofbiz.webapp.control.ConfigXMLReader.RequestMap;

/**
 * JSONJavaEventHandler - JSON Object Wrapper around the JavaEventHandler
 */

public  class TestClass implements EventHandler{

	public static final String module =TestClass.class.getName();
    protected EventHandler service;

    public void init(ServletContext context) throws EventHandlerException {
        this.service = new JavaEventHandler();
        this.service.init(context);
    }

    public String invoke(Event event, RequestMap requestMap,
HttpServletRequest request, HttpServletResponse response) throws
EventHandlerException {
        // call into the java handler for parameters parsing and invocation
        String respCode = service.invoke(event, requestMap, request,
response);

        // pull out the service response from the request attribute
        Map<String, Object> attrMap =UtilHttp.getParameterMap(request);
        //Map<String, Object> attrMap =
UtilHttp.getJSONAttributeMap(request);

        // create a JSON Object for return
        //JSONObject json = JSONObject.fromObject(attrMap);
        JSONObject json = JSONObject.fromObject(attrMap);
        String jsonStr = json.toString();
        if (jsonStr == null) {
            throw new EventHandlerException("JSON Object was empty; fatal
error!");
        }

        // set the X-JSON content type
        response.setContentType("application/x-json");
        // jsonStr.length is not reliable for unicode characters
        try {
            response.setContentLength(jsonStr.getBytes("UTF8").length);
        } catch (UnsupportedEncodingException e) {
            throw new EventHandlerException("Problems with Json encoding",
e);
        }

        // return the JSON String
        Writer out;
        try {
            out = response.getWriter();
            out.write(jsonStr);
            out.flush();
        } catch (IOException e) {
            throw new EventHandlerException("Unable to get response writer",
e);
        }

        return respCode;
    }

}


-------------------------------------------------------------------
*the java event 2: using a xhtml tag to be transform by the eval() function
of js:
-------------------------------------------------------------------
package src;
import org.ofbiz.webapp.event.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.webapp.control.ConfigXMLReader.Event;
import org.ofbiz.webapp.control.ConfigXMLReader.RequestMap;

/**
 * JSONJavaEventHandler - JSON Object Wrapper around the JavaEventHandler
 */

public  class TestClass implements EventHandler{

	public static final String module =TestClass.class.getName();
    protected EventHandler service;

    public void init(ServletContext context) throws EventHandlerException {
        this.service = new JavaEventHandler();
        this.service.init(context);
    }

    public String invoke(Event event, RequestMap requestMap,
HttpServletRequest request, HttpServletResponse response) throws
EventHandlerException {
        // call into the java handler for parameters parsing and invocation
        String respCode = service.invoke(event, requestMap, request,
response);

        // pull out the service response from the request attribute
        Map<String, Object> attrMap =UtilHttp.getParameterMap(request);
        //Map<String, Object> attrMap =
UtilHttp.getJSONAttributeMap(request);

        // create a JSON Object for return
        //JSONObject json = JSONObject.fromObject(attrMap);
        JSONObject json = JSONObject.fromObject(attrMap);
        String jsonStr = json.toString();
        if (jsonStr == null) {
            throw new EventHandlerException("JSON Object was empty; fatal
error!");
        }

        // set the X-JSON content type
        response.setContentType("application/x-json");
        // jsonStr.length is not reliable for unicode characters
        try {
            response.setContentLength(jsonStr.getBytes("UTF8").length);
        } catch (UnsupportedEncodingException e) {
            throw new EventHandlerException("Problems with Json encoding",
e);
        }

        // return the JSON String
        Writer out;
        try {
            out = response.getWriter();
            out.write("<input type='text' value='cbub2' id='ess'/>");
            //out.write(jsonStr);
            out.flush();
        } catch (IOException e) {
            throw new EventHandlerException("Unable to get response writer",
e);
        }

        return respCode;
    }

}

-------------------------------------------------------------------

*the js script :
-------------------------------------------------------------------
//Event.observe(window, 'load', function() {
//    var validateForm = new Validation('serviceTestForm', {immediate: true,
onSubmit: false});
//    Event.observe('submitBtn', 'click', function() {
//       if (validateForm.validate()) {
//    	   alert('La requête a échoué avec respect....')
//           //testerFct();
//       }
//    });
//});

Event.observe('submitBtn', 'click', function() {
 	   alert('La requête a échoué avec respect....')
    }

//new Ajax.Request("/youreRequestHere", {
//    method: "get",
//    parameters: {"parameter": "data23"},
//    onSuccess: function(transport){
//        var jsonData =
//transport.responseText.evalJSON();
//        //here you can update you're div with the data
//
//    }
//}); 


function testerFct() {
    var request = $('serviceTestForm').action;
    new Ajax.Request(request, {
        asynchronous: true,method:'get',
        onSuccess: function(transport) {
    	//alert('La requête a été bien envoyée...')
    	var toto=transport.responseText.evalJSON();
    	$('zonetexte').value=toto;
    	
            //here we delete our main function
        }, 
        onFailure: function(transport) {
        	alert('La requête a échoué avec respect....')
                //here we delete our main function
            },
        parameters: $('serviceTestForm').serialize(), requestHeaders:
{Accept: 'application/json'}
    });
}

//getServerError = function (data) {
//    var serverErrorHash = [];
//    var serverError = "";
//    if (data._ERROR_MESSAGE_LIST_ != undefined) {
//        serverErrorHash = data._ERROR_MESSAGE_LIST_;
//
//        serverErrorHash.each(function(error) {
//            if (error.message != undefined) {
//                serverError += error.message;
//            }
//        });
//        if (serverError == "") {
//            serverError = serverErrorHash;
//        }
//    }
//    if (data._ERROR_MESSAGE_ != undefined) {
//        serverError += data._ERROR_MESSAGE_;
//    }
//    return serverError;
//};


-------------------------------------------------------------------
*the client side page :
--------------------------------------------------------------------
<form id="serviceTestForm"  method="GET">
<table valign="center">

	<tr>
		<td>Zone de réponse AJAX </td>
		<td id="zonetexte2"><input type="text" id="zonetexte" name="zonetexte"
value=""/> </td>
		

	</tr>
	<tr>
		<td>just to test the service module without Ajax... </td>

	</tr>
	
		<tr>
		<td>
		<label>Salutation:
		<input type="text" name="salutation" id="salutation" value=""/>
		</label>
         </td>
         </tr>
         <tr>
		<td>
		<label>Nom:
		<input type="text" name="lastName" id="lastName" value=""/>
		</label>
         </td>
         </tr>
         <tr>
         <td>
       	<label>Nom Intermédiaire:
		<input type="text" name="middleName" id="middleName" value=""/>
		</label>
         </td>
         </tr>
         <tr>
         <td>
         <div id="pagePP" name="pagePP"> 
		<label>Prénoms:
		<input type="text" name="firstName" id="firstName" value=""/>
		</label>
		</div> 
         </td>
         </tr>
         <tr>
         <td>
         <label>Suffixe:
		<input type="text" name="suffix" id="suffix" value="" />
		</label>
         </td>
		</tr>
		
		<tr>
		<td>
         <label>
		<input type="button" name="submitBtn" id="submitBtn"
onclick="testerFct();" value="Enrégistrer"/>
		</label>
         </td>
		</tr>	
</table>

</form>






--------------------------------------------------------------------

 and in my controller ...
------------------------------------------------------
..
...

<request-map uri="testServiceAjax">
    	<security https="false" auth="false"/>
    	<event type="java" invoke="invoke"  path="src.TestClass"/>
    	<response name="success" type="none" />
    	<response name="error" type="none" />
</request-map>
..
...


------------------------------------------------------


thank for having a look of those and tell me my mistakes ... or anything  i
must perform...



PS: in  your last post you were talking about a simple way to use the ajax
request by preparing a normal screen and update the div after the ajax
resquest completed
can you please give me a simple example about that ...

-- 
View this message in context: http://ofbiz.135035.n4.nabble.com/AJAX-JSON-response-tp2274772p2277896.html
Sent from the OFBiz - User mailing list archive at Nabble.com.

Re: AJAX JSON response

Posted by Sascha Rodekamp <sa...@googlemail.com>.
I use the normal java event handler when working with json objects. You can
pass the JSON String/ Array as normal parameter to your Event. In the Event/
Service you can simply parse the parameter String into a JSON Object:
    JSONObject jsonObject = JSONObject.fromObject(jsonStringFromParameter);

Do some stuff with the jsonObject change/edit/add Data and transform back to
a String.

This String can be written into your response Object.
    1) Set the Content Type to "application/x-json"
        response.setContentType("application/x-json");
    2) set the Content length
        response.setContentLength(jsonString.getBytes("UTF8").length);
    3) Get the response writer and write the json String to your response
Object

If your calling the Event/ Service with an Ajax Request you can user the
evalJSON() Method.
new Ajax.Request("/youreRequestHere", {
                        method: "get",
                        parameters: {"parameter": "data23"},
                        onSuccess: function(transport){
                            var jsonData =
transport.responseText.evalJSON();
                            //here you can update you're div with the data

                        }
                    });

The controller entry looks like this

    <request-map uri="youreRequestHere">
        <security auth="false" https="false" />
        <event type="java" invoke="yourEventHere" path="x.y.z"/>
        <response name="success" type="none" />
        <response name="error" type="none" />
    </request-map>

BTW: why you're working with JSON Data when you want simply update a div?
Creat a normal Screen and a normal controller entry which calls the screen.
Then Do you're Ajax Request, the response will be the difined Screen which
you can insert / replace in your're div you wan't to update.

Cheers
Sascha

2010/7/1 Levenimeux <ya...@gmail.com>

>
> thanks sasha for your answer
>  but can you explain me more how to parse my arguments to the event/service
> (i guess you mean minilang or java classes to invoke). by the way after
> posting my question i was trying to use the JSONJavaHandler when firing
> request to my uri....but now after reading your answer  i get a quetion
> about this ....do i have to use necessarly the DojoJSONserviceHandler or
> can
> i use the JSONJavaHandler instead and if this is the case do i have to do
> some modifications ???  i suppose that if i use the DojoJSONserviceHandler
> like you propose i have to write a service (in minilang or even java). if
> we
> consider those conditions are verified  how do i have to write my urimap in
> the controller i mean
> ---------------------------
>  < request-map type="java or service according to the service ive wrote"
> path="my service or java class path"  invoke="the method to invoke if
> event">
> <response name="succes" type="request" value="in the biginning ive used
> json
> but i had the kind of result ive described before and after  i used /view
>  >
> --------------------------
> but i guess i don't get it the best way because it not work as it must (
> now
> the downloadable file ive described before don't popup anymore)
>  now can you explain me the right request-map i have to write (when using
> the DojoJSONserviceHandler or even just the JSONjavaHandler and how to use
> them)
> if it possible can you send me just an example (project or url) using the
> way youre describing and the related configurations...
> thank alot for advance .....
> --
> View this message in context:
> http://ofbiz.135035.n4.nabble.com/AJAX-JSON-response-tp2274772p2275011.html
> Sent from the OFBiz - User mailing list archive at Nabble.com.
>



-- 
Sascha Rodekamp
   Lynx-Consulting GmbH
   Johanniskirchplatz 6
   D-33615 Bielefeld
   http://www.lynx.de

Re: AJAX JSON response

Posted by Levenimeux <ya...@gmail.com>.
thanks sasha for your answer
 but can you explain me more how to parse my arguments to the event/service
(i guess you mean minilang or java classes to invoke). by the way after
posting my question i was trying to use the JSONJavaHandler when firing
request to my uri....but now after reading your answer  i get a quetion
about this ....do i have to use necessarly the DojoJSONserviceHandler or can
i use the JSONJavaHandler instead and if this is the case do i have to do
some modifications ???  i suppose that if i use the DojoJSONserviceHandler
like you propose i have to write a service (in minilang or even java). if we
consider those conditions are verified  how do i have to write my urimap in
the controller i mean 
---------------------------
 < request-map type="java or service according to the service ive wrote"
path="my service or java class path"  invoke="the method to invoke if
event">
<response name="succes" type="request" value="in the biginning ive used json
but i had the kind of result ive described before and after  i used /view  >
--------------------------
but i guess i don't get it the best way because it not work as it must ( now
the downloadable file ive described before don't popup anymore)
  now can you explain me the right request-map i have to write (when using 
the DojoJSONserviceHandler or even just the JSONjavaHandler and how to use
them) 
if it possible can you send me just an example (project or url) using the 
way youre describing and the related configurations...
thank alot for advance .....
-- 
View this message in context: http://ofbiz.135035.n4.nabble.com/AJAX-JSON-response-tp2274772p2275011.html
Sent from the OFBiz - User mailing list archive at Nabble.com.

Re: AJAX JSON response

Posted by Sascha Rodekamp <sa...@googlemail.com>.
Hi,
have a look at the DojoJSONServiceEventHandler.

The Way is simple pass your Arguments to your Event/ Service parse them into
a Jason Object (have a look here http://www.json.org/java/).
Do what ever you want :-)

And write back the result to the response Object.

Now you can work with the JSON Object in your Client.

I hope i could help
Cheers
Sascha

2010/7/1 Levenimeux <ya...@gmail.com>

>
> "Hi everybody ;
> i'm  an ofbiz framework beginner developper and in the application i'm
> developping i need to use AJAX in the client side. i'm now try to use Json
> for the response but i get no result . when i fire a request to the
> controler , instead of  updating the div i've prepared in the client side
> page i get a downlodable file wich content is the following one :
> -----------------------------------------------------
>
> {"targetRequestUri":"/testServiceAjax","_CONTEXT_ROOT_":"C:\\workspace\\ofbiz\\hot-deploy\\practice\\webapp\\practice\\","javax.servlet.request.key_size":128,"_FORWARDED_FROM_SERVLET_":true,"javax.servlet.request.ssl_session":"4c2b3a693e0b8204df23eb50f3c5bfe89ab1ae92c9d134be9b3d55fe55f5e284","_REQUEST_FROM_SPIDER_":"N","_SERVER_ROOT_URL_":"
> https://localhost:8443
> ","_LOGIN_PASSED_":"TRUE","_CONTROL_PATH_":"/practice/control","javax.servlet.request.cipher_suite":"SSL_RSA_WITH_RC4_128_MD5","thisRequestUri":"json"}
> --------------------------------------------------------
>  then  i suppose that i have this type of response because in my webapp
> controller there is no handler for the type Json .so  i search in ofbiz for
> any handler of the json  type and i find as reponse the common-controller
> of
> the common component in ofbiz (common
> /webcommon/webinf/common-controller.xml). while reading this controller and
> looking for any handler of the json type i found this comment :
> --------------------------------------------------
> <!-- These event handlers have been deprecated, if you need to send json
> responses then chain
>         the json request from this controller after calling your event
>    <handler name="jsonservice" type="request"
> class="org.ofbiz.webapp.event.JSONServiceEventHandler"/>
>    <handler name="jsonservice-multi" type="request"
> class="org.ofbiz.webapp.event.JSONServiceMultiEventHandler"/>
>    <handler name="jsonsimple" type="request"
> class="org.ofbiz.webapp.event.JSONSimpleEventHandler"/>
>    <handler name="jsonjava" type="request"
> class="org.ofbiz.webapp.event.JSONJavaEventHandler"/>
>     -->
> --------------------------------------------------
> so i make a copy of the last line in this comment to my app controller but
> i
> get the same response as described before... so now i have no idea of how
> to
> use this Json type in my webapp controller ...
>  can anyone explain me the  meaning of the comment i found in the
> common-cotroller or
> can anyone explain me the way to use Ajax with the JSON type in the
> controller  and some link about the subject will be welcome
> thank for advance ....  "
>
> --
> View this message in context:
> http://ofbiz.135035.n4.nabble.com/AJAX-JSON-response-tp2274772p2274772.html
> Sent from the OFBiz - User mailing list archive at Nabble.com.
>



-- 
Sascha Rodekamp
   Lynx-Consulting GmbH
   Johanniskirchplatz 6
   D-33615 Bielefeld
   http://www.lynx.de