This is basically the opposite of fetch(), how do you make a non-cached request?.
Let's say we have client-side:
<div onclick="fetch('/data.php').then(r => r.text()).then(s => console.log(s));">Click me</div>
and server-side in PHP:
<?php echo "hello"; /* in reality, this can be much more data
and/or updated later with other content */ ?>
When clicking multiple times on Click me, the request is done multiple times over the network with request response code "200".
Thus, no caching has been done by the browser / by PHP:
How to prevent this data to be transferred multiple times if it is in fact not needed here?
Potential solution: Since /data.php can be updated on the server, the server could serve the data requests with a datetime metadata timestamp, that I could store in a client-side JS variable timestamp. Then before doing the next fetch request for /data.php, I could do a preliminary request
fetch('/get_last_modification_date.php').(r => r.json()).then(data => {
if (data['timestamp'] != timestamp)
fetch('/data.php')... // if and only if new data is here
});
Thus, we only do a fetch('/data.php')... if the timestamp of this data is more recent than the one we already had.
This would work, but it seems we are manually doing something that could be done by the browser+PHP cache mechanism.
How to ask PHP and the browser to do all this caching for us?
fetch() behaves the same as a regular HTTP request, so you can just apply the standard HTTP rules regarding caching.
For example you can use the If-Modified-Since mechanism, that I will explain.
When a server returns the following headers for a resource:
Cache-Control: no-cache
Last-Modified: <date in RFC2616 format>
then, on subsequent requests, the browser will send an If-Modified-Since header with the Last-Modified date.
If the server returns a 304 (Not Modified) status, then the browser will use the cached version of the resource.
Remark: despite its name, the no-cache directive doesn't mean that the resource can't be cached; it just means
that the browser must validate it with the server before using it.
To illustrate this, I will assume that you want to send the contents of some data.txt file:
<?php
// Get the modification time of the resource
$dataTime = filemtime('data.txt');
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
{
$sinceTime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
if($sinceTime==$dataTime)
{
// The browser already has the latest version of the resource
header('HTTP/1.1 304 Not Modified');
exit;
}
}
// Send the resource
header('Cache-Control: no-cache');
header('Last-Modified: '.gmdate('D, d M Y H:i:s T', $dataTime));
header('Content-Type: text/plain; charset=UTF-8');
readfile('data.txt');
?>
I see two solutions to this; and I've implemented both already throughout my applications, so they both work.
Solution A : Specify the cache value when using the fetch API, instead of just passing the link from which you want to fetch a given resource / post specific data / whatever.
Choose from default, no-store, reload, no-cache, force-cache or only-if-cached according to your needs, as explained in the first link.
Combine this with your mentioned timestamp to accordingly decide if the cache is still fresh/ stale etc. (as explained in the first link), and you're good to go.
Solution B : I've implemented in this in some scenarios where for example multiple kind of GET requests are allowed to the same endpoint, while however some requests (like GET https://example.org/api/v1/users) make subsequent ones, that are further narrowed down (like GET https://example.org/api/v1/users/employees/4), obsolete.
In such a scenario B, I initiate a JS object, like so:
const users = {};
Suppose I then for example fetch the users via GET https://example.org/api/v1/users, and that that requests also retrieves the employees for this API (for whatever reason) under an employees key.
I populate users with the retrieved data, hence also with an employees key, holding for example 5 employees.
Then, on subsequent requests, like GET https://example.org/api/v1/users/employees/4; I check for example in this case if the users object already retrieved the employees by doing stuff like:
if (!users.hasOwnProperty('employees')) { // Only fetch your data in this case }
To only make a request to the server if the data is not already present in my local js environment. You then may add a timestamp property to your users object according to your needs, and check in the condition above if the timestamp of subsequent requests is below that timestamp, e.g. the request should be retrieved from the local variable, and not from the server. This kind of mimicks your cache, it's the same principle.
Of course, solution B really depends on how you've setup your server responses etc., so I'd say solution A is the standard approach.
For further infos regarding solution A, you probably also want to have a quick read through when is a HTTP Request's cache still considered fresh?, or rather just checkout the entire HTTP Cache docs quickly.
And you may also want to have a look at this question, as the first answer shows an example of how you could also explicitly set the Cache-Control Header. In this sense; you should consider the value of the max-age key of the Cache-Control header you set as your timestamp. This is how browsers generally handle caching natively.
A simple way is to wrap the call to fetch
Ideally this would be in a class or closure, but global variables now for brevity’s sake.
var fetched = false;
function clickMe(someURL) {
if (fetched) { return; }
fetched = true;
fetch(someURL).then() // etc.
}
// onclick="clickMe('/data.php')"
use + Date.now() for unique requests;
and don't use static text in experiments like this ,use dynamic content in output:
i did my own experiment(in xampp windows) base on your question (in firefox) look in console and then in server's headers section ..
index.php :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="Custa">
<title></title>
</head>
<body>
<div onclick="fetch('data.php?'+ Date.now()).then(r => r.text()).then(s => console.log(s));">Click me</div>
</body>
</html>
data.php :
<?php
echo microtime(true);
?>
Related
I am trying to overwrite custom value to HTTP REFERRER. I got success with javascript but my client want in PHP and i need help in rewriting Javascript to PHP.
JS code :
var reff = ["http://example.com", "http://example.net", "http://example.org"];
var randomreff = reff[Math.floor(Math.random() * reff.length)];
delete window.document.referrer;
window.document.__defineGetter__("referrer", function () {
return randomreff;
});
document.write(document.referrer);
I am trying to rewrite this code in PHP or maybe finding a similar solution with PHP. i tried multiple way to do in PHP. these are some example.
PHP Try 1 :
$reff = new Arr("http://example.com", "http://example.net", "http://example.org");
$randomreff = get($reff, call_method($Math, "floor", to_number(call_method($Math, "random")) * to_number(get($reff, "length"))));
_delete(get($window, "document"), "referrer");
call_method(get($window, "document"), "__defineGetter__", "referrer", new Func(function() use (&$randomreff) {
return $randomreff;
}));
PHP with variable :
$var = 'var reff = ["http://example.com", "http://example.net", "http://example.org"];
var randomreff = reff[Math.floor(Math.random() * reff.length)];
delete window.document.referrer;
window.document.__defineGetter__("referrer", function () {
return randomreff;
});
';
PHP with header referer :
header("Referer: https://www.example.com/");
None of them worked. Help me to rewrite Javascript code or alternative solution with PHP.
You won't be able to do this with PHP exclusively. document.referrer is a DOM property that is set by the browser when the page loads by reading the referrer header on the request. Since the request is generated by the browser you can't really touch it with PHP since that is executed on the server and not in the browser, if you want to execute something in the browser you will need javascript.
In your examples you are just trying to run javascript-code from PHP it seems, and that just won't work. The last sample that sets the referrer-header will set it on the response back from the server, but as I said, referrer is a request variable so it will just be ignored.
The only thing you could do from PHP is to tell the browser to redirect to the page again (by setting the location-header), but as far as I know these days this won't reset the referral-header (if so then redirects from http to https for example would loose it all the time).
I'm not exactly sure are you trying to acomplish here. Setting document.referrer is only valid for the current page and won't affect what the next page sees. If executed early it might fool some tracking scripts at most.
Before I get to the question, let me explain how we have things set up.
We have a proxy.php file, in which class Proxy is defined with functions that call upon a rest for creating/editing/getting Wordpress posts, fields etc.
Then, we have a proxyhandler.php, in which Proxy class is initialized and serves as a handle between proxy.php and a javascript file.
In javascript file we have an ajax call to proxyhandler.php in which we send our secret and other data.
Now, the problem arises here:
We define the secret through wp_localize_script, by using md5 custom string + timestamp. We send the encripted string and timestamp through ajax to proxy handler, where we use the previous (hardcoded inside proxyhandler) string and timestamp to generate a md5 string again, and check the one sent against the one generated. If they are the same, we continue by doing whatever was requested, if they dont fit, we just return that the secret didn't match.
Now, the real issue comes here - by using wp_localize_script, the variable for the secret is global and as such, anyone can utilize it via dev tools and can send any ajax request to proxyhandler that they want.
What would be the proper procedure to make it more secure? We've thought of doing this:
Instead of using wp_localize_script, we put the script inside a php file, we define the secret using a php variable and then simply echo the secret file into ajax. Would this be viable, or are there any other ways?
Instead of sending an encrypted string in global scope, then check against it, you should use nonce in your AJAX request:
var data = {
action: 'your_action',
whatever_data: who_know,
_ajax_nonce: <?= wp_create_nonce('your_ajax_nonce') ?>
};
Then, use check_ajax_refer() to verify that nonce:
function your_callback_function()
{
// Make sure to verify nonce
check_ajax_refer('your_ajax_nonce');
// If logged in user, make sure to check capabilities.
if ( current_user_can($capability) ) {
// Process data.
} else {
// Do something else.
}
...
}
Depend on the AJAX METHOD, you can use $_METHOD['whatever_data'] to retrieve who_know data without needing to use wp_localize_script().
Also remember that we can allow only logged in users process AJAX data:
// For logged in users
add_action('wp_ajax_your_action', 'your_callback_function');
// Remove for none logged in users
// add_action('wp_ajax_nopriv_your_action', 'your_callback_function');
The final thing is to make sure NONCE_KEY and NONCE_SALT in your wp-config.php are secure.
I'm trying to record user's clicks on a specific iFrame in a div containing an ad, in order to block problematic IP addresses, thus preventing those who are trying to spam the ad, from being able to click it again. In each click made by the user, a record will be inserted into a table in mySQL database which includes:
IP address
Clicks counter
Unix timestamp
Each user/IP address has a privilege to click the ad 3 times in 24 hours.
For detecting each click on the iFrame ad, I used iframeTracker-jquery class and implemented a JavaScript code as follow:
index.php:
<?php include 'AdProtection.php'; ?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.iframetracker.js"></script>
<script>
jQuery(document).ready(function($) {
$('.iframetrack iframe').iframeTracker({
blurCallback: function() {
console.log("Click has been detected!");
$.ajax({
type: "POST",
url: "update.php"
);
}
});
});
</script>
</head>
<body>
<div class="iframetrack" id="adsense_frame">
<?php //Returns true when a user 's IP address isn't currently blocked by checking in Database. if(AdProtection::protectAd()) echo '<iframe width="728" height="90" src="js/demo/sample-iframe/red.html" frameborder="0" allowtransparency="true" scrolling="no"></iframe>'; ?>
</div>
</body>
</html>
update.php:
<?php
function update($odb)
{
$sql=$odb->prepare('INSERT INTO system (ip, clicks, timestamp) VALUES(:ip, clicks+1, :timestamp) ON DUPLICATE KEY UPDATE clicks = clicks+1, timestamp = :timestamp');
$sql->execute(array(':ip' => ip2long($_SERVER['REMOTE_ADDR']),':timestamp' => time()));
}
//PDO Connection
include ( "db.php");
$sql=$odb->prepare('SELECT clicks, timestamp FROM system WHERE ip= :ip');
$sql->execute(array(':ip' => ip2long($_SERVER['REMOTE_ADDR'])));
$data = $sql->fetch();
if($data != null)
{
if($data['clicks'] % 3 == 0)
{
if(($data['timestamp'] + (24 * 60 * 60)) < time())
update($odb);
else
//User is currently blocked.
}
else
update($odb);
}
else
update($odb);
There are 2 crucial problems when implementing this JavaScript code / jQuery POST request:
The code can be manipulated/modified by an individual since JavaScript is a client-side language.
A spam can be made on the update.php file.
How can I deal with these problems ?
Do the checks server-side. Always.
You have neither control nor reliable knowledge about the client, so with anything sensitive, don't trust it.
Ultimately, a user may just download the source code of an open-source browser and modify it as (s)he wishes.
Disabling things client-side is a nice plus if it indicates that functionality is not available, and it might save you and your users some time and bandwidth, but there are gonna be those who try to circumvent it, and for those you need to be prepared.
Disabling things server-side means just denying execution, i.e. just put an exit; after your comment //User is currently blocked., that should do it.
For your second question: yes, the update.php might get spammed, but so might any other PHP script.
Every reasonable web server I know has some way of limiting the amount of requests a client can make in a certain amount of time.
Lighttpd has a native mod_evasive, nginx has HttpLimitReqModule and for Apache there's a number of things, see this SO answer.
If the spamming exceeds the capabilities of your web server, it's time to look into DDos protection.
Js code may be manipulated by anyone as its client side all what you can do is to minimalise risk of your code to be potentially disabled by other script in order to do it write your js to use only private methods and variables in a self-executing function. So the code will be not visible in global namespace, you may also need to copy definitions of globally available objects (like document or getElementById) as they may change them and not your code itself. After that obfuscate code and minify it.
For PHP you will probably need to implement some kind of authentication to work in pair with your js script as this is nothing more than securing any request for access so maybe IP or session validation. Yo may also implement some other server side mechanisms in order to prevent this script from being accessed by certain IP adresses.
You may also decide to not display iframe at all for certain ip addresses or by device fingerprint http://en.wikipedia.org/wiki/Device_fingerprint which will not depend on client side logic, this will probably make it more secure than solution proposed by you.
Is there any way to get the http status of the current web page from javascript?
Spent some time searching on the web, but no luck at all... Seems like it's not possible, but wanted to check with Stack Overflow for maybe some fancy workaround.
(Providing it from the server as part of the response body is not acceptable, the status is supposed to be only available via the http header)
This is not in any way possible, sorry.
Yes You can
Simply request the same page, i.e. URI, using the XMLHttpRequest. Suppose that your page on /stop.php in stop.php you may do something like:
<script>
function xhrRequest(){
console.log(this.status);
// Do some logic here.
}
function getReq(url){
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", xhrRequest);
oReq.open("GET", url);
oReq.send();
}
getReq("/stop.php");
</script>
Checkout this DEMO
🕯 Note:
You have to note that, it is a copy of the page not the page itself.
I, already, have used this solution on a page in which the server may
generate Forbidden HTTP status code when the request is come from
unauthorized IP address, so the condition here is very simple and
there is no much difference between the original and the copy page
that you have simulate its visit.
As a one liner:
fetch(location.href).then(response => console.log(response.status));
This is asynchronous, if you need a synchronous solution use XMLHttpRequest (as in the other answer) together with async: false or use async/await which feels synchronous, but is still asynchronous under the hood.
Alternatively
An approach without an extra call would need to include the status code in the page on the server side (e.g. in a meta tag), then read it on the client side via JavaScript.
Java + Thymeleaf:
<meta name="statuscode" th:content="${#response.status}">
PHP (unverified):
<meta name="statuscode" content="<?php echo http_response_code() ?>">
It is not beautiful, but you can use:
t = jQuery.get(location.href)
.success(function () { console.log(t.status) })
.error(function() { console.log(t.status) });
That When Eric says, this solution will make a new request from the same paga, and not show status of current request.
you can only check status of page loading
try:var x = document.readyState;
The result of x could be:
One of five values:
uninitialized - Has not started loading yet
loading - Is loading
loaded - Has been loaded
interactive - Has loaded enough and the user can interact with it
complete - Fully loaded
I am working on creating a RESTful API that supports cross-domain requests, JSON/JSONP support, and the main HTTP method (PUT/GET/POST/DELETE). Now while will be easy to accessing this API through server side code , it would nice to exposed it to javascript. From what I can tell, when doing a JSONP requests with jQuery, it only supports the GET method. Is there a way to do a JSONP request using POST/PUT/DELETE?
Ideally I would like a way to do this from within jQuery (through a plugin if the core does not support this), but I will take a plain javascript solution too. Any links to working code or how to code it would be helpful, thanks.
Actually - there is a way to support POST requests.
And there is no need in a PROXI server - just a small utility HTML page that is described bellow.
Here's how you get Effectively a POST cross-domain call, including attached files and multi-part and all :)
Here first are the steps in understanding the idea, after that - find an implementation sample.
How JSONP of jQuery is implemented, and why doesn't it support POST requests?
While the traditional JSONP is implemented by creating a script element and appending it into the DOM - what results inforcing the browser to fire an HTTP request to retrieve the source for the tag, and then execute it as JavaScript, the HTTP request that the browser fires is simple GET.
What is not limited to GET requests?
A FORM. Submit the FORM while specifing action the cross-domain server.
A FORM tag can be created completely using a script, populated with all fields using script, set all necessary attributes, injected into the DOM, and then submitted - all using script.
But how can we submit a FORM without refreshing the page?
We specify the target the form to an IFRAME in the same page.
An IFRAME can also be created, set, named and injected to the DOM using script.
But How can we hide this work from the user?
We'll contain both FORM and IFRAME in a hidden DIV using style="display:none"
(and here's the most complicated part of the technique, be patient)
But IFRAME from another domain cannot call a callback on it's top-level document. How to overcome that?
Indeed , if a response from FORM submit is a page from another domain, any script communication between the top-level page and the page in the IFRAME results in "access denied". So the server cannot callback using a script. What can the server can do? redirect. The server may redirect to any page - including pages in the same domain as the top-level document - pages that can invoke the callback for us.
How can a server redirect?
two ways:
Using client side script like <Script>location.href = 'some-url'</script>
Using HTTP-Header. See: http://www.webconfs.com/how-to-redirect-a-webpage.php
So I end up with another page? How does it help me?
This is a simple utility page that will be used from all cross-domain calls. Actually, this page is in-fact a kind of a proxi, but it is not a server, but a simple and static HTML page, that anybody with notepad and a browser can use.
All this page has to do is invoke the callback on the top-level document, with the response-data from the server. Client-Side scripting has access to all URL parts, and the server can put it's response there encoded as part of it, as well as the name of the callback that has to be invoked. Means - this page can be a static and HTML page, and does not have to be a dynamic server-side page :)
This utility page will take the information from the URL it runs in - specifically in my implementation bellow - the Query-String parameters (or you can write your own implementation using anchor-ID - i.e the part of a url right to the "#" sign). And since this page is static - it can be even allowed to be cached :)
Won't adding for every POST request a DIV, a SCRIPT and an IFRAME eventually leak memory?
If you leave it in the page - it will. If you clean after you - it will not. All we have to do is give an ID to the DIV that we can use to celan-up the DIV and the FORM and IFRAME inside it whenever the response arrives from the server, or times out.
What do we get?
Effectively a POST cross-domain call, including attached files and multi-part and all :)
What are the limits?
The server response is limited to whatever fits into a redirection.
The server must ALWAYS return a REDIRECT to a POST requests. That include 404 and 500 errors.
Alternatively - create a timeout on the client just before firing the request, so you'll have a chance to detect requests that have not returned.
not everybody can understand all this and all the stages involved. it's a kind of an infrastructure level work, but once you get it running - it rocks :)
Can I use it for PUT and DELETE calls?
FORM tag does not PUT and DELETE.
But that's better then nothing :)
Ok, got the concept. How is it done technically?
What I do is:
I create the DIV, style it as invisible, and append it to the DOM. I also give it an ID that I can clean it up from the DOM after the server response has arrived (the same way JQuery cleans it's JSONP SCRIPT tasgs - but the DIV).
Then I compose a string that contains both IFRAME and FORM - with all attributes, properties and input fields, and inject it into the invisible DIV. it is important to inject this string into the DIV only AFTER the div is in the DOM. If not - it will not work on all browsers.
After that - I obtain a reference to the FORM and submit it.
Just remember one line before that - to set a Timeout callback in case the server does not respond, or responds in a wrong way.
The callback function contains the clean-up code. It is also called by timer in case of a response-timeout (and cleans it's timeout-timer when a server response arrives).
Show me the code!
The code snippet bellow is totally "neutral" on "pure" javascript, and declares whatever utility it needs. Just for simplification of explaining the idea - it all runs on the global scope, however it should be a little more sophisticated...
Organize it in functions as you may and parameterize what you need - but make sure that all parts that need to see each other run on the same scope :)
For this example - assume the client runs on http://samedomain.com and the server runs on http://crossdomain.com.
The script code on the top-level document
//declare the Async-call callback function on the global scope
function myAsyncJSONPCallback(data){
//clean up
var e = document.getElementById(id);
if (e) e.parentNode.removeChild(e);
clearTimeout(timeout);
if (data && data.error){
//handle errors & TIMEOUTS
//...
return;
}
//use data
//...
}
var serverUrl = "http://crossdomain.com/server/page"
, params = { param1 : "value of param 1" //I assume this value to be passed
, param2 : "value of param 2" //here I just declare it...
, callback: "myAsyncJSONPCallback"
}
, clientUtilityUrl = "http://samedomain.com/utils/postResponse.html"
, id = "some-unique-id"// unique Request ID. You can generate it your own way
, div = document.createElement("DIV") //this is where the actual work start!
, HTML = [ "<IFRAME name='ifr_",id,"'></IFRAME>"
, "<form target='ifr_",id,"' method='POST' action='",serverUrl
, "' id='frm_",id,"' enctype='multipart/form-data'>"
]
, each, pval, timeout;
//augment utility func to make the array a "StringBuffer" - see usage bellow
HTML.add = function(){
for (var i =0; i < arguments.length; i++)
this[this.length] = arguments[i];
}
//add rurl to the params object - part of infrastructure work
params.rurl = clientUtilityUrl //ABSOLUTE URL to the utility page must be on
//the SAME DOMAIN as page that makes the request
//add all params to composed string of FORM and IFRAME inside the FORM tag
for(each in params){
pval = params[each].toString().replace(/\"/g,""");//assure: that " mark will not break
HTML.add("<input name='",each,"' value='",pval,"'/>"); // the composed string
}
//close FORM tag in composed string and put all parts together
HTML.add("</form>");
HTML = HTML.join(""); //Now the composed HTML string ready :)
//prepare the DIV
div.id = id; // this ID is used to clean-up once the response has come, or timeout is detected
div.style.display = "none"; //assure the DIV will not influence UI
//TRICKY: append the DIV to the DOM and *ONLY THEN* inject the HTML in it
// for some reason it works in all browsers only this way. Injecting the DIV as part
// of a composed string did not always work for me
document.body.appendChild(div);
div.innerHTML = HTML;
//TRICKY: note that myAsyncJSONPCallback must see the 'timeout' variable
timeout = setTimeout("myAsyncJSONPCallback({error:'TIMEOUT'})",4000);
document.getElementById("frm_"+id+).submit();
The server on the cross-domain
The response from the server is expected to be a REDIRECTION, either by HTTP-Header or by writing a SCRIPT tag. (redirection is better, SCRIPT tag is easier to debug with JS breakpoints).
Here's the example of the header, assuming the rurl value from above
Location: http://samedomain.com/HTML/page?callback=myAsyncJSONPCallback&data=whatever_the_server_has_to_return
Note that
the value of the data argument can be a JavaScript Object-Literal or JSON expression, however it better be url-encoded.
the length of the server response is limited to the length of a URL a browser can process.
Also - in my system the server has a default value for the rurl so that this parameter is optional. But you can do that only if your client-application and server-application are coupled.
APIs to emit redirection header:
http://www.webconfs.com/how-to-redirect-a-webpage.php
Alternatively, you can have the server write as a response the following:
<script>
location.href="http://samedomain.com/HTML/page?callback=myAsyncJSONPCallback&data=whatever_the_server_has_to_return"
</script>
But HTTP-Headers would be considered more clean ;)
The utility page on the same domain as the top-level document
I use the same utility page as rurl for all my post requests: all it does is take the name of the callback and the parameters from the Query-String using client side code, and call it on the parent document. It can do it ONLY when this page runs in the EXACT same domain as the page that fired the request! Important: Unlike cookies - subdomains do not count!! It has to he the exact same domain.
It's also make it more efficient if this utility page contains no references to other resources -including JS libraries. So this page is plain JavaScript. But you can implement it however you like.
Here's the responder page that I use, who's URL is found in the rurl of the POST request (in the example: http://samedomain.com/utils/postResponse.html )
<html><head>
<script type="text/javascript">
//parse and organize all QS parameters in a more comfortable way
var params = {};
if (location.search.length > 1) {
var i, arr = location.search.substr(1).split("&");
for (i = 0; i < arr.length; i++) {
arr[i] = arr[i].split("=");
params[arr[i][0]] = unescape(arr[i][1]);
}
}
//support server answer as JavaScript Object-Literals or JSON:
// evaluate the data expression
try {
eval("params.data = " + params.data);
} catch (e) {
params.data = {error: "server response failed with evaluation error: " + e.message
,data : params.data
}
}
//invoke the callback on the parent
try{
window.parent[ params.callback ](params.data || "no-data-returned");
}catch(e){
//if something went wrong - at least let's learn about it in the
// console (in addition to the timeout)
throw "Problem in passing POST response to host page: \n\n" + e.message;
}
</script>
</head><body></body></html>
It's not much automation and 'ready-made' library like jQuery and involes some 'manual' work - but it has the charm :)
If you're a keen fan of ready-made libraries - you can also check on Dojo Toolkit that when last I checked (about a year ago) - had their own implementation for the same mechanism.
http://dojotoolkit.org/
Good luck buddy, I hope it helps...
Is there a way to do a JSONP request using POST/PUT/DELETE?
No there isn't.
No. Consider what JSONP is: an injection of a new <script> tag in the document. The browser performs a GET request to pull the script pointed to by the src attribute. There's no way to specify any other HTTP verb when doing this.
Rather than banging our heads with JSONP method, that actually won't
support POST method by default, we can go for CORS .That will provide no big changes in the conventional way of programming. By simple Jquery Ajax call we can go with cross domains.
In CORS method, you have to add headers in server side scripting file, or in the server itself(in remote domain), for enabling this access. This is much reliable, since we can prevent/restrict the domains making unwanted calls.
It can be found in detail in wikipedia page.