this time I'm looking for something really special.
In my PHP page, I got a table generated by a Javascript, here is the example :
Example Page
This table is racing game results. I didn't write the JS, and I can't change the format of the results.
What I need is to parse these results to get variables, to generate championship results giving points to guys, adding points of multiple series, etc...
I tried :
Parsing with DOMDocument, also substr, but as it's JS generated it can't work.
>>this solution<< which sounded good but it doesn't work.
Do you guys have any idea to get an exploitable array ?
If not, what do you suggest as alternative solution ? I'm not able to reproduce the JS in a PHP function, too hard.
Here is the JS : click
Thank you !
Here's how you'd be able to parse the initial array in PHP:
$url = 'http://mxs-concept.com/liveresults/test.php';
$page = file_get_contents($url); // fetch the page
preg_match('/resultslines=(.+)print_race_analysis/sim', $page, $matches); // find javascript array
$js = preg_replace('/,\s+\]$/', ']', $matches[1]); // fix last comma before "]"
$array = json_decode($js); // decode the array
var_dump($array); // see the exact array you had in javascript
However, after reading your edit, it seems that you'd need more work if you're taking the PHP way. You might want to try to install NodeJS and make it parse the JS but might be an overkill. If I would you, I'd translate the JS to PHP even if it will take a day just because NodeJS might take a week instead.
Related
So I am using a plugin for tags in a form and it works well but I am having troubles with the suggestions.
You can have an autocompleter by specifying an attribute
suggestions: ['Black','White','Red','Blue','Green','Orange']
Thing is, I have to make a call to a servlet to find the keywords to put in there, so I end up with a String that I try to pass to the attribute.
var dataFromServlet = "'Black','White','Red','Blue','Green','Orange'";
suggestions: [dataFromServlet]
Thing is, now the completer assumes the ENTIRE String is one element.
I have been at this for hours and I can't for the life of me figure out how to solve this seemingly very simple problem. I have tried using arrays, passing JSON from the servlet instead and parsing it, splitting the string and using a loop to rebuild it differently, nothing works. This is driving me crazy, I feel like I'm missing something very obvious.
The plugin documentation does suggest a different method for fetching suggestions via ajax calls, but it ends up calling the ajax method on every single keypress and it lags the whole thing out.
The best solution, have the backend return a proper JSON object. That way you do not have to worry about your hacky solution breaking because of the data in the string.
If for some problem out of your control you can not make a change to the back end, you can convert to an array by reformatting the string and using JSON.parse
var dataFromServlet = "'Black','White','Red','Blue','Green','Orange'";
var obj = {
suggestions: JSON.parse("[" + dataFromServlet.replace(/'/g, '"') + "]")
};
console.log(obj.suggestions);
Again, this solution is a bandaid, the correct solution is make the back end servlet return proper JSON formatted data.
What I did here is trying to replace JSON.stringify() with something else, to avoid RangeError. And I found the method below.
This is my code: (I use big-json module and this module implement json-stream-stringify for stringify)
const data = generateData();
const stringifyStream = json.createStringifyStream({
body: data
});
stringifyStream.on('data', function(str) {
console.log(str.toString());
})
I tried to print the str, it will print the string type data line by line, my question is: how to write the complete str to a file? I tried to add fs.writefileSync() after the console.log() and it will only write in the last line of str. Sorry I am new to stream and node.js. Hvae no idea how to fix it.
The other question is, can I find a way to re-format the output string just like JSON.stringify(data, null, 2) did?
FYI: The data is a really deep object. No circular, but may have repeated part. And I prefer to keep everything unchanged and not pruned.
Really appreciate any help here! Thank you for your time.
Have you tried separating JSON.stringify from fs.writeFileSync ? just to know wich one is actually having problems.
If it is JSON.stringify I suggest you to fragment the object in multiple ones or filter what you use. Whatever you can do to reduce the actual data. We don't know what de data really is so I cannot make assumptions on that but you never have those problems generally, if it's caused by the data being too big, you are doing things wrong!
If the problem is fs.writeFileSync and you have your JSON stringified then try using fs.createWriteStream to write the data.
I'm programming in oTree (which is a Django based environment for social experiments) and I have the following problem. I defined some lists in Python and I'd like to import them and use them in an HTML template. If I print them in HTML I manage to see them without any problem, however, once I need to use them in Javascript, the program fails to read them and the single quotes of the elements of the list are converted in '.
The list is imported like this var filtered_elements = {{ array }};.
I think the problem is exactly here, as JS cannot work with them. Do you have any suggestion on how to do that? I considered using JSON, but since I'm quite new to programming, I cannot understand if it's just a waste of time or there is a simpler way out.
Thanks for your answers!
It sounds like your data is already JSON, otherwise you would be getting single quotes and u prefixes. So the only issue is Django autoescaping; you can disable it with the safe filter:
var filtered_elements = {{ array|safe }};
Your data should be JSON, instead of putting the Python list into the contact directly, put "array": json.dumps(array) in the context dictionary.
The JSON string doesn't need HTML escaping inside a tag, but it does need JS escaping! Otherwise some string may include something like </script><script>absolutely anything goes here... to run arbitrary JavaScript, if the JSON contains user data.
So use |escapejs:
var filtered_elements = {{ array|escapejs}};
I want to load my initial page with php, so instead of making rest call to get variable, I already have the variable in my page , I need it to some way assign it to angular. I saw different ways for doing it like
<.....ng-init="somefunction('<?echo $myjsonstring?>')">
but this is not working as it thinks that my json string ends at the first double codes .I though to replace double codes with some special symbol and in angular to replace it back but this require some processing which I think will reduce its performance. Is there any other way to do this?
Try json_encode:
<...ng-init="somefunction('<?php echo json_encode($myjsonstring); ?>')">
If you want to build a 'complicated' JSON, You can use the Simple JSON for PHP like this :
<...ng-init="somefunction('<?php
include('includes/json.php');
$Json = new json();
$Json->add("teachers", $teachers_object);
$Json->add("users", $users_object);
$Json->add("someArray",$anArray);
echo $Json->make();
?>')">
Sorry I couldn't be more descriptive with the title, I will elaborate fully below:
I have a web application that I want to implement some AJAX functionality into. Currently, it is running ASP.NET 3.5 with VB.NET codebehind. My current "problem" is I want to dynamically be able to populate a DIV when a user clicks an item on a list. The list item currently contains a HttpUtility.UrlEncode() (ASP.NET) string of the content that should appear in the DIV.
Example:
<li onclick="setFAQ('The+maximum+number+of+digits+a+patient+account+number+can+contain+is+ten+(10).');">
What is the maximum number of digits a patient account number can contain?</li>
I can decode the string partially with the JavaScript function unescape() but it does not fully decode the string. I would much rather pass the JavaScript function the faq ID then somehow pull the information from the database where it originates.
I am 99% sure it is impossible to call an ASP function from within a JavaScript function, so I am kind of stumped. I am kind of new to AJAX/ASP.NET so this is a learning experience for me.
First of all, if you're pulling the questions from the db on page load you most likely have all the answers too, so just keep going with your current approach by jamming the answers into the page as your code sample is doing. Unless your FAQ list has thousands and thousands of questions, doing it the "AJAX way" by hitting the db on each click of the list item doesn't give you much here IMO. If it does have that many questions then a straight list is the wrong way to go anyway.
Secondly, two things to keep in mind re your approach:
you're placing html inside an html attribute
the attribute is specifying a javascript function to call
So you need to make sure your "answer" escapes both html and is valid js. By valid js I mean it can't have new lines and must escape quotes properly. For example, the following html - although valid html - won't fire the onclick and you'd just get a js syntax error:
<li onclick="setFAQ('This line's
multi line and has a single quote in it!')"
To account for these I would say HttpUtility.HtmlAttributeEncode in tandem with System.Web.Script.Serialization.JavaScriptSerializer is more appropriate to the markup you've shown.
JavaScriptSerializer json = new JavaScriptSerializer();
string answerString = "This line's\nmulti line and has a single quote in it!";
string onClickJS = String.Format("setFAQ({0})", json.Serialize(answerString));
string onClickAttr = HttpUtility.HtmlAttributeEncode(onClickJs);
Even better, use .NET's ListItem object and lose HtmlAttributeEncode altogether:
ListItem faqItem = new ListItem(questionString);
faqItem.Attributes.Add("onclick", String.Format("setFAQ({0})", json.Serialize(answerString)));
The html portion is escaped automatically for you, plus it's a lot cleaner.
As for your javascript, you don't have to decode anything in setFAQ(). Just take its argument and put it in into you "answer" div:
function setFAQ(answer) {
document.getElementById('answer').innerHTML = answer
}
I think just using HttpUtility.HtmlEncode may solve your problem. I'm not sure I follow completely though : \