I'm using a library (rightjs) to make xhr requests to a server which only accepts PUT requests for a certain api call. Looking at the code, the library seems to overwrite the method to be POST and appends the method in a querystring parameter:
if (method == 'put' || method == 'delete') {
add_params._method = method;
method = 'post';
}
(the query string is formed calling .map() on add_params later on)
I'm not familiar with the reason for this, but I'm guessing it intends to support servers which do not have WebDAV functionality. I'd like to contribute to the library but don't want to outright delete this code since it seems like there must be a good reason for it.
Why does this library do this, and what methods can I use to figure out if its needed?
(a) This has nothing to do with WebDAV. (b) There used to be libs and intermediaries not supporting PUT, and this was a workaround (which of course requires the server to support it).
Related
So, I was asked to create some kind of web service that return a javascript library (that changes based on the query params) to a jsonp call.
I tried to write down some scripts to do so and looks like it's possible and easy.
Now the question is, I read a lot of articles about jsonp but, why should I not make something like this? And what could I do to achive the same result but not this way?
client sample here:
var script = document.createElement('script');
script.src = '//my_url/testjsonp.php';
document.getElementsByTagName('head')[0].appendChild(script);
server sample here:
echo 'var a = function(){ /* basically what i want here */ }()';
A couple of issues with that:
You're creating a global a variable. The page calling your service should be in charge of that, so unless you've made the a configurable, that's a problem.
The code within your function would have to magically know what it was supposed to do with the data. That's contrary to the point of JSONP, which is for the server just to return the data and let the client decide what to do with it.
Those two reasons are why a standard JSONP request allows the caller to specify the callback name (usually with a callback parameter, but the name varies)
http://example.com/path/to/service?callback=foo
...and a standard JSONP response looks like this:
foo({/*...JSON here...*/});
That way, the caller defines the function, which knows what to do with the data you're passing into it.
I'd like to use an old s_code.js to generate a url that I can use to track an event, but I'd like not to use s.t() as it provides no way of keeping tabs on the request. Is there any way to get the url as a String before sending off the tracking request with s.t()?
You'd need to pull from a mixture of methods in order to get this data. There is no one method (at least in AppMeasurement) that will get this for you. A combination of s.pb (builds the domain and path, but also calls for the creation of the request), s.gb for the build of URL parameters, and s.t for the build of the cache buster. YMMV given this is in the core library with 0 expectations of internal methods not getting renamed.
I guess my question is why you're wanting to do this. There are options of preventing the call from being made, but needing to inspect the URL is a first for me.
In my previous angularjs project I used interceptors to intercept the http calls, and to be able to serve mock data instead of the real data from the server. I found it very useful throughout the development process.
My question is, how could I do this without angularjs (In my current project I use another framework, which does not have interceptors)?
Is there any other http library out there, that supports this? How could I achive this using jquery's or superagent's http capabilities?
So i found the following script: https://github.com/creotiv/AJAX-calls-intercepter/blob/master/index.html
Here is a live fiddle: http://jsfiddle.net/0eyadb88/1/
I'm not going to go over everything in the script as simply it looks like it does handle the XMLHttpRequest as i commented on. To what extent this works, well that would be just some testing of course and should be able to be expanded.
i've added a non jquery ajax call (testing with chrome here) and it handles that as well.
The main section to pay attention to is
(function (open) {
XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
alert('Intercept');
open.call(this, method, url + ".ua", async, user, pass);
};
})(XMLHttpRequest.prototype.open);
Personally i would use this approach unless a decent libary is around, but of course if such a libary exists. please do let us know ;)
Otherwise cleaning up the script or using that one in general should be fairly easy.
You should check out dfournier/plasticine. I developed this library in order to intercept a request and fake the response or intercept server response and modify it. I use it at work and the backend team is not ready but we already defined the API.
I know that I can route to router.get('/object/:id', ...), router.post('/object/new', ...), router.delete('/object/:id', ...), and router.put('/object/:id', ...) and that when I browse to a specific object, the browser will issue a http get request. And I understand that I can post info through a form. But how can I implement the DELETE and PUT methods so that I can edit and delete objects? How do I specify the method used in the route? Do I have to change the route so that it is unique (ie, router.get('/object/delete/:id', ...) and router.get('/object/edit/:id', ...)) and just use get methods?
In your HTML form element you can use the method attribute to specify the method. <form method="put">. However, more typically these type of RESTful API endpoints are called from browsers with javascript as AJAX requests, which can use all of the available HTTP methods. This can be done with the XmlHttpRequest standard API, jQuery's $.ajax, or the front end framework of your choosing.
Do I have to change the route so that it is unique
No, you can have the same URL path with different HTTP methods and those can be handled by different callback functions to behave differently. Conventional REST URL schemes make heavy semantic use of the various HTTP methods requesting the same URL path (GET means get, PUT means replace, etc).
I'm creating a system where a Javascript script extracts data from a Sage extract, and stores it in a Javascript object (JSON I guess). I need to then upload the data to an SQL database via PHP.
I had thought of using an Iframe, by changing the src to the PHP pages URL, then pass GET variables to the page via the url. I was wondering if I could actually use tags to do this too? By creating new images and setting the src to the PHP pages URL (again, passing GET variables to it), then the PHP page could do the rest? I know the image wouldn't display anything, it doesn't need to. I just need a way to pass data to the PHP page.
Best practices?
The modern way of using JavaScript to communicate with a server is XMLHttpRequest. By default it is asynchronous and does give you the option to change this, though synchronous requests may be considered bad practice.
Here is a basic example
function sendObject(object, uri, callback) {
var xhr = new XMLHttpRequest(),
data = new FormData();
data.append('object', JSON.stringify(object));
if (callback) xhr.addEventListener('load', callback);
xhr.open('POST', uri);
xhr.send(data);
}
// ex. usage
sendObject(
{foo: "bar"},
"/somepage.php",
function () {console.log('completed with code:', this.status)}
);
Using a FormData saves you a little time, too. If you can't expect it to be available, simply do
postData = encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&' + etc;
As the two other answer have said, for an HTML page with Javascript to communicate with the server, a PHP page, you would need to use XMLHttpRequest, aka AJAX. Paul S.'s answer is the best answer with respect to how to directly use XMLHttpRequest with Javascript.
However, one thing to keep in mind is that if you have to support older browsers, especially Internet Explorer version 9 or below, you'll run into quirks and it's advised to use a library for this. For the all purpose library, which includes not only AJAX methods but also form data handling and manipulating the DOM before, during, and after your request, your best bet is to use jQuery. For example, for an AJAX request to send data from a form:
$.ajax({
url: 'http://www.example.com/data.php',
data: $(form).serialize(),
dataType: 'JSON', // JSON will be returned if possible
type: 'POST'
}).then(function(data) {
...
});
jQuery is great, but it is also a big library and if you only really want or need AJAX requests, it's better to find a smaller library or use a function that's known to work cross browser. It's also important to note that jQuery has strange handling of promises, which is the way a function would say it will return a value but not right away. These promises are necessary if you chain AJAX functions together without making your code contain many nested functions. Two of the most well known promise libraries are rsvp.js and q.