How to Get AJAX Response Status Codes in PhantomJS
Read numeric AJAX HTTP status codes in PhantomJS with onResourceReceived, match URLs, handle multi-stage events, and debug failed resources.

Use PhantomJS’s page.onResourceReceived callback and read response.status. Match response.url to the AJAX endpoint you care about, and inspect response.stage because a large response can produce more than one callback. The page.open callback only reports overall page-load success or failure; it does not provide the numeric status of an individual AJAX response.
The central pattern is:
var webpage = require('webpage');
var page = webpage.create();
page.onResourceReceived = function (response) {
if (response.url.indexOf('/api/') !== -1) {
console.log('URL: ' + response.url);
console.log('HTTP status: ' + response.status + ' ' + response.statusText);
console.log('Resource #' + response.id + ', stage: ' + response.stage);
}
};
page.open('https://example.com', function (loadStatus) {
console.log('Page load: ' + loadStatus); // success or fail
});
This uses the documented onResourceReceived fields. Change the URL filter to match the application you are investigating.
What each PhantomJS callback tells you
| Callback | What it represents | What to read |
|---|---|---|
page.open(url, callback) |
Overall page-load result | loadStatus, usually success or fail |
page.onResourceReceived |
Response metadata for resources loaded by the page, including AJAX requests | response.url, response.status, response.statusText, response.id, and response.stage |
page.onResourceError |
A resource that could not be loaded | errorCode, errorString, id, and url |
The official reference describes status as the HTTP status code and gives 200 as an example. The page.open documentation describes a page-level load status instead. These are different layers, so replacing one callback with another loses the information you need.
Build a useful AJAX status logger
1. Filter the resource URL
onResourceReceived is not limited to XHR or Fetch responses. It can receive metadata for many resource types, including documents, scripts, stylesheets, images, and API calls. A URL filter keeps the log focused:

