0

I am using a jQuery library called MockAjax which allows you to mock/test real AJAX calls.

In my application I can use my live app version of an AJAX request and MockAjax will intercept the AJAX request and respond with a Mock response!

I am also using another library called M<ockJson which is similar but instead allows you to generate a Mock JSON response.

Using both libraries together, my Application makes an AJAX request. MockAjax catches the AJAX request and then MockJson generates and returns a random JSON response.

In my past projects this has worked great with no issues until today...

Now that my application is working pretty good, I decided it;s time to restructure the JavaScript into a more structured version. (putting DOM events, tasks, etc into sections of code).

This is where my problem began....

In my new code,

  1. my App makes an AJAX request.
  2. MockAjax catches the AJAX request.
  3. MockJson is called to get the JSON response
  4. ERRORS this is where it all goes wrong...

At this last step, it should pass the JSON response back to the original AJAX calls Success function. It simply does not!

I get no errors or anything in the console. I set up a simple alert() in my AJAX calls success() function and it does not make it that far to even trigger the alert!

I am not sure if there is some sort of scope issue or what the problem could be. When my app was flat, all variables and functions in the glbal root level with no structure to the app at all...it all worked. As soon as I moved everything into Objects, etc....it all works except this 1 issue of not returning the MockAjax response back to the Real Ajax response!

I removed 95% of the app code and re-built it with just the very minimal to run this example problem. The demo of the problem is here... http://jsbin.com/vugeki/1/edit?js

