I have lot of HTML pages containing links to same URL address like this:
<a href="http://example.com/page.php?params=1">Link</a>
The question is: Can I return a javascript response instead of plain HTML that can be executed by clicking on a link?
For example, I tried this in page.php
:
header("Location: javascript:alert(1)", true, 302);
but it doesn't work. If I send the HTML page containing the required javascript, then the browser opens a new page or replaces the current page with this blank page containing the JS.
Is there any other method to do this without changing link's href? It seems like it can't because of security restrictions.
No, you cannot invoke JavaScript from the server-side. You can, however, have JavaScript loaded that makes calls to the server and retrieves data.
With that in mind you can have a call to retrieve JSON or XML from the server in which a payload resides that can be extracted by a JavaScript function that is already defined on the client-side.
// note: in this example I use jQuery because their AJAX API is terrific
$.ajax({
url: "http://example.com/page.php?params=1"
})
.done(function( data ) {
// data is our payload
doSomethingWithPayload(data);
});
That way doSomethingWithPayload
already is defined on the client, and is called whenever the payload is received.