ofbiz-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Levenimeux <yassine.elkachch...@gmail.com>
Subject Re: AJAX JSON response
Date Sun, 04 Jul 2010 20:33:13 GMT

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.

Mime
View raw message