App flow:

  • projectTaskModal.init(); is ran on page load
  • This fires off projectTaskModal.mockAjax.init(); which sets up the MockAjax and MockJson code
  • Then projectTaskModal.task.openTaskModal(projectTaskModal.cache.taskId); is ran which executes the AJAX request
  • AJAX POST Request is sent to /gettaskevents
  • MockAjax catches the request sent to /gettaskevents
  • MockAjax then calls MockJson to generate the JSON response. projectTaskModal.mockAjax.generateTaskEventsJson(); calls that function and I have it printing the JSON respionse into the console so I can see that it is generating it!
  • In my MockAjax code, var taskevents holds the JSON response and then set it to this... this.responseText = taskevents; ``this.responseTextI believe is what is supposed to be returned to the Applications originalAJAX` call. It seems that this is where the problem might be! It does not seem to be returning the response back to the original AJAX code that requested it in the first place!

Could this be some sort of scope issue?

var projectTaskModal = {

    cache: {
        taskId: 1,
        projectId: '12345',
    },


    init: function() {
        projectTaskModal.mockAjax.init();
      //console.log(projectTaskModal.mockAjax.init.generateTaskEventsJson());
        projectTaskModal.task.openTaskModal(projectTaskModal.cache.taskId);
    },


    task: {


        openTaskModal: function(taskId) {
            // Load Task Events/Comments Panel from AJAX Request
            projectTaskModal.task.loadTaskEventsPanel(taskId);
        },

        /**
         * Load Task Events/Comments from backend Database JSON
         * @param  {string} jsonServerEndpoint URL for AJAX to Request
         * @return {string} Generated HTML of all Task Events built from JSON
         */
        loadTaskEventsPanel: function(taskId) {


            // Request Task Events and Comments using AJAX Request to Server
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                url: '/gettaskevents',
                data: {
                    action: 'load-task-events',
                    task_id: projectTaskModal.cache.taskId
                },
                success: function(data) {

alert('TESTING AJAX SUCCESS CALLBACK WAS CALLED!');

                    console.log('function loadTaskEventsPanel(taskId) DATA: ');
                    console.log(data);

                    // Parse JSON data
                    var taskEventsJson = data;
                    var task_events = taskEventsJson.task_events;

                    // Loop over each Task Event record returned
                    $.each(task_events, function(i, event) {
                        console.log('commentID: ' + event.commentId);
                        console.log('create_at DateTime: ' + event.created_at);
                    });

                }
            });
        },

    },


    mockAjax: {
        init: function(){

          // Adding the @EVENT_TYPE keyword for MockJSON Template Usage
          $.mockJSON.data.EVENT_TYPE = [
              'Comment Created',
              'Task Status Changed',
              'Task Completed'
          ];



          // Mock AJAX response for AJAX request to /gettaskevents
          $.mockjax({
              url: '/gettaskevents',
              contentType: 'text/json',
              responseTime: 2900, // Simulate a network latency of 750ms
              response: function(settings) {
                  console.log('mockJax POST to /gettaskevents :');
                  //console.log(settings);
                  //DEBUG('Get Task Events JSON', settings.data);
                  if(settings.data.value == 'err') {
                     alert('MockAjax Error');
                     this.status = 500;
                     this.responseText = 'Validation error!';
                  } else {
                     alert('MockAjax Success');
                     //var taskevents = generateTaskEventsJson();
                     var taskevents =  projectTaskModal.mockAjax.generateTaskEventsJson();
                     this.responseText = taskevents;
                     console.log(taskevents);
                  }
              }
          });

        },



          // Generate Mock JSON Response to load fake Task Evewnt/Comments JSON for Mock AJAX request
          //var generateTaskEventsJson = function () {
          generateTaskEventsJson: function() {
            var mockTaskJson = $.mockJSON.generateFromTemplate({
            "task_events|10-14" : [{
                "commentId|+1" : 100000000,
                "projectId|+1" : 100000000,
                "taskId|+1" : 100000000,
                "userId|+1" : 100000000,
                "created_at" : "@DATE_YYYY-@DATE_MM-@DATE_DD",
                "event_type" : "@EVENT_TYPE",
                "userName" : "@MALE_FIRST_NAME @LAST_NAME",
                "description" : "@LOREM_IPSUM @LOREM_IPSUM"
              }]
            });
            //DEBUG('Generate Mock Task Events JSON', mockTaskJson.task_events);
            //console.log(mockTaskJson.task_events);
            //return mockTaskJson.task_events;
            return mockTaskJson;
          }







    },


};

$(function() {
    projectTaskModal.init();
});
JasonDavis
  • 48,204
  • 100
  • 318
  • 537
  • 1
    I'd strongly suggest you reduce your code to the smallest section of code that demonstrates what you're actually asking about. And, if you want more people to read and response to your question make the text in your question much more to the point about your actual question and describing what is going wrong in the code. – jfriend00 Apr 10 '15 at 00:46
  • Are you sure it is not executing the `success` callback, or is it perhaps erroring out somewhere? – prodigitalson Apr 10 '15 at 00:54
  • @prodigitalson in my asuccess callback I have a simple `alert()` set just to test if it is even getting called and it isn't. In my 1st link it all works. In my 2nd link where I re-arranged code into blocks, it doesn't return the MockAjax call to my real AJAX call – JasonDavis Apr 10 '15 at 01:27
  • Seems it might not be an issue with the code as 1 of my demo apps works fine on CodePen.io but has the problem described above when ran on JSBin – JasonDavis Apr 10 '15 at 03:10
  • I found part of the problem... the version running `jQuery v1.11.2` works great...the broken version was running `jQuery v 2.1.1` – JasonDavis Apr 10 '15 at 03:17

1 Answers1

1

Your JSBin example shows that you are using a very old version of Mockjax (1.5.0-pre). The latest is 1.6.2, released quite recently (I'm the core maintainer now). Below is a link to an updated JSBin where everything appears to be working just fine. The old version of Mockjax that you were running was created before jQuery 2.0 existed, and thus does not support it (1.6.2 does).

http://jsbin.com/qucudeleve/1/

So... update your Mockjax version to use Bower, npm, or just Rawgit (https://rawgit.com/jakerella/jquery-mockjax/master/jquery.mockjax.js) from the primary account (mine) versus your own fork which is extremely out of date!

Good luck.

Jordan Kasper
  • 13,153
  • 3
  • 36
  • 55