i have an XMLHttpRequest.The request passes a parameter to my php server code in /var/www. But i cannot seem to be able to extract the parameter back at the server side. below i have pasted both the codes:
javascript:
function getUsers(u)
{
alert(u);//here u is 'http://start.ubuntu.com/9.10'
xmlhttp=new XMLHttpRequest();
var url="http://localhost/servercode.php"+"?q="+u;
xmlhttp.onreadystatechange= useHttpResponse;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function useHttpResponse()
{
if (xmlhttp.readyState==4 )
{
var response = eval('('+xmlhttp.responseText+')');
for(i=0;i<response.Users.length;i++)
alert(response.Users[i].UserId);
}
}
servercode.php:
<?php
$q=$_GET["q"];
//$q="http://start.ubuntu.com/9.10";
$con=mysql_connect("localhost","root","blaze");
if(!$con)
{die('could not connect to database'.mysql.error());
}
mysql_select_db("BLAZE",$con) or die("No such Db");
$result=mysql_query("SELECT * FROM USERURL WHERE URL='$q'");
if($result == null)
echo 'nobody online';
else
{
header('Content-type: text/html');
echo "{\"Users\":[";
while($row=mysql_fetch_array($result))
{
echo '{"UserId":"'.$row[UsrID].'"},';
}
echo "]}";
}
mysql_close($con);
?>
this is not giving the required result...although the commented statement , where the variable is assigned explicitly the value of the argument works...it alerts me the required output...but somehow the GET method's parameter is not reaching my php or thats how i think it is....pls help....
If u is http://start.ubuntu.com/9.10 as you write, the URL gets garbled because : is a forbidden character in a URL.
You need to escape the URL using encodeURIComponent() in Javascript, and urldecode() it back in PHP. Docs here and here.
The JavaScript part would look like so:
var url="http://localhost/servercode.php"+"?q="+encodeURIComponent(u);
and the PHP part:
$q=urldecode($_GET["q"]);
your mySQL query is also vulnerable to a SQL injection, which is highly dangerous. You should at least sanitize $q using mysql_real_escape_string(). See this question for an overview on the problem, and possible solutions.
Related
I'm trying to make a simple HTTP module, similar to express, to help learn how to use HTTP.
When working with express I often use parameters such as:
app.get('/id/:id' (req, res) => {console.log(req.params.id); stuff})
I was wondering-
Is it possible just using HTTP?
If it isn't able to be done with just HTTP, then how would you go about creating it?
Your question is a little bit confusing but I think what you mean is how to implement an HTTP Router in pure javascript instead of relying on a framework like express.
If that's the case I support your initiative 100%! It's really important to understand what is going on behind the scenes.
A good way to really understand a good way to do so would be by reading the source code of a good router that is already out there.
You could study the Express router's source code but I recommend you to go play with find-my-way which is a dedicated router that you can use with HTTP only without any other framework.
Yes but you need to process it manually.
Assuming you're using node's http module, the information you are looking for is in req.url but it includes the whole url path.
For example, you want to parse /id/:id, and the browser is making a request to http://your.server/id/100?something=something. Then the value of req.url will be:
/id/100?something=something
But if you are writing an HTTP module from scratch using the net module then you need to know the format of an HTTP request. Basically an HTTP request looks like a text file with the following format:
GET /id/100?something=something HTTP/1.1
Host: your.server
The header section ends with double newlines. Technically it should be \r\n\r\n but \n\n is also acceptable. You first need to get the url from the first line of the request between the protocol (GET in the example above but can be POST, PUT etc.) and the HTTP version number.
For anyone interested in writing a HTTP server from scratch I always recommend James Marshall's excellent article: https://www.jmarshall.com/easy/http/. It was originally written in the late 90s but to this day I haven't found a clearer summary of the HTTP protocol. I've used it myself to write my first HTTP server.
Now you have to write code to extract the 100 from the string.
If you are doing this manually, not trying to write a framework like Express, you can do it like this:
const matches = req.url.match(/id\/([^\/?]+)/);
const id = matches[1];
If you want to write a library to interpret the /id/:id pattern you can maybe do something like this (note: not an optimized implementation, also it behaves slightly differently to express):
function matchRoute (req, route) {
const [ urlpath, query ] = req.url.split('?'); // separate path and query
const pathParts = urlpath.split('/');
const routeParts = urlpath.split('/');
let params = {};
for (let i=0; i<pathParts.length; i++) {
if (routeParts[i].match(/^:/)) { // if route part starts with ":"
// this is a parameter:
params[routeParts[i].replace(':','')] = pathParts[i];
}
else {
if (routeParts[i] !== urlParts[i]) {
return false; // false means path does not match route
}
}
// if we get here (don't return early) it means
// the route matches the path, copy all found params to req.params:
req.params = params;
return true; // true signifies a match so we should process this route
}
}
// Test:
let req.url = '/id/100';
let result = matchRoute(req, '/id/:id');
console.log(result, req.params); // should print "true, {id:100}"
I'm trying to push one inputless TV screen dashboard (using chromecast) with azure authentication in nodejs (working fine without auth so far)
My best move (?) is using ms-rest-azure package allowing to perform initial authentication from another device with https://aka.ms/devicelogin & a code
However, is there a clean way to retrieve this code and make it available outside the console ? I can't find reference or callback.
My fallback scenario would be to intercept process.stdout.write but feels like dirty.
There is an options object you can pass to interactiveLogin. One option is "userCodeResponseLogger", which should be a function, eg
let options = {"userCodeResponseLogger":(msg)=>{
console.log("I have the message",msg)
}
}
msRestAzure.interactiveLogin(options).then((credentials) => {
// doing authentication stuff
});
Note you'll still need to parse the msg to extract the code.
had to go forward on this issue and finally ends up by intercepting process.stdout.write with a better implementation then mine : https://gist.github.com/pguillory/729616/32aa9dd5b5881f6f2719db835424a7cb96dfdfd6
function auth() {
hook_stdout(function(std) {
var matches = / the code (.*) to /.exec(std);
if(matches !== null && matches.length >=2) {
var code = matches[1];
// doing something with the code
unhook();
}
});
msRestAzure.interactiveLogin().then((credentials) => {
// doing authentication stuff
});
}
I an new to NetSuite, and I am having a problem. I have created a button on a form through a user event script.
The button calls a client script, which executes a saved search. The search result should be displayed to the user.
Everything is located in one file:
function userEventBeforeLoad_AddSearchButton(type, form, request){
if(type == 'view' || type == 'edit'){
form.setScript('customscript_tvg_project_search_button');
var projectid = nlapiGetFieldValue('companyname');
form.addButton("custpage_search", "KHM Search", "performSearch('" + projectid + "')");
}
}
function performSearch(projectid) {
console.log('test in client');
alert('projectid = ' + projectid);
var obj = nlapiLoadSearch(null, 'customsearch_project_cost_detail_sublist');
obj.setRedirectURLToSearchResults();
}
I created a user event script record for userEventBeforeLoad_AddSearchButton(). and a client script record for performSearch().
In the code above, the button is created and the alert is being displayed. But no redirect is happening.
When I look at the result in Firebug it looks like this:
{"result":"\/app\/common\/search\/searchresults.nl?api=T","id":5}
Any ideas why the redirect is not happening, and what to do?
Edit: My code above was stripped down to simplify. The reason I am passing projectid over is that I actually need to filter the search result, suing the following two lines:
var searchFilter = new nlobjSearchFilter('job', null, 'anyof', projectid);
obj.addFilter(searchFilter)
Although the documentation does state that, "This method is supported in afterSubmit user event scripts, Suitelets, and client scripts", it seems from this NS User Group post by a Netsuite Employee in reply to someone who experienced the same issue as you, that the API does not actually perform the redirection client side:
Redirection works on server side. Use window.location.assign(url) to
navigate via script in client-side.
Testing this, I can see that setRedirectURLToSearchResults does appear to correctly "load the search into the session", so adding this line afterwards should fix your problem.
window.location = '/app/common/search/searchresults.nl?api=T';
setRedirectURLToSearchResults is not working for me either, but since you are using clientscript you might want to try this:
function performSearch(projectid) {
console.log('test in client');
alert('projectid = ' + projectid);
var searchid = 'customsearch_project_cost_detail_sublist';
location = '/app/common/search/searchresults.nl?searchid=' + searchid;
}
This Groovy code outputs an empty string:
def url = 'http://www.wikidata.org/w/api.php?action=wbgetentities&sites=enwiki&titles=Mozambique&format=xml&props='.toURL()
print url.getText('utf-8')
With the same URL, curl also returns empty, but curl -L returns the XML I want.
Is there something for Groovy that is similar to that -L option?
-L: If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option will make curl redo the request on the new place.
Groovy uses Java's HttpUrlConnection under the covers, which doesn't automatically follow redirects. However,here is a small function that will handle it for you by checking the status and location header on the response and call the redirected URL if necessary:
def findRealUrl(url) {
HttpURLConnection conn = url.openConnection()
conn.followRedirects = false
conn.requestMethod = 'HEAD'
if(conn.responseCode in [301,302]) {
if (conn.headerFields.'Location') {
return findRealUrl(conn.headerFields.Location.first().toURL())
} else {
throw new RuntimeException('Failed to follow redirect')
}
}
return url
}
The code can be downloaded on GitHub.
I would like to extract the file extension from a url. For example, http://www.url.com/index.html. I would something like a function extension, where extension(http://www.url.com/index.html) return http. The task is trivial in the case of the URL I have given, but what if I have query parameters, i.e. http://www.url.com/index.html?q=bar?
UPDATE:
This is what I've gotten so far:
function extension(url) {
var components = url.split('/');
var lastComponent = components[components.length-1];
return lastComponent.split('?')[0].split('.')[1];
}
I have't tested it extensively yet. Is there better?
This can be done without introducing vars, as:
var fileExtension = function( url ) {
return url.split('.').pop().split(/\#|\?/)[0];
}