asim-ishaq
asim-ishaq

Reputation: 2220

Modifying Ajax post request data using dojo/notify api

I am trying to attach a Form data variable to Ajax Post Request using DOJO/NOTIFY. For example: there is a form which sends an item a = 10 to the server. Using dojo/notify (send) I attach another variable b=5 with the ajax post request but the problem is that it does not work and only a=10 is sent to server. Following is my code:

require(["dojo/request", "dojo/request/notify"], function (Request, Notify) {

    //Called before sending Ajax Request
    Notify("send", function (request) {
        dojo.byId("status").innerHTML = "Sending Ajax Request";
        /*
          At this point I want to add another form data item before 
          it is sent to Server.Example b = 5. The following is the 
          way to do it but It does not seem to work:
        */

        request.options.data += "&b=5";
        //I also tries the following but it also not working:
        //request.options.data.b = "5";     
    });

    Request.post("http://jsfiddle.net/",{
        data:{a:10}
    });
});

JSFIDDLE: http://jsfiddle.net/TEMA2/1/

Upvotes: 0

Views: 555

Answers (1)

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44665

dojo/request/notify was never made for these purposes. The response you get from it is only used for providing you a notification, it's not used in the request for further processing, so your modifications are actually ignored.

To intercept calls, you should rather be looking at the dojo/request/registry module, which you can use to register providers (which can be used as interceptors).

For example, if you want to add data to your request you could use:

Registry.register(function(url, options) {
    options.data.b = 5;
    return true;
}, Request, true);

Registry.post("/echo/json",{
    data:{a:10}
});

So in this case I'm sending a POST request with a=10, also notice that I'm no longer sending the request using the dojo/request module, but by using the dojo/request/registry module (I'm using Registry.post()).

This module will then look for an appropriate provider, and in this case we registered a provider that will always return true, which means it will always be used.

In that provider we're changing the options.data object and add an extra attribute to it. The other attributes in the Registry.register() function are:

  • Request: Tells the provider system that we want to use the dojo/request module to handle the call
  • true: Tells you that this provider should be used as the first provider (it has higher priority)

So in fact we add an extra abstraction layer to the request that makes intercepting calls possible.

I also updated your JSFiddle: http://jsfiddle.net/TEMA2/2/

Upvotes: 1

Related Questions