var apiPattern = /\/api\/|graphql|\.json(?:\?|$)/i;
page.onResourceReceived = function (response) {
if (!apiPattern.test(response.url)) {
return;
}
console.log(JSON.stringify({
url: response.url,
status: response.status,
statusText: response.statusText,
id: response.id,
stage: response.stage
}));
};
Use a host-and-path check when the page talks to several services. For example, compare the parsed URL’s host and pathname if your PhantomJS version and script environment provide a URL parser. A simple substring or regular expression is often sufficient, but avoid matching a common word that appears in unrelated asset URLs.
2. Record both callback stages
PhantomJS documents start and end stages. Large responses delivered in chunks can invoke onResourceReceived more than once. Do not assume one callback equals one request. Log the resource ID and stage, then treat the end record as the final response metadata when you need one result per resource.
var responses = {};
page.onResourceReceived = function (response) {
if (response.url.indexOf('/api/') === -1) {
return;
}
if (!responses[response.id]) {
responses[response.id] = [];
}
responses[response.id].push({
url: response.url,
status: response.status,
statusText: response.statusText,
stage: response.stage
});
console.log('resource=' + response.id +
' stage=' + response.stage +
' status=' + response.status +
' url=' + response.url);
};
If you only print a status when stage === 'end', make sure your target runtime actually supplies that stage for the resources you care about. The documentation warns about multiple records, but this research does not establish universal behavior for every non-2xx response or every PhantomJS build.
3. Handle resources that never produce a response
A DNS failure, connection refusal, TLS problem, or other load error may invoke onResourceError instead of producing normal response metadata. The callback has a different shape:
page.onResourceError = function (error) {
console.log(JSON.stringify({
type: 'resource-error',
id: error.id,
url: error.url,
errorCode: error.errorCode,
errorString: error.errorString
}));
};
The onResourceError reference defines these fields. An error callback is not an HTTP response with a status such as 404 or 500; it describes why PhantomJS could not load the resource at all.
Complete runnable PhantomJS example
Save this as ajax-status.js, replace the page URL and endpoint pattern, then run it with your PhantomJS executable.
var webpage = require('webpage');
var system = require('system');
var page = webpage.create();
var targetUrl = system.args[1] || 'https://example.com';
var apiPattern = /\/api\/|graphql|\.json(?:\?|$)/i;
var seen = {};
page.onResourceReceived = function (response) {
if (!apiPattern.test(response.url)) {
return;
}
if (!seen[response.id]) {
seen[response.id] = [];
}
var record = {
type: 'response',
id: response.id,
stage: response.stage,
url: response.url,
status: response.status,
statusText: response.statusText
};
seen[response.id].push(record);
console.log(JSON.stringify(record));
};
page.onResourceError = function (error) {
if (!apiPattern.test(error.url)) {
return;
}
console.log(JSON.stringify({
type: 'error',
id: error.id,
url: error.url,
errorCode: error.errorCode,
errorString: error.errorString
}));
};
page.open(targetUrl, function (loadStatus) {
console.log(JSON.stringify({
type: 'page-load',
url: targetUrl,
status: loadStatus
}));
phantom.exit();
});
Run it with:
phantomjs ajax-status.js https://example.com
The page may start AJAX work after the initial load callback. If the application schedules requests later, wait for a known condition or a short delay before calling phantom.exit(). For example, set a timer after a successful page load:
page.open(targetUrl, function (loadStatus) {
console.log('Page load: ' + loadStatus);
window.setTimeout(function () {
phantom.exit();
}, 3000);
});
Use a page-specific signal when possible instead of an arbitrary delay. A delay can miss slow requests or keep the process alive longer than necessary.
Reading the output correctly
status: the numeric HTTP status exposed by the resource response.statusText: the accompanying status text when PhantomJS provides it.url: the requested resource URL, which lets you associate the response with an AJAX endpoint.id: the resource identifier used to correlate repeated records and errors.stage: the callback stage, commonlystartorend.
Do not infer that a successful page load means every API call succeeded. A page can render while an API returns an error, and a page-level failure does not tell you which resource caused it. Build your reporting around resource IDs and URLs.
Equivalent checks outside PhantomJS
If you only need to inspect an endpoint and do not need a browser to execute page JavaScript, a direct HTTP client is simpler. These examples do not reproduce browser cookies, JavaScript-generated headers, or the page’s request sequence.
cURL
curl -i -sS 'https://example.com/api/data'
The response headers include the HTTP status line. Add -L to follow redirects when that is part of the question you are answering.
Python
import requests
response = requests.get('https://example.com/api/data', timeout=30)
print(response.url)
print(response.status_code)
print(response.reason)
Node.js
const response = await fetch('https://example.com/api/data');
console.log(response.url);
console.log(response.status, response.statusText);
Use PhantomJS when the request is created by page JavaScript or depends on browser state. Use a direct client when the endpoint, authentication, and request method are already known.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
page.open prints only success or fail |
You are reading the page-level callback. | Inspect response.status inside onResourceReceived. |
| No AJAX records appear | The URL filter does not match the actual endpoint, or the request occurs after the script exits. | Log all resource URLs temporarily, broaden the pattern, and delay exit until the request is made. |
| The same resource appears several times | A response arrived in multiple chunks or at multiple stages. | Group by response.id, inspect stage, and use the final stage when appropriate. |
| A failed request has no HTTP status | The resource never completed an HTTP response. | Read onResourceError‘s errorCode and errorString. |
| HTTPS works in another client but fails in PhantomJS | The PhantomJS environment may have an SSL library or certificate compatibility problem. | Check that the SSL libraries, usually OpenSSL, are installed correctly, as recommended by the PhantomJS troubleshooting guidance. |
| Status is unexpected for a protected endpoint | The page may require cookies, authentication headers, a user agent, or a browser challenge. | Inspect the actual request requirements and configure the page before capture. Treat the observed behavior as runtime-specific. |
Performance, reliability, and cost considerations
Performance
Resource callbacks run while the page is loading. Keep handlers cheap: filter URLs early, write compact records, and avoid expensive parsing for every image or script. If you need a complete history, store records by resource ID and process them after the page exits rather than doing heavy work in the callback.
Waiting for a selector or application signal is usually more efficient than using a long fixed delay. A fixed delay can either miss a slow API response or waste time on fast pages. When collecting many pages, launch separate PhantomJS processes carefully and cap concurrency according to available CPU, memory, and the target site’s rate limits.
Reliability
Log the URL, ID, stage, status, and status text together. This makes repeated callbacks explainable and prevents records from different endpoints being merged. Preserve resource errors separately from HTTP responses. Also record the page-load result so an otherwise empty resource log is diagnosable.
PhantomJS’s callback contract is documented, but the supplied research does not verify every edge case for non-2xx responses or every historical binary. Run a small compatibility check against the exact PhantomJS version used in production, especially for TLS and large responses.
Cost
Running PhantomJS yourself usually means budgeting for the machine, process supervision, browser memory, network egress, retries, and maintenance. Direct HTTP clients are cheaper when browser execution is unnecessary. A hosted screenshot service can move browser operations out of your infrastructure, but compare billing rules carefully: a screenshot service may charge for captures even when a target page is blank or blocked.
Or skip the browser setup
If your actual goal is a clean image or PDF of a page rather than inspecting PhantomJS network events, ScreenshotNeo provides a single HTTP request. Its API accepts a URL and returns PNG, JPEG, WebP, or PDF. Cookie and consent banners are accepted and 60-plus known consent platforms, newsletter popups, and chat widgets are removed before capture; each step can be disabled.
Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response includes X-Page-Verdict and X-Billed headers. ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
See the ScreenshotNeo API documentation for all options.
cURL
curl -G 'https://api.screenshotneo.com/v1/shot' -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get('https://api.screenshotneo.com/v1/shot', params={'access_key': 'YOUR_API_KEY', 'url': 'https://stripe.com'}, timeout=90)
open('shot.webp', 'wb').write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Features include full-page captures with lazy images loaded, CSS-selector element shots, dark mode, device presets and custom viewports, retina scale, PDF paper and page controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification.
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account to start.
FAQ
Can I get an AJAX status from page.open?
No. Its callback reports page-load success or failure. Use onResourceReceived for a resource’s numeric HTTP status.

Is onResourceReceived limited to XMLHttpRequest?
No. It reports resource responses generally. Filter by URL, host, path, or another property that identifies the API call.
Why should I log stage?
A resource may generate multiple callbacks, including callbacks for different stages or chunks. The stage and resource ID let you correlate those records.
What if the endpoint returns 404 or 500?
Read the numeric value in response.status. The supplied documentation confirms the field and its purpose, but behavior for every non-2xx case should be checked against your PhantomJS runtime.
What callback covers DNS or TLS failures?
Use onResourceError. It supplies an error code and description when a resource cannot be loaded, rather than an HTTP response status.


