0

I have modified my code to make use of callback functions to return value however i think there is still an error. I am not able to access the value from my callback even though its returning one as i can see in the console logs.

Javascript

function postToServer(ajaxSuccessFn) {
    var Employee = {
        //some data
    };
    console.log('inside post to server');

    try {
        dojo.xhrPost({
            url: 'hello',
            content: Employee,
            load: ajaxSuccessFn,
            error: function (e) {
                console.log('Error Occured ' + e);
            }
        });

    } catch (e) {
        console.log(e);
    }

};

function handleServerResponse(containers, Callback) {

    var formErrors = {
        "errors": "yes",
        "firstName": "1234",
        "surname": "456",
        "otherNames": "789",
        "bSurname": "10025"
    };

    console.log('handling server error obj');

    try {
        $.each(formErrors, function (key, value) {

            if (key == 'errors') {

                hasErrors = value;
                console.log('hasErrors set to ' + value);
            }
        });

    } catch (e) {
        console.log(e);
    }

    try {
        if (hasErrors == true) {
            //alert('form has errors');
            for (var i = 0; i < containers.length; i++) {

                console.log('Processing container number ' + i + ' with name ' + containers[i]);
                var processingContainer = containers[i];

                dojo.forEach(processingContainer.getChildren(), function (wid) {
                    var widgetName = wid.attr('id');


                    $.each(formErrors, function (key, value) {

                        if (key == widgetName && value.length > 0) {

                            var myWidget = dijit.byId(widgetName);
                            var wdgName = dijit.byId(widgetName).attr("id");
                            var myWidgetValue = value;
                            //console.log('Printing here '+wdgName +' : '+myWidgetValue);

                            myWidget.validator = function () {
                                console.log('Attribute Name is :' + wdgName + ' Error Value is : ' + myWidgetValue);
                                //console.log(wdgName + " : "+myWidgetValue);
                                this.set("invalidMessage", myWidgetValue);
                            };
                            myWidget._hasBeenBlurred = true;
                            myWidget.validate();

                        }

                    });

                });

                console.log('done ' + hasErrors);
            }
        }

    } catch (e) {
        console.log(e);
    }

    console.log('function returning hasErrors as ' + hasErrors);
    return hasErrors;
}

function PostNameInformation() {

    var containers = [byId("container1"), byId("container2")];

    try {
        var doesErrorsExist = postToServer(handleServerResponse(containers, function (args) {
            return args;
        }));
        console.log('Were there any errors ' + doesErrorsExist);
    } catch (e) {
        console.log(e);
    }
}
devdar
  • 5,564
  • 28
  • 100
  • 153
  • 1
    While you can return something in a callback, in this case it will be ignored completely. I am not sure what you mean by 'preventing the page from moving', but while doing an AJAX request, there is nothing you can do except for waiting for the result. You could preemtively stop the page 'from moving' when you start the request and then onblock it once the success callback has been called. But there is no sense in returning something out of an anonymous request success callback. – Tim Apr 21 '14 at 15:40
  • Is there anyway i can set a value in the callback function and access it outside the function? – devdar Apr 21 '14 at 15:53
  • returning true of false stops the page from moving onto another page since the function that calls the other page does the ajax request before and if there are any errors then it stops the page – devdar Apr 21 '14 at 15:55
  • Of course there is. But it would be better to directly call another function instead of setting a variable that other functions then have access to. You don't want to start using globals to keep track of your async state. That'll open pandora's box. Instead, you need to start thinking about something that helps you to manage async control flow. Promises are one way to do it, but not the only or necessarily the best way. – Tim Apr 21 '14 at 15:55
  • If you want to prevent navigating to another page upon for example clicking a link, you will need to call `event.preventDefault()` and then handle the redirect manually once the result of the ajax request is in. – Tim Apr 21 '14 at 15:56
  • no it isnt a redirect i am using dojo form wizard and there is a passFunction attached to the 'next' button. The developer defines what can be in that function and at the end returning a true or false determine if the next page from the form wizard can be called. If false page doesnt move if true the other page is called. The developer can do validation in this function. What i did was i passed data from the first page to the database and in the success function i handled errors. – devdar Apr 21 '14 at 16:03
  • So now there there are errors from the object passed back into the call back function i am now tring to get the passFunction to return false. I hope that clears it up a bit – devdar Apr 21 '14 at 16:04
  • @TheShellfishMeme i modified my question after some research and you advice i realized i needed to separate the ajax request however i am not getting a value returned – devdar Apr 21 '14 at 18:20
  • @JasonP i sorted out the issue with the callback function however i am noticing the ajax request callback function returns a value after the entire ProcessInformation() completes what can i do to work around this ? I would like if the callback function can return a value then allow the ProcessInformation() function to competed – devdar Apr 21 '14 at 19:13
  • @devdar `ProcessInformation()` needs to accept a callback or return a promise as well. – Jason P Apr 21 '14 at 19:24
  • @Jason P Would i need to call ProcessInformation() inside the AjaxRequestNameDetails(function (hasErrors) function? I am just abit lost – devdar Apr 21 '14 at 19:33
  • I think the concept of async functions is too complex for a comment. Read through and understand the duplicate I posted. I think that where you're getting hung up is that if you call an async function, any functions calls up the stack need to be handled in an async manner as well. – Jason P Apr 21 '14 at 19:37
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/51135/discussion-between-devdar-and-jason-p) – devdar Apr 21 '14 at 23:22
  • I modified the code making use of the callback functions however i think i may have an error somewhere. – devdar Apr 22 '14 at 16:58

0 Answers0