The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Read an AJAX request’s numeric HTTP status in PhantomJS from page.onResourceReceived, using response.status. Filter on response.url to select the endpoint you need, and inspect response.stage because a large response can produce more than one callback. Do not use the value passed to page.open as an AJAX status: that callback reports only whether the page load succeeded or failed.
The callback that contains the AJAX status
PhantomJS reports responses for resources loaded by a page through page.onResourceReceived. Each response object includes the resource URL, an identifier, a callback stage, the numeric HTTP status, and status text. The status field is the value you want—for example, 200, 404, or another code returned by the server.
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);
});
Replace /api/ with a path, host, query fragment, or other test that identifies the endpoint in your application. The filter is only an example; PhantomJS invokes this handler for resources generally, not exclusively for XMLHttpRequest or fetch traffic.
Why page.open returns only success or fail
The second argument to page.open is called after PhantomJS attempts to load the document. Its argument is a page-load result such as 'success' or 'fail'. It answers “did the page load?” rather than “what status did this particular AJAX request return?”
#1 Best Overall
- Use
page.open’s callback to decide whether the top-level navigation completed. - Use
onResourceReceivedto read an individual resource’s HTTP metadata. - Use
onResourceErrorwhen PhantomJS cannot load a resource and therefore has no normal response object to inspect.
A page can load successfully while an API call returns an error, and a page-load failure does not identify every resource that failed. Keep these events separate in your logging and control flow.
How to identify the correct AJAX request
Filter by URL
The response.url property lets you associate a response with an endpoint. A precise host-and-path test is safer than a broad substring when several services use similar names.
var targetHost = 'https://example.com';
var targetPath = '/api/orders';
page.onResourceReceived = function (response) {
if (response.url.indexOf(targetHost + targetPath) === 0) {
console.log(JSON.stringify({
id: response.id,
url: response.url,
stage: response.stage,
status: response.status,
statusText: response.statusText
}));
}
};
Log every response while discovering traffic
If you do not yet know the exact endpoint, temporarily log all responses. Load the page, trigger the action that makes the AJAX call, then narrow the filter after you see the URLs.
page.onResourceReceived = function (response) {
console.log(response.id + ' ' + response.stage + ' ' +
response.status + ' ' + response.url);
};
Remember that scripts, stylesheets, images, documents, and other resources appear in the same callback. URL matching is what separates the API response from the rest of the page’s traffic.
Record the request identity
Store response.id with the URL and status. The identifier helps you correlate multiple events for the same resource and distinguish simultaneous requests to the same endpoint.
Rank #2
Understand stage and repeated callbacks
PhantomJS documents response stages such as start and end. A large response delivered in multiple chunks can invoke onResourceReceived once per chunk, so one request is not guaranteed to produce one callback.
Capture the final status
For a compact result, process the terminal event when the runtime reports end. Keep a fallback for runtimes or responses where the stage is not what you expect.
var seen = {};
page.onResourceReceived = function (response) {
if (response.url.indexOf('/api/orders') === -1) {
return;
}
if (!seen[response.id]) {
seen[response.id] = [];
}
seen[response.id].push({
stage: response.stage,
status: response.status,
statusText: response.statusText,
url: response.url
});
if (response.stage === 'end') {
console.log('Final status for resource ' + response.id + ': ' +
response.status + ' ' + response.statusText);
}
};
When you need a complete trace
Keep every record instead of overwriting it. A trace can show when a response began, whether chunks arrived, and which status PhantomJS reported on each event. Do not count callback invocations as request counts unless you group them by response.id.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallHandle resources that fail to load
If PhantomJS cannot load a resource, onResourceError supplies an error description rather than normal response metadata. The callback exposes the resource id, its url, an errorCode, and an errorString.
page.onResourceError = function (error) {
if (error.url.indexOf('/api/') !== -1) {
console.log('Resource failed: ' + error.url);
console.log('Error code: ' + error.errorCode);
console.log('Error: ' + error.errorString);
console.log('Resource #' + error.id);
}
};
This is different from an HTTP response such as a server-generated 404 or 500. A transport, certificate, DNS, or connection problem may prevent PhantomJS from receiving an HTTP status at all, so report the error callback separately.
A complete diagnostic script
The following script logs page-load state, matching response events, and load errors. It waits for the page to open, but the response handler remains active while the page runs.
var webpage = require('webpage');
var system = require('system');
var page = webpage.create();
var target = system.args[1] || 'https://example.com';
var endpointPart = system.args[2] || '/api/';
page.onResourceReceived = function (response) {
if (response.url.indexOf(endpointPart) === -1) {
return;
}
console.log(JSON.stringify({
type: 'response',
id: response.id,
stage: response.stage,
url: response.url,
status: response.status,
statusText: response.statusText
}));
};
page.onResourceError = function (error) {
if (error.url.indexOf(endpointPart) === -1) {
return;
}
console.log(JSON.stringify({
type: 'resource-error',
id: error.id,
url: error.url,
errorCode: error.errorCode,
errorString: error.errorString
}));
};
page.open(target, function (loadStatus) {
console.log(JSON.stringify({
type: 'page-load',
url: target,
status: loadStatus
}));
});
Run it with a page URL and an identifying endpoint fragment, for example phantomjs inspect.js https://example.com /api/orders. Triggering the AJAX action may require page interaction or JavaScript executed through PhantomJS; the network callbacks only observe traffic that the page actually generates.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Troubleshooting common results
No AJAX line appears
- The URL filter is too strict. Log every
response.urlfirst, then adjust it. - The request occurs after your script exits. Keep PhantomJS running until the action and response complete.
- The page uses a different origin, redirect, or query string. Match the actual URL shown in the diagnostic log.
You see several lines for one request
Group events by response.id and inspect stage. Chunked delivery can produce multiple callbacks; treat the end event as the completion point when available.
page.open says success but the API failed
That is expected when navigation succeeded independently of an AJAX error. Read the API’s response.status in onResourceReceived.
There is no numeric status
Check onResourceError. A resource that never receives an HTTP response is represented by an error code and message instead.
Rank #4
HTTPS behaves differently
PhantomJS troubleshooting advises checking that its SSL libraries, usually OpenSSL, are installed and working. A TLS setup problem can prevent a response from reaching onResourceReceived.
Status appears unexpected
Log the complete URL, including query parameters, the resource ID, stage, status text, and error events. The documented API defines status as the HTTP status code (with 200 as an example), but behavior for every non-2xx case is not established by the reference material; verify the target PhantomJS runtime with your endpoint.
Operational guidance and limitations
- Use URL and resource ID together; URL alone may match concurrent calls.
- Do not infer request counts from callback counts because chunked responses repeat events.
- Keep page-load, response, and resource-error records in separate fields so monitoring can distinguish navigation failures from API failures.
- PhantomJS 1.2 release notes (June 21, 2011) describe sniffing resource requests and responses with
onResourceRequestedandonResourceReceived. Treat the runtime as historical software and validate scripts against the exact binary and environment you operate.
Or skip the browser setup
If your goal is a reliable image or PDF of a page rather than inspecting PhantomJS network events, ScreenshotNeo provides a single HTTP request. Its capture pipeline accepts cookie and consent banners as a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. It also provides an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for request options. The free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.FAQ
Can I get the AJAX status inside the page’s own JavaScript?
The documented PhantomJS method is the outer page object’s onResourceReceived callback, where the response metadata is exposed.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Should I treat every response callback as a completed request?
No. Check stage and correlate events by id; chunked responses can generate several callbacks.
Best Value
What should I store for later debugging?
Store the resource ID, URL, stage, status, status text, and any matching resource-error fields. This preserves enough context to separate duplicate requests and transport failures.
Does a failed AJAX request always have an HTTP status?
No. If PhantomJS cannot load the resource, use onResourceError; the failure may occur before an HTTP response exists.
Frequently Asked Questions
Can I get the AJAX status inside the page’s own JavaScript?
The documented PhantomJS method is the outer page object’s onResourceReceived callback, where the response metadata is exposed.
Should I treat every response callback as a completed request?
No. Check stage and correlate events by id; chunked responses can generate several callbacks.
What should I store for later debugging?
Store the resource ID, URL, stage, status, status text, and any matching resource-error fields.
Does a failed AJAX request always have an HTTP status?
No. If PhantomJS cannot load the resource, use onResourceError; the failure may occur before an HTTP response exists.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Recommended Free Tools

