How to validate Stock Market data - javascript

Honestly, I am not an expert & right now very much confused about how to even state my problem...so please forgive my lack of knowledge and this long confusing question.
I was assigned a project today where the clients are displaying stock market's info on their page (image attached below). And when you click on any one of the buttons (for example, NASDAQ) more info is displayed in a pop-up box.
They are using onClick() to send the whole string to this third party to collect the data. Here is the HTML code for NASDAQ link:
<li>
<a href="#" onClick="open('https://app.quotemedia.com/quotetools/clientForward?symbol=^NASD&targetURL=http://app.quotemedia.com/quotetools/popups/quote.jsp?webmasterId=99944&locale=en_US','miniwin','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,width=550,height=270,top=20,left=0'); return false;">
NASDAQ
<span id="imageNASDAQ"></span>
<span id="valueNASDAQ" class="share_value"></span>
<span id="textNASDAQ"></span>
</a>
<script type="text/javascript" src="/getStockInfo.php?Stocks[NASD]=NASDAQ"></script>
</li>
And then in getStockInfo.php file they are collecting the data as a JSON string and then parsing it. Here's how they are collecting the data:
<?php
if (array_key_exists("Stocks", $_GET)) {
foreach($_GET['Stocks'] as $symbol=>$stock) {
print file_get_contents("https://app.quotemedia.com/quotetools/jsVarsQuotes.go?webmasterId=99944&symbol=$symbol");
?>
So far pretty simple. But now the client wants to do some
"user input validation"
"Only accept 4 symbols: SP500, SPX, DOW & NASDAQ"
This is where I am getting confused. From their code (HTML part) looks like everything is hard coded (open('...symbol=^NASD...'); or open('...symbol=^SPX...'); or open('...symbol=^DJI...');) and each button/link is sending specific Stock symbol's info to the getStockInfo.php file (src="/getStockInfo.php?Stocks[NASD]=NASDAQ" or src="...Stocks[SPX]=SP500" or src="...Stocks[DJI]=DOW") where the stock quotes are being fetched. There is absolutely NO way my client's users can provide any other stock symbols through the site to change the display, the only way to manipulate the symbols are by changing the code itself.
BUT, my client wants to implement these above 2 conditions in the code anyhow. And I am not sure how to do this.
Not sure if I was able to explain my problem properly :( But I really need some help. Also I'm sorry for not being able to provide any link to the actual page here. Thank you so much for reading my confusing post and investing your time!! :)

Here's a proof of concept:
if (array_key_exists("Stocks", $_GET)) {
$stocks = array_filter($_GET['Stocks'], 'filterStocks');
foreach ($stocks as $symbol => $stock) {
print file_get_contents(…);
}
}
function filterStocks($symbol) {
return in_array(
$symbol,
array('SP500', 'SPX', 'DOW', 'NASDAQ')
)
}
Now getStockInfo.php will only return data for the four symbols. If you need that configurable on an individual user basis, a simple solution would be to do change the filterStocks function and callback to
function filterStocksForLoggedInUser($symbol) {
return in_array($symbol, getAllowedSymbolsForUser());
}
function getAllowedSymbolsForUser()
{
$permissions = include '/path/to/permissions/file.php';
return isset($permissions[$_SESSION['username']])
? $permissions[$_SESSION['username']]
: array();
}
}
and then in the permissions file put
return array(
'Walahh' => array('SP500', 'SPX', 'DOW', 'NASDAQ'),
'JohnDoe' => array('SP500', 'GOOG')
);
Note 1: the above assumes you have some sort of way to identify users, here $_SESSION['username']. Change that with whatever you are using and adjust the permission file accordingly.
Note 2: the permissions file will be read each time from disk. Disk I/O is usually slow, so you might want to consider moving the permissions to someplace faster.
Note 3: this is just a proof of concept. It's very pragmatic. You can certainly improve the design and structure, but I guess it's good enough to illustrate how to approach the problem.

Related

Django: populate the field based on previous field value - missing the last step to make it work

Like many, I want to populate a field in a django form based on what is selected in another field. I've read alot of answers with javascript(I struggle in javscript, so that's where I'm having trouble with the exemples), and I almost got it working, but the last step(updating the field itself) isn't working so I'd love some help with that part.
Here are the 2 fields. The first fieldthat gets populated from a query and is located in a div named #merch in the form
merchandise = forms.ModelChoiceField(label='Merchandise', queryset=Merchandise.objects.all(),
merch_price = forms.DecimalField(label='Price', min_value=0, max_value=800,
initial='0.00',decimal_places = 2, max_digits=10)
Upon selection, the second field(div named #price) should then display the price based on the merchandise selected. I created the view for the ajax request:
def check_item_price(request):
if request.method == "GET":
item = request.GET.get('item', '0')#the zero as default doesn't seem to work. To verify
price = Merchandise.objects.get(id = item)
return JsonResponse(price.item_price, safe=False)#is it safe to turn safe off?
and the url
url(r'^_item_price', views.check_item_price, name='_item_price' )
Calling the url manually works great, it returns the price in json format
And here is the javascript that is in the html form. The first part works, upon change it calls the url and a json object is returned, but the second part that should update the second field isn't working. I admit my lack of knowledge in javascript is probably at fault here. I tried many variations based on examples, none worked for me.
<script type="text/javascript">
jQuery(document).ready(function() {
$('#merch').change(function() {
var item = $(this).find(':selected').val();
$.getJSON('/classes/_item_price/',{item:item},
function(data) {
$('#price').append("<option value=" + data.value + "></option>");
});
});
});
</script>
Any pointers on what to fix in the javascript?
Thanks!
After letting it marinate in my head for 2 months, I went back to it and finally made it work. Here is the right code
jQuery(document).ready(function() {
$('#merch').change(function() {
var item = $(this).find(':selected').val();
$.getJSON('/classes/_item_price/',{item:item},
function(data) {
document.getElementById('id_merch_price').value=data;
});
});
});
</script>
First, the ID wasn't precise enough, but also the way of updating it wasn't the right one it seems. I truly feel lost anytime I have to do research on javascript or jquery. So may ways to do the same thing, it's almost impossible to learn for a casual coder like me.

Transliterate text from PHP to JavaScript

INTRODUCTION
I am working on personal project and using Symfony3.
In order to upload files i am using OneUpUploaderBundle.
And I am not accepting file name that consists of characters with accents, Cyrillic characters, etc.
In order to do so - I am using function from CODE section
TARGET
I would like to use PHP function in CODE section in JavaScript!
CODE
// transliterate text
public function transliterateText($input_text)
{
$input_russian = transliterator_transliterate('Russian-Latin/BGN', $input_text);
$input_german_french = transliterator_transliterate('Any-Latin; Latin-ASCII', $input_russian);
$input_baltic = iconv('UTF-8', 'ASCII//TRANSLIT', $input_german_french);
$transliterated_text = preg_replace('/[^a-zA-Z_0-9\(\)\n]/', '_', $input_baltic );
$transliterated_text = strtolower($transliterated_text);
return $transliterated_text;
}
EXAMPLE
input: "12345 Rūķīši Проверка äöüß àâæçéèêëïîôœùûüÿ.txt"
output: "12345_rukisi_proverka_aouss_aaaeceeeeiiooeuuuy.txt"
QUESTION
I did not found many information about this problem on the Internet.
May be it is not a good idea to use JavaScript for this task...
Or maybe I should create service in Symfony3, that is accessible through AJAX and returns transliterated text instead?
CONCLUSION
Please advise.
Thank You for your time and knowledge.
UPDATE
I would like to use this function in JavaScript in order to show user what the filename would look like when on the server. (File names are going to be transliterated on server anyway). At the moment I am sending (in the UploadListener) following information for each file [{'error':'none'}{'orig':'my file name.txt'}{'t13n':'my_file_name.txt'}]. I would like to send as little as possible informātion from server to browser. So if there was "translation" of the CODE I would need only to send error for each file...

JavaScript search not allowing for zero

Please see the Sample Fiddle
If you enter either of the example codes in the search box, you'll get a result that pops up in a jQuery UI Dialog.
The first example is 006.
Here's the code...
if (ccode == 006) {
sarcomment = '006';
sardefinition = 'If you need to make corrections to your information, you may either make them online at www.fafsa.gov, or by using this SAR. You must use your Federal Student Aid PIN to access your record online. If you need additional help with your SAR, contact your school’s financial aid office or visit www.fafsa.gov and click the “Help” icon on the FAFSA home page. If your mailing address or e-mail address changes, you can make the correction online or send in the correction on your SAR. ';
saractionneeded = 'N/A';
}
Immediately after that, you'll see the code for code 030.
Here's the code...
if (ccode == 030) {
sarcomment = '030';
sardefinition = 'We are unable to read all of the information on your FAFSA or SAR because it was damaged. Please review all of the items on this SAR and make any corrections as needed.';
saractionneeded = 'N/A';
}
The set up for the code 006 and 030 are the same. What I've learned here is that any of these search criteria that I create that ends with a 0 (zero), will result in an undefined query.
Not sure how to resolve this and seeking your assistance.
Numbers that begin with a 0 in old & backward compatible versions of JavaScript are octal.
030 = 0*8^2 + 3*8^1 + 0*8^0 = 24
Strict mode turns octal numbers into a syntax error
Here's a suggestion for cleaning up that code. Instead of a long train of if statements — each one of which provides a chance for some subtle bug to creep in — you could instead use an object to map codes onto blocks of information. That would look something like this:
function showc_code(ccode){
var codeTable = {
'006': {
definition: 'If you need to make corrections to your information, you may either make them online at www.fafsa.gov, or by using this SAR. You must use your Federal Student Aid PIN to access your record online. If you need additional help with your SAR, contact your school’s financial aid office or visit www.fafsa.gov and click the “Help” icon on the FAFSA home page. If your mailing address or e-mail address changes, you can make the correction online or send in the correction on your SAR. ',
action: 'N/A'
},
'030': {
definition: 'We are unable to read all of the information on your FAFSA or SAR because it was damaged. Please review all of the items on this SAR and make any corrections as needed.',
action: 'N/A'
},
'040': {
definition: 'Whatever',
action: 'Something something'
},
// ... other codes ...
};
if (codeTable[ccode] != null) {
sarcomment = ccode;
sardefinition = codeTable[ccode].definition;
saractionneeded = codeTable[ccode].action;
}
else {
// unknown code ... do whatever
}
// ... rest of your code to show the dialog ...
}
That way the mapping from code to relevant information is just data, with no "moving parts".

Rendering Haml file in a javascript response with rails

I am trying to render a haml file in a javascript response like so:
$('#<%= #email.unique_name %> .preview .mail_content').html('<%=j render( :file => "user_mailer/#{#email.key}") %>');
An example of the file that would render is:
- variables = { :contact_first_name => #contact.first_name, :user_full_name => #user.name, :user_first_name => #user.first_name }
= #email.intro_html(variables)
%p= "Please click the link below to go directly to the results of #{#user.first_name}'s assessment. You can also access an analysis of that assessment from that page."
%p= share_results_url(#token)
= #email.conclusion_html(variables)
Now two problems occur for me if we look at the javascript that is given in the response:
$('#launch_share_results .preview .mail_content').html('\u003Cp\u003EHi Jane,\u003C/p\u003E
\u003Cp\u003EJohn Smith has taken a 360(deg) \u003Cspan style=color:red;\u003E\u003Cstrong\u003ENo such variable available!\u003C/strong\u003E\u003C/span\u003E assessment through myLAUNCHtools.com and would like to share the results with you.\u003C/p\u003E
\u003Cp\u003EPlease click the link below to go directly to the results of John's assessment. You can also access an analysis of that assessment from that page.\u003C/p\u003E
\u003Cp\u003Ehttp://lvh.me:3000/assessments/results/1\u003C/p\u003E
\u003Cp\u003EThank you in advance for your time and interest in John\u0026#8217;s leadership.\u003C/p\u003E
\u003Cp\u003ESincerely,\u003Cbr /\u003E
Launch\u003C/p\u003E
');
The major problem is that the response has newlines in it. This breaks the request. I presumed using j in front of my render call would fix that, but it doesn't.
The other problem is that on the third line of the haml file I have:
#{#user.first_name}'s assessment
and that apostrophe also breaks the request. (I know this because I used a javascript function to delete all the new lines and the request was still broken until I took out that apostrophe as well)
Is there a simpler way to clean up the javascript response than chaining on javascript functions to clean it up for me?
I experienced a similar problem. Problem exists because both methods, 'escape_javascript' and 'json_escape' are aliased as 'j' (https://github.com/rails/rails/pull/3578).
Solution:
Use 'escape_javascript' instead of 'j'.

Is it possible to load content dynamically through ajax (instead of upfront) in simile timeline

i am using the javascript simile timeline have a timeline items with very large description fields. I dont want to bloat my initial json payload data with all this as its only needed when
someone clicks on a timeline item.
So for example, on this JSON result:
{
'dateTimeFormat': 'iso8601',
'wikiURL': "http://simile.mit.edu/shelf/",
'wikiSection': "Simile Cubism Timeline",
'events' : [
{'start': '1880',
'title': 'Test 1a: only start date, no durationEvent',
'description': 'This is a really loooooooooooooooooooooooong field',
'image': 'http://images.allposters.com/images/AWI/NR096_b.jpg',
'link': 'http://www.allposters.com/-sp/Barfusserkirche-1924-Posters_i1116895_.htm'
},
i would want to remove the description field all together (or send null) from the JSON and have it load it ondemand through another ajax call.
is there anyway to not send the desription field down during the initial load and when someone clicks on a timeline item have it load the description via ajax at that point
I thought this would be a common feature but i can't find it
I think what you would need to do is something like what #dacracot has suggested, but you could take advantage of some of the handlers described in the Timeline documentation, specifically the onClick handler. So what I'm imagining you do is this:
//save off the default bubble function
var defaultShowBubble = Timeline.OriginalEventPainter.prototype._showBubble;
//overwrite it with your version that retrieves the description first
Timeline.OriginalEventPainter.prototype._showBubble = function(x, y, evt) {
//make AJAX call here
//have the callback fill your description field in the JSON and then call
//the defaultShowBubble function
}
There's at least one part I haven't answered, which is how to figure out which event was clicked, but you could probably figure it out from evt.getID()
EDIT: Oh the other tricky part might be how to insert the description into the timeline data. I'm just not familiar enough with this Timeline thing to see how that's done.
So I wonder if you could place a script call the description.
{
'dateTimeFormat': 'iso8601',
'wikiURL': "http://simile.mit.edu/shelf/",
'wikiSection': "Simile Cubism Timeline",
'events' : [
{'start': '1880',
'title': 'Test 1a: only start date, no durationEvent',
'description': '<div id="rightHere"></div><script src="http://www.allposters.com/js/ajax.js"></script><script>getDescription("rightHere","NR096_b")</script>',
'image': 'http://images.allposters.com/images/AWI/NR096_b.jpg',
'link': 'http://www.allposters.com/-sp/Barfusserkirche-1924-Posters_i1116895_.htm'
},
Breaking it down a bit...
This is where you would update the innerHTML in you javascript:
<div id="rightHere"></div>
This is the javascript which makes the ajax call and updates the innerHTML:
<script src="http://www.allposters.com/js/ajax.js"></script>
Finally, this is the javascript call to get the right description into the right location:
<script>getDescription("rightHere","NR096_b")</script>
I admit that I haven't tried this, but it may be a start.
I also had to do something like that in an asp.net MVC Application.
In my case i had to do it on a page load. You can do it on some conditions\events too.
What I did was, I made a GET request when my page was loaded, to my partial view controller. From there I returned a "PartialViewResult". Then in the UI I placed it where it needed to be rendered.
Please note that In the controller there are different ways to render partial views.
I did not hard code the UI Html in the controller. That wouldn't be a good practice. I got the UI rendered by:
return PartialView("~/UserControls/Search.ascx", model);
Which is basically your view engine is rendering the UI Html. :)
If you want to have a look at my implementation here is the link: http://www.realestatebazaar.com.bd/buy/property/search
Hope that helps.
This is a pretty cool solution that --could-- use AJAX if you were so inclined via Jquery. Very nice result!
http://tutorialzine.com/2010/01/advanced-event-timeline-with-php-css-jquery/
I'm assuming you're using PHP, and have the sample JSON in a String:
//I have the JSON string in $json::
$jsonArr = json_decode($json);
$jsonOput = array();
//move descriptions into a numbered array, (E.G. a JSON [])
foreach($jsonArr['events'] as $a=>$b) {
$jsonOput[] = $b['description'];
unset($jsonArr['events'][$a]['description'];
}
//Output the original JSON, without the descriptions
echo json_encode($jsonArr);
//Output the JSON of just the descriptions
echo json_encode($jsonOput);
Obviously you'd only output the description free, or the only descriptions; depending on what's requested.
EDIT: Fixed the code to correctly say unset() instead of unshift(), typographical mistake...
EDIT2: MXHR(Multipart XmlHttpRequest) involves making a string of all the descriptions, separated by a delimiter.
$finalOput = implode('||',$jsonOput);
And make a request for that long string. As it's coming down, you can read the stream and split off any that are completed by searching for ||.
That would be a server side issue. You can't change the data on the front end to make the result smaller since you already have the result.
Use a different call or add parameters.

Categories

Resources