Casperjs: the secret to moving forward only when an ajax call response is received

I am trying to utilize casperjs for an ajax call that requires waiting for my server's response, which may take up to 3 minutes. However, I have encountered an issue where the casper.then function times out after exactly 30 seconds. I attempted adjusting casper.options.waitTimeout = 180000 /* 3 minutes */ in the code, and also experimented with a code block that consistently waits for 3 minutes regardless of the api call result.

It is essential for me to receive the data from the api call in order to proceed with the rest of my script, as the evaluate function only returns a boolean value every time and does not suffice. How can I ensure that the function waits for the full 3 minutes? There are numerous processes happening in the background that necessitate this extended wait period.

var casper = require('casper').create();

casper.start('mysite.html', function() {
});

casper.then(function() {
  result = getSomethingFromMyServerViaAjax( theId );
});

I also attempted an alternate method, but it consistently waits for 3 minutes irrespective of the speed at which the ajax call returns.

casper.waitFor(function check() {
    return this.evaluate(function() {
        return result = getSomethingFromMyServerViaAjax( theId ) /* this takes up to 3 minutes */;
    });
}, function then() {
   casper.log("Doing something after the ajax call...", "info");
   this.die("Stopping here for now", "error");
}, 180000 );

Although my ajax call functions correctly elsewhere within the 30-second timeframe, if it exceeds this limit, casper disregards the block and continues execution without waiting.

Answer №1

You came close to the solution. To activate your long-running call, you must use a trigger. Since it appears to be synchronous, I have enclosed it within setTimeout. The outcome will be posted in window.resultFromMyServerViaAjax after a brief delay.

this.evaluate also operates synchronously. Once executed, the wait step is queued to monitor if the window property has been initialized.

var casper = require('casper').create(),
    theId = "#whatever";

casper.start('mysite.html');

casper.then(function() {
    // trigger
    this.evaluate(function(theId){
        window.resultFromMyServerViaAjax = null;
        setTimeout(function(){
            window.resultFromMyServerViaAjax = getSomethingFromMyServerViaAjax(theId);
        }, 0);
    }, theId);
    this.waitFor(function check() {
        return this.evaluate(function() {
            return !!window.resultFromMyServerViaAjax;
        });
    }, function then() {
       casper.log("Executing tasks following the ajax call...", "info");
    }, function onTimeout() {
       this.die("Pausing here for now", "error");
    }, 180000 );
});
casper.run();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The current state of my DOM doesn't match the updated value in my model. The update is triggered by a function that is called when a button is clicked

app.controller('thumbnailController', function ($scope) { debugger $scope.customers = [ { name: 'Ave Jones', city: 'Phoenix' }, { name: 'Amie Riley', city: 'Phoenix&ap ...

Utilize a bot to scan through an array for specific elements

I'm currently working on a project to create a bot that can extract information from an info.json file and display it in the form of a rich embed within a Discord Channel. One challenge I've encountered is that my JSON file contains multiple arr ...

Issues with Angular updating the *ngFor Loop

I'm looking to showcase a lineup of upcoming concerts in my HTML, sourced from a web API (which is functioning correctly). The API is encapsulated within a ConcertService: @Injectable({ providedIn: 'root' }) export class ConcertService { ...

Mapping technologies provided by Google Maps Geocoding API are top-notch

I'm having an issue with the code below. It should display a map and a div section, but for some reason, it's not showing the marker point on the map. Can anyone provide assistance? Thank you in advance! <!DOCTYPE html> <html> <he ...

Hidden input fields do not get populated by Angular submit prior to submission

I am in the process of implementing a login feature in Angular that supports multiple providers. However, I have encountered an issue with submitting the form as the loginProvider value is not being sent to the server. Below is the structure of my form: &l ...

The Django CSRF token is inaccessible for retrieval

I'm in the process of developing a website using Vue.js for the frontend and Django for the backend. I've made sure to include the csrf token in every request from the frontend to the backend to prevent any 403 Forbidden errors. All requests are ...

How do I showcase the array value on top of a form using Javascript?

My current form displays errors using alerts, but I want to update it so that the errors are printed above the input fields for easy reference by users. This is the existing code for displaying errors: function showErrors() { if (errList.length >= ...

Can you explain the concept of cross domain and how JSONP fits into the picture?

As a beginner in .net programming, I have created a webservice where JavaScript calls the webservice in my code. I attempted to call it using my phone's browser while on the same network. It works perfectly with localhost, but when trying to call the ...

How can I choose an expandable element using Selenium?

I am currently facing issues while trying to select an element on a webpage using selenium. The element in question is expandable, and when clicked, it reveals other items/fields. Here is the code snippet for the element: <DIV class="section"> ...

Why isn't PHP's rawurlencode the same as JavaScript's escape function?

When I use urlencode or rawurlencode in PHP to encode the simple character § (paragraph), the result is "%C2%A7". However, using escape in JavaScript only produces "%A7". This creates encoding issues when transferring data between a PHP server and a JavaS ...

Tips for adding an item to an array within a Map using functional programming in TypeScript/JavaScript

As I embark on my transition from object-oriented programming to functional programming in TypeScript, I am encountering challenges. I am trying to convert imperative TypeScript code into a more functional style, but I'm struggling with the following ...

Tips for converting numbers in JavaScript and troubleshooting issues when trying to filter out non-numeric characters using Tel input commands

After finding this answer on how to convert digits in JavaScript, I attempted to apply the method to convert numbers in a phone number field with tel input type. function toEnglishDigits(str) { const persianNumbers = ["۱", "۲", &quo ...

Using Javascript to pass the value of a selected checkbox

I am having an issue with passing a row value to a different function when a user clicks on a checkbox in the last column of a table. The code I have written doesn't seem to be firing as expected. Can anyone help me figure out what might be missing in ...

Does the 'a' HTML tag secretly trigger window.location.assign?

Being relatively new to the online world, I have a simple question in mind. Imagine that I have a very basic a tag in my HTML: <a href="www.google.com"> Click me </a> What actually happens when I click on this link? Does the browser simply ...

"The Rails application.js file is in need of some required elements, and there seems to be an issue

I've encountered a strange issue with my rails app and AJAX. It seems that all of my AJAX form submits (via remote: true) are being sent twice, even though I only have one: <%= javascript_include_tag "application" %> In the application layout, ...

When refreshing the webpage, it becomes glitchy but then corrects itself

Currently working on a website, I've encountered a frustrating problem that has me scratching my head. This issue occurs across multiple pages; upon refreshing the page, the navbar, search bar, and other elements become completely disorganized. Stra ...

Which is better for a jQuery/Ajax Login Box: JSONP or CORS?

To create a login box that meets the specified criteria, the following must be taken into consideration: Develop it as a versatile UI Component that can be utilized in various sections of a website Allow for multiple instances of this component to coexis ...

Problematic Situation Arising from JavaScript AJAX and NVD3.JS Unresolved Object Error

I am currently in the process of developing a script that will allow me to retrieve data for my chart from an external PHP file. Initially, I attempted manually inputting the data into the chart and it worked perfectly fine. However, when I tried using A ...

Utilizing Javascript's every() method to verify if all elements in an array are integers

I am currently working on a function that needs to return true if an array contains all integers, and false if it does not. I am incorporating the every method for this purpose, which is documented on MDN here. For example, if the input is '1234&apos ...

What's the reason behind ng-click only functioning with a function and not an assignment within this specific directive?

I am currently working on creating a dynamic table using an array of objects that can be sorted by clicking the headers. I have a specific question regarding how the sorting feature is implemented. let myDirectiveTemplate = ` <table class="directiveTab ...