I have a PHP page that displays data using different variables submitted through the URL. For instance:
index.php?rownum=30&colnum=2&qlang=en
I need to give the user the ability to change the sort order.
For that I have added an HTML <select> with two options calling my re_order() function which should basically call the same URL with all parameters intact except the new sort order.
Is there an easy way to perform that or should I use a PHP session to see what parameters have been set before?
That's a task that should be handled by the client.
You can probably do something like this:
location.search = location.search.replace(/([&?]sort)(?:=[^&]*)?(?=&|$)/i, '$1=newvalue');
You can make it a reusable function:
function setUrlParam(searchString, param, value) {
var rx = new RegExp('([&?]' + param + ')(?:=[^&]*)?(?=&|$)', 'i'),
encodedVal = encodeURIComponent(value);
return rx.test(searchString)?
searchString.replace(rx, '$1=' + encodedVal) :
searchString += '&' + param + '=' + encodedVal;
}
location.search = setUrlParam(location.search, 'sort', 'date');
Related
I am trying to retrieve the value attribute of an unsubmitted input field as parameter to a URL that opens/saves an excel file. The Parameters are supposed to be used to filter the excel file.
I have tried using a for()-loop to save the parameters into an array and then proceed to use the append() method to add them to the end of the url.
Code below shows how I am trying to singularly append each parameter one after the other
var url = new URL("file:database/reports/getCurrentStorageOverview.php?params=excel");
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
search_params.append('params', $("#searchParameter1").val());
search_params.append('params', $("#searchParameter2").val());
search_params.append('params', $("#searchParameter3").val());
search_params.append('params', $("#searchParameter4").val());
url.search = search_params.toString();
var new_url = url.toString();
window.open("database/reports/getCurrentStorageOverview.php?params=excel");
console.log(new_url);
The parameters are supposed to be added to the end of the url however the console keeps telling me the value attribute is either undefined/ when i was trying to use an array it was filling the array with 4 "undefined(s)"
it's a different aproach but since i haven't tested your method i can show u what i normally use for this case:
const querify = obj => {
return Object.keys(obj)
.map(key => {
if (typeof obj[key] === 'object') {
return querify(obj[key])
} else {
return `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`
}
})
.join('&') }
what this does is it takes an object like
var filters = { page: 1, length: 10, sortBy: 'id', etc... }
and turns it into a query string that looks like "page=1&length=10&sortBy=id" etc so u can use it like this:
var url = `database/reports/getCurrentStorageOverview.php?${querify(filters)}`
<script>
//some code here
var content = '<div onclick="populatedata(\'' + obj.Records[t] + '\')" >';
function populatedata(obj) {
console.log(typeof obj);
}
</script>
Now output of the above code is string, but I want object content in function populatedata.
As #nnnnnn Suggested I had passed index of record in function and received it in populatedata.
<script>
//some code here
var content = "<div onclick="populatedata("+t+")>";
function populatedata(index) {
console.log(obj.Records[index]); //this is just for illustration
//further processing here
}
</script>
You didn't clarify what type obj.Records[t] is, but I guess it is an object. So you have problem because result of concatenation with a String is always a new string, with toString() applied to non-string types (obj.Records[t] in your case).
What you need to do is to stringify your object manually so that you control string presentation yourself:
var content = '<div onclick="populatedata(' + JSON.stringify(obj.Records[t]) + ')">';
Then result of such concatenation would be something like (if obj.Records[t] = {name: 123}):
<div onclick="populatedata({"name":123})">
which will allow populatedata invocation with proper parameter.
If you want to be able to further process the argument of populatedata, you'll first want to stringify it, then change your function from logging the typeof to just the object.
var content = "<div onclick='populatedata(" + JSON.stringify(obj.Records[t]) + ")'>test</div>";
function populatedata(obj) {
// do things with obj here
console.log(obj);
}
However, as Oriol mentioned in a comment on your question, you probably don't want to take that approach. It's better to:
Manage handlers through the dom API
Pass data objects in programmatically as opposed to embedding them into the dom
I have objects in Parse called "Post" and within that, I have columns called "title" and "content". I am trying to ask the user for an input value and save this as "remove". If the user's input value ("remove") matches a "title" value already saved in parse.com, I want to delete the entire row in parse, so that both the "title", "content" and everything else in the row is deleted. The deleting part is not working so I am wondering if my code is actually making it go through all the data saved in parse and find the one that matches the user's input and then delete it.
What am I doing incorrectly and what can I change to make it delete the entire row?
Thank you in advance.
function getPosts(){
var query = new Parse.Query(Post);
query.find({
success: function(results){
for(var i in results){
var title = results[i].get("title");
var content = results[i].get("content");
var remove = $("#post-remove").val();
console.log("Remove: "+remove);
console.log("MAC Address: " +title);
console.log("place: "+content);
if (title == remove)
{
window.alert("The MAC address matches.");
console.log(remove+" matches " + title+ " and is located in " +content);
var Post = Parse.Object.extend("Post");
var query = new Parse.Query(Post);
query.find("objectId", {
success: function(yourObj){
//console.log(yourObj);
//Post.destroy({}); //if title matches remove, delete the Post (title and content) (but it's not deleting it)
Post.remove("title");
Post.remove("content");
}
});
}
}
}
});
}
To clarify and add a bit to #JakeT's acceptable answer:
1) find objects to delete like this:
function postsMatching(title) {
var Post = Parse.Object.extend("Post");
var query = new Parse.Query(Post);
query.equalTo("title", title);
return query.find();
}
2) Delete an array of parse objects like this:
Parse.Object.destroyAll(posts);
3) Put the two ideas together (returning a promise to find then delete) like this:
var title = $("#post-remove").val();
postsMatching(title).then(function(posts) {
console.log("deleting " + JSON.stringify(posts));
Parse.Object.destroyAll(posts);
}, function(error) {
console.log("error " + JSON.stringify(error));
});
First of, you can use the Parse.Query.equalTo(key, value) method to filter for the Post/s you are looking for. That will render a lot of your logic unnecessary.
Additionally, since most parse calls are asynchronous, I would suggest learning about Parse Promises and using those instead of the call backs you're using.
Finally, you don't need a second nested query, since you already have the object you are trying to destroy. You just need to call destroy() on that object, and if you have some extra content you need to take care of deleting (i.e., your 'content' is a pointer to another object that is owned only by the Post you are deleting), you should set up a beforeDestroy() trigger for the Post object in your cloud code that will delete that pointer as well.
I use this site to download required info about lat/ lon of districts of India.
http://india.csis.u-tokyo.ac.jp/
Can I get all the districts of a give state using python? For e.g. if I choose State: maharashtra I get the list of districts like Akola, Raigarh in the next drop down list. I need that info as a python list.
I can see that a javascript function is called and it is getting the data from /api/ directory.
function setDistrictList() {
var selected = "";
state = $("#state_list").val();
districts = {};
url = "/api/getDistrictList";
Is it possible that I can get this list of districts programmatically using python?
update:
I have tried this function. But that returns the results and not the Java Script drop down list that I expect.
def __getVillageMarkersFromWeb(self,query, state_code=None, district_code=None):
stateString = '"state":"' + state_code + '"' if state_code is not None else ""
districtString = ',"district":"' + district_code + '"' if district_code is not None else ""
f_param = '{' + stateString + districtString + '}'
params = urllib.urlencode({"q":query,"f":f_param})
url = "http://india.csis.u-tokyo.ac.jp/geocode-cgi/census_ajax_json.cgi"
http = httplib2.Http()
response, markers_xml = http.request(url, "POST", params)
dom = minidom.parseString(markers_xml)
markers = dom.getElementsByTagName("marker")
return markers
You could, using BeautifulSoup.
BeautifulSoup allows you to target elements with particular class/id after you've gotten the markup from a page using Requests/urllib/urllib2.
Then you can loop through your BS object and save each to your list.
If the content on a page is generated with JavaScript, PhantomJS can emulate the JS before the markup is scraped.
I'm creating HTML markup in Javascript by concatinating string elements. Something like this:
var makeButton = function (el) {
'use strict';
var config = el.attr("data-config"),
dyn = $.parseJSON(config),
hover = false,
state = 'up',
hrf = '',
...
if (dyn.href) {
hrf = 'href="' + dyn.href + '" ';
}
...
// when all variables have been set, concat
iconspan = dyn.icon ? '<span class="ui-icon ' + icn + icp + ics + '"> </span>' : '';
textspan = '<span class="ui-btn-text">' + txt + '</span>';
innerspan = '<span class="ui-btn-inner">' + textspan + iconspan + '</span>';
btn = '<a data-role="button" data-wrapperels="span" class="ui-btn ' + hvr + cls + '" ' + data_icp + data_thm + data_min + data_inl + '>' + innerspan + '</a>';
return btn;
};
When all is set, I'm returning the string to the calling function, where it is inserted into other strings being created. I'm wondering if it's at all possible to store any information on what I'm creating. Since I'm not instantiating into jQuery (= $( btn )) I can't add any information using something like data().
Question:
So if I have a plain "string", what alternatives do I have (if any) to store information on that string?
So if I have a plain "string", what alternatives do I have (if any) to store information on that string?
None. primitive values can have no properties, so you can't store anything on them. Either you switch to objects, or you store the information in some other static structure where it is identified by the string value (of course your function would need to return distinctive strings then, and garbage-collection is somewhat complicated).
So you could just use String objects wrapping the strings you want to return. They will have the same behaviour in primitive operations (e.g. concatenation) but you can store additional information on them:
btn = new String(btn);
btn.data = …;
return btn;
I'm not entirely sure what you're trying to achieve (it might be worth considering a templating language like mustache.js or underscore templates instead of concatenating strings), but if you want to create a relationship between two disperate bits of data, then an Associative Array should do the job.
// Use a JavaScript object as an Associative Array.
dataByButtonMarkupMap = {};
// Build your button markup as before.
btnMarkup = "..."
// Use the markup as a Key in the associative array, don't worry that it's massive, as long
// as it's a string (or can be coerced to one), it can be used as a key.
dataByButtonMarkupMap[btnMarkup] = "some data";
// You can now retrieve that data via the button markup
var myData = dataByButtonMarkupMap[btnMarkup];
It might be worth considering refactoring your design so that instead of passing strings around, you return an object which encapsulates both the template string and the data, eg:
function makeButton() {
// ...
// Return an object instead of a string so you can encapsualte
// additional data alongside the template string.
return {
template: btn,
data: "some data"
}
}
Hope that helps.