Retrieving ID atribute from URL - javascript

In my django project i have a url:
https://example.com/nice_page#123
This url will lead user to particular post on my page, this is an example how it works on stackoverflow:
What is the "N+1 selects problem" in ORM (Object-Relational Mapping)? (it is a link to particular answer, and your browser will move you right to this answer.)
My goal is to get this #123 id from url.
I can't do it with django's META data by request.META it doesn't show this #123 id, it only returns me https://example.com/nice_page
How can i get this #123 id?
I would prefer making it with django, but javascript is also acceptable.
Update: as follows from the comments, thanks to –
Willem Van Onsem and Ankit Tiwari, this task is unsolvable by server-side (by django) How to access url hash/fragment from a Django Request object

Yes, only with JavaScript. E.g. using an example from here:
const url = new URL('https://example.com/nice_page#123');
console.log(url.hash); // Logs: '#123'
Or reference the hash of the current URL in a browser:
console.log(window.location.hash);

You could use location.search and URLSearchParams.
https://example.com/nice_page?id=123
const params = new URLSearchParams(window.location.search);
const id = parseInt(params.get("id"));
console.log(id);
You can read more about here: https://developer.mozilla.org/en-US/docs/Web/API/Location/search

Related

How do I retrieve a list of posts based on a tag slug in WP Rest API V2?

I have an application that retrieves data from a Wordpress site using the WP Rest API V2. The API has recently been change from using a 'filter[tag]=' to a new syntax. I am looking to retrieve a list of posts within a specific tag.
Old syntax:
http://demo.wp-api.org/wp-json/wp/v2/posts?filter[tag]=slug
The new syntax looks like this:
http://demo.wp-api.org/wp-json/wp/v2/posts?tags=id
It now takes an ID integer instead of a slug as argument. I have looked over the documentation but I can't seem to find a solution for this. I have no option of using the id, I can only use the slug!
The WP Rest API documentation can be found here: https://developer.wordpress.org/rest-api/reference/posts/
Do you have any idea how to solve this?
Just get the list of tags by calling http://demo.wp-api.org/wp-json/wp/v2/tags before your requesting posts on a specifiy tagId. In that way you will find the tagId you need by filtering the data by your "slug". The demo API is not support CORS thats way I dont create a working fiddle.
Nested $http request bad example
$http({
method: 'GET',
url: 'http://demo.wp-api.org/wp-json/wp/v2/tags'
}).then(function (result) {
var filtered = filterFilter(result.data, { slug: 'dolor'});
$http({
method: 'GET',
url: 'http://demo.wp-api.org/wp-json/wp/v2/posts?tags=' + filtered[0].id
}).then(function (result) {
console.log(result.data);
});
});
Looking at the official API docs for TAGS, you can search for strings in the tags schema with a request like this:
http://demo.wp-api.org/wp-json/wp/v2/tags?search=yourslug
The resulting JSON output will display tags containing the string you searched in any of the schema fields, like slug.
After you retrieved the desired tag, you can fetch the posts with that specific tag using it's ID (as suggested by #lin).

Dumbed down Powershell web client function to let me post form data easily

Ive been using an Internet Explorer automation script found here:
http://www.pvle.be/2009/06/web-ui-automationtest-using-powershell/
That lets me easily post form data using commands (functions) like this:
NavigateTo "http://www.websiteURI/"
SetElementValueByName "q" "powershell variable scope"
SetElementValueByName "num" "30"
SetElementValueByName "lr" "lang_en"
ClickElementById "sb_form_go"
The above would let me post values to elements and click to submit the form.
I would like to do the equivalent with Powershell's web client using helper functions. I haven't found such a script. The closest I could find was The Scripting Guys, Send-WebRequest:
http://gallery.technet.microsoft.com/scriptcenter/7e7b6bf2-d067-48c3-96b3-b38f26a1d143
which I'm not even sure it does what I expect (since there's no working examples showing how to do what I want).
Anyway, I'd really appreciate some help to get me started to do the equivalent of what I showed up there with working examples (as simple as possible). A bonus would be to also be able to get a list of element names for a URI in order to know what form elements I want to submit.
PS: I also need to be able to specify user-agent and credentials; so, examples with these included would be ideal.
Have you taken a look at the Invoke-WebRequest commmand? (requires powershell 3.0 or above) I believe the following would work for submitting the data
#POSTing data
Invoke-WebRequest http://www.websiteURI/ `
-UserAgent 'My User Agent' `
-Credential $cred `
-Method Post `
-Body #{
q = 'powershell variable scope'
num = 30
lr = 'lang_en'
}
For your bonus, the result of Invoke-WebRequest contains a collection of the InputFields on the page, which you can use to get a list of form elements to set.
#List input elements
Invoke-WebRequest http://www.websiteURI/ | select -ExpandProperty InputFields

Passing objects from NodeJS to client and then into KnockoutJS viewmodel

So thanks to SO I can pass an object from node to the client, but then getting it into a knockout view model is a bit awkward. These are the steps I have so far (I've included links to the relevant lines as they appear in my github project. Thought the context might help.):
Apply JSON.stringify and pass to the jade file
recipeJSON: JSON.stringify(recipe);
Wrap this in a function in a header script that just parses the JSON and returns the result
script
function getRecipeObject() {
var r = '!{recipeJSON}';
return JSON.parse(r);
}
Call this function and pass the result to a view model constructor
self.recipe = ko.observable(new Recipe(getRecipeObject()));
This works but is there a better way?
Question clarification (Edit): I feel step 2 shouldn't be necessary. Is there a way to directly pass the JSON from node to the Recipe() constructor, without the getRecipeObject() acting as an intermediate step? I tried passing recipeJSON in directly like so
self.recipe = ko.observable(JSON.parse('!{recipeJSON}'));
That doesn't work I think because its not a jade template and has no access to the variable.
According to the answer to this question rendering data into scripts is bad practice and I should instead make an XHR call on page load instead.
Edit
I just saw you linked a github repo! So you're already familiar with most of this...you even have an endpoint set up at /recipe/:id/view, so now I'm really confused...what isn't working out for you? Just the last step of deserialization using ko.utils.*?
Sorry about all the exposition -- I thought this was way more rudimentary than it actually was; I hope no offense taken there!
You really don't want to return a script to execute -- instead, treat this as a DTO: an object that just stores data (no behaviors). An example would be:
{
recipeID: 12,
reviewIDs: [42, 12, 55, 31],
rating: 4.2
recipeName: "A super tasty pie!"
}
This object (representation) is a projection -- a simplified version of the full data stored in the database.
The next step is to create an endpoint to access that data on the server. Let's assume you're using Express:
var app = express();
app.get('/recipes/:recipeID', function(req, res) {
var recipeID = req.params.recipeID;
// It would be cool if this existed, huh?
getRecipeAsync(recipeID, function(recipe) {
res.status(200).json(recipe);
});
});
If you send a GET request to your (hypothetical) application (let's say it's https://localhost:8080/recipes/12), you'll get json representing the (admittedly imaginary) recipe with ID 12.
You can accomplish getting the JSON with jQuery (or any other library that makes XHR nice and pretty)
var recipeID = 12;
$.ajax({
url: "/recipes/" + recipeID,
type: "GET"
}).then(function(recipe) {
console.log("Hey! I got the recipe: %O", recipe);
// Note: you might need to use ko.utils.fromJS(recipe) if the returned
// data is JSON that ISN'T deserialized into an object
var recipeObservable = ko.utils.fromJS(recipe);
});
That's about everything you need to know. Obviously, the devil's in the details, but that's basic idea; let me know if that helps!

Django get last GET parameter

I've been working with Django for a few months now so I'm still new at it.
I want to get the last GET parameter from the URL. Here is and example of the URL:
example.com?q=Something&filter1=Test&filter1=New&filter2=Web&filter3=Mine
Is there a way to get the last inserted GET parameter with django? It could be filter1, filter2 or filter3..
Maybe there is a way to do this after the initial refresh with javascript/jQuery?
Thanks!
You can try to parse url parameters yourself. For example:
Python/Django
from urlparse import urlparse, parse_qsl
full_url = ''.join([request.path, '?', request.META['QUERY_STRING']])
#example.com?q=Something&filter1=Test&filter1=New&filter2=Web&filter3=Mine
parameters = parse_qsl(urlparse(full_url)[4])
#[(u'q', u'Something'), (u'filter1', u'Test'), (u'filter1', u'New'), (u'filter2', u'Web'), (u'filter3', u'Mine')]
last_parameter = parameters[-1]
#(u'filter3', u'Mine')
Javascript
var params = window.location.search.split("&");
//["?q=Something", "filter1=Test", "filter1=New", "filter2=Web", "filter3=Mine"]
var last_param = params[params.length-1].replace("?","").split("=");
//["filter3", "Mine"]
This example do not use jQuery and provides basic knowledge of url parsing. There are a lot of libraries, that can do it for you.

How to exclude an object's id property before or during $.toJSON

I'm writing a custom REST adapter for ember-data users with a django rest framework app and need to build a JSON string to do POST/PUT. The only problem is I can't seem to chain another jQuery method after the $.toJSON that removes this.
So far I have an ember.js object that I plan to extract each property from, except my django app doesn't want the id to go along with the HTTP POST
I can get a legit string like so
$.param(record.toJSON());
This results in the following
id=0&username=dat
I'd like a quick way to exclude id when I do this toJSON (does this exist w/ out writing it by hand?) Using jQuery 1.8+
Thank you in advance
Turns out this was really simple
var json_data = record.toJSON();
delete json_data.id;
var data = $.param(json_data);
Now instead of
id=0&username=dat
I now get
username=dat

Categories

Resources