Node/Express - How to implement DELETE and PUT requests - javascript

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).

Related

Retrieving the Omniture tracking call url before calling s.t()

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.

How to properly connect Ajax/Javascript to the backend

I have created a PHP class that allows my users to createAccount, updateAccount along with various other functions.
I normally create an 'interface' script that initiates a class and calls the login function and I pass the variables from the front end to this script using JavaScript. However I have to create lots of these 'interface' scripts for each function. Is there any better way to do this?
I end up with an 'interface' folder which scripts such as createAccount.php, updateAccount.php and these scripts are called when the user wants to do any of these functions. Is there a better way to do this?
There are many possibilities for client-server communication. The method and design by which you choose to allow this communication is up to you.
As for your question - you can create a single php endpoint (i.e. endpoint.php) through which to handle all ajax requests. Specific parameters of the request, such as which server side action to perform, can be sent through the query parameters in the url (and accessed in your script with the $_GET variable), or through post data (and accessed with $_POST).
Assuming you are using jQuery, an AJAX request to this endpoint might look like:
$.ajax({
url: 'path/to/endpoint.php',
data: {
_function: 'createAccount',
/* ... */
}
});
And in endpoint.php you may handle the request in such a manner:
<?php
switch ($_GET['_function']){
case 'createAccount':
// handle account creation
// ...
break;
case '...':
// ...
}
?>
This is just one possibility of communication between client and server. No matter how you do it - with a single endpoint which handles all requests, or multiple endpoints - it's your design decision.
You might want to look up on client-server communication protocols over HTTP, such as REST and SOAP.

what's the diffrence between $.ajax / $.get / $.POST / .load()?

I'm trying to understand AJAX and JSON and I'm not sure I get it, there are methods and functions that are doing the same stuff...
You've got $.getJSON to retrieve JSON format data from server, and you have $.ajax + $.post + $.get + load() to send data data to the server?
Can I use all of those methods to send JSON data?
Really I'm confused! Help me figure this out.
All those are just shorthands for calling the $.ajax function.
load is for retrieving HTML and writing it to the DOM in one go. You want to load JSON.
get and getJSON use GET requests which are not well-suited for sending JSON data.
post does a POST request, but doesn't allow you to choose the contentType of the sent data
For sending JSON you should use the $.ajax function with its many options, see Send JSON data with jQuery.
An AJAX request is, at heart, an HTTP request. This is the same protocol which is used for all content on the Web (arguably, if it's not HTTP, it's not the Web) - loading a page, the images on the page, the CSS and JS includes, a submitted form, etc, etc.
As such, it inherits pretty much all of the flexibility of HTTP, meaning a generic function like jQuery.ajax ends up quite complex, with lots of options you don't normally need to worry about. This leads to the Shorthand Methods you mentioned, which bundle up common sets of options and functionality.
Among the things you might want to vary:
The "method" of the request: GET or POST (or less common ones like HEAD, PUT, DELETE...). A GET request is the simplest: request this URL, give me its contents; parameters to a GET request are shoved onto the "query string" of the URL. A POST request is how larger forms would be submitted on a normal page: the parameters are passed as a body of data separate from the URL and control headers; for an AJAX request this is often helpful to send a block of XML or JSON to a URL. This is a very broad overview, and there are many more distinctions in behaviour and meaning between the two.
The "content type" you want in the response (and, for a POST request, of the data you're sending). Not only does this tell both the server and the browser what data it is handling, ensuring it will pass it successfully, it can give jQuery (or whatever library) a hint of what to do next: if a call returns XML, you'll probably want to manipulate it as a DOM straight away; if it's JSON, you'll want to parse it as a JS object.
What you want to do once the data comes back. I've already mentioned parsing JSON or XML, but what if your response is actually a block of HTML that you want to inject straight into the parent page? Obviously you could do that yourself in the callback function, but again jQuery includes a shorthand form in the shape of .load().
All of the above are possible with jQuery.ajax, but you'd have to remember the parameters, even though you're falling into the same cases again and again, so chances are most of the time you'll be using whichever of the shorthands suits your needs at that moment.

Http methods differences

What is difference between
HTTPPOST
HTTPDELETE
HTTPPUT
HTTPGET
Normally used post and get method for submit form and i know them very well but want to know with delete and put method when and why they can be used to improve programming skills
What the different methods do depends entirely on how the remote web server chooses to interpret them. There is no fixed meaning. A server does not care if it sees GET or POST; rather, the code that ends up being executed to service the request does (and can decide to do anything, since it's code).
The HTTP protocol gives an official guideline for what kind of action each verb is supposed to trigger, which is:
GET: retrieve a resource
PUT: replace a resource with another, or create it if it does not exist
DELETE: remove a resource if it exists
POST: might do anything; typically used to "add" to a resource
However this mapping is ultimately governed by application code and is typically not respected by web applications (e.g. you will see logical deletions being enacted with POST instead of DELETE).
The situation is better when talking about REST architectures over HTTP.
In a nutshell:
GET = fetch a resource.
POST = update a resource.
DELETE = delete a resource.
PUT = create/replace a resource.
In HTML, only GET and POST are allowed. A typical web-development HTTP server will do nothing unless you have code (or configuration) to specify what you want it to do with the different HTTP methods.
There's nothing stopping you from updating user data in response to a GET request, but it's not advisable. Browsers deal with GET and POST differently, with respect to caching the request (a cached GET will automatically be reissued, but a cached POST will prompt the user to allow it to be resent) and many HTML elements can issue GETs, making them unsafe for updates. There are other HTTP methods too http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol.
Many people who claim to be RESTful will confuse HTTP POST and PUT with SQL UPDATE and INSERT. There isn't a direct correlation, it always depends on context. That is, what POST means depends entirely on the resource that you're interacting with. For example, creating a new entry on a blog could be a POST to the blog itself, or a PUT to a subordinate resource. However, a PUT, by definition, must always contain the entire resource.
Typically, you would not allow a HTTP client to determine the URI of a new resource, so a POST to /blog would be safer than a PUT to /blog/article-uri although HTTP does cater for appropriate responses should the server be unable to honour the intended URI. (HTTP is just a specification, you have to write the code to support it, or find a framework)
But as you can always achieve a PUT or DELETE use-case by POSTING to a parent resource responsible for its subordinates (i.e. POSTing a message to /mailbox instead of PUTting it at /mailbox/message-id), it isn't essential to expose PUT or DELETE methods publicly.
You can improve your programming skills by adopting REST principles to improve the visibility of the interactions within a system, it may be simpler to contextualise your interactions in terms of REST by having a uniform interface, for example.
REST is not HTTP though: http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm.

How does the diigolet bookmarklet get around cross-scripting?

http://www.diigo.com/tools/diigolet
Diigolet essentially allows you to use a bookmarklet to bookmark sites. With the bookmarklet I'm making, I also need to pass the current URL of the site the user is on to my server. Everytime I try this, I get a cross-scripting error.
Does anybody know how to bypass this like the diigolet?
Essentially, they work around the same-origin policy by injecting a script tag with the different-domain URL rather than using an XMLHttpRequest. Note that this is different from a normal JSON request in that the JSON is wrapped in a callback function, for example:
myCallbackFunction(<JSON here>);
(This works because JSON is a subset of JavaScript's object literal notation.)
In their case, they hardcode the name of the callback function as diigolet.callback, but there exists a specification called JSONP that JavaScript libraries such as jQuery support.
Under the JSONP specification, the name of the callback function is passed to the server via a callback=myCallbackFunction parameter in the GET request. Your server-side code needs to handle this appropriately to be able to handle JSONP requests from jQuery.

Categories

Resources