How can I handle a big json string in TYPO3 - json

I have developed a little order extension where customers can design a business card. This extension uses a canvas in association with fabric.js.
Customers can add some text, simple forms, images and so on and the result of her customization is a json string which I bind via jquery to an hidden input to store this data in a property image when the form is submitted.
FLUID:
<f:form.hidden class="custom-image" property="image" />
JS:
$('.step3 .custom-image').val(getJsonOfCanvas());
HTML result:
<input class="custom-image" type="hidden" name="tx_example_orderform[step3data][image]" value="{"objects":[{"type":"rect","originX":"left","originY":"top","left":761,"top":181,"width":50,"height":50,"fill":"#68e5e7","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":0.8,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","transformMatrix":null,"params":{"base":1,"x":761,"y":181,"scaleX":1,"scaleY":1},"rx":0,"ry":0}],"background":""}">
So business card modifications increase the value of this hidden input -> a lot of modifications = big json string.
In a later order step customers can check and edit her entries and also can edit her business card again. For this reason I am using the same json string to load the canvas again:
FLUID (little bit tricky because it's inline js):
<script type="text/javascript">
<![CDATA[var jsonCanvasString = ]]>
<f:if condition="{step3data.image}">
<f:then>
<f:format.htmlentitiesDecode>{step3data.image}</f:format.htmlentitiesDecode>
</f:then>
<f:else>
''
</f:else>
</f:if>
<![CDATA[;]]>
</script>
JS:
if (typeof jsonCanvasString !== 'undefined') {
canvas.loadFromJSON(jsonCanvasString, canvas.renderAll.bind(canvas));
}
This works great when the json string is not so big, but when he is too long I get a blank page and nothing will be rendered, but if I debug my image property I can see that's the property image is still set:
Any suggestions?
Maybe is there a better way to store the json string and pass him from js to php or from php to js?
Hope you can help me :)

Related

Extracting data from API to html elements

I am not an experienced coder so excuse me if my explanation isn't perfect.
I'm making an html page and I'd like there to be a section that shows some Osu! stats. There's this osu api that spits out all of the information I could possibly need but there's a litle bit too much of it.
https://osu.ppy.sh/api/get_user?k=ff96ad02d159e0acad3282ad33e43a710dac96d5&u=Sceleri
The above returns:
[{"user_id":"6962718","username":"Sceleri","count300":"93129","count100":"15744","count50":"3404","playcount":"776","ranked_score":"184300015","total_score":"258886799","pp_rank":"345687","level":"34.115","pp_raw":"314.239","accuracy":"94.54791259765625","count_rank_ss":"1","count_rank_s":"55","count_rank_a":"74","country":"FI","pp_country_rank":"4112","events":[]}]
I'd like to parse a few numbers from there. Example:
"pp_raw":"314.239" -> <p>;314.239</p>;
The <p> would be inside a div and so on, where I can specify some CSS to it and make it look good. The main problem is extracting the data to separate <p> elements.
I have executed this with regex in Rainmeter before (I had help) but I have no idea how to do it in html.
Use Jquery ajax calls. The url you posted basically gives you a json object.
HTML:
<div id="pp_raw">
</div>
Jquery
$.get( "https://osu.ppy.sh/api/get_user?k=ff96ad02d159e0acad3282ad33e43a710dac96d5&u=Sceleri", function( data ) {
//You can put whatever you want in the style attr to make things pretty
$( "#pp_raw" ).html("<p style='color:red'>"+data[0]['pp_raw']+"</p> ");
});
JSFiddle:
https://jsfiddle.net/rwt5mdyk/8/

How to send a more complex POST form?

I have the following table where a user can choose some quanitity for a corresponding item.
What is the simplest way to send this data to the server without using JavaScript?
Right now I am creating a data-name with item's name on each quantity input field. Then grabbing all those input fields, followed by the $.post request (not shown here).
var items = [];
var $quantities = $('.quantity');
$.each($quantities, function(index, input) {
items.push({
name: $(input).data('name'),
quantity: $(input).val()
});
});
I am curious to know if there is a more elegant approach to do this with just using the HTML form element.
Edit: I am free to choose whatever model I see fit. No constraints there since this is a fresh from the start personal project.
You could create a traditional HTML form.
<form method="post" action="/url/to/submit/to.php" id="orderform">
<table>
... all your order table code ...
<input type="text" name="cucumber" value="0">
... and all your input code ....
... etc ...
</table>
</form>
Then have the action URL be a server-side script that processes the form data and returns an appropriate webpage. Note: this will require the webpage to reload.
The nice thing about JavaScript is you can submit the form data and not have to reload the webpage.
Also note, you can get your HTML form data using jQuery very easily. In my above example:
var formData = $('#orderform').serializeArray();
Now use can use formData in your $.post() script.
If you put the item names into hidden input fields in the form, you can use:
$('#formID').serialize()
to get all the inputs in one step, and pass this as the data argument to $.post().
In this way you can send form data using ajax
$.ajax({
url:'TarfetPage.jsp',
type:'POST',
datatype:'text',
data:$('#formID').serialize(),
success:function(data)
{
$("#divId").html($.trim(data));
}
});

Need to update date code mm/dd/yyyy in in several webpages without using code

I need to get the date from the server in mm/dd/yyyy without any javascript or asp code. I would prefer to do this as either a link that flows in the current document frame and that also injects the mm/dd/yyyy into the current html web page as css or other non code based solution. I don't want to use any extraneous querying languages like xslt, xquery, or plinq either.
example:
<h3>Date:<date format="mm/dd/yyyy" src="currentdate.asp" /></h3>
output:
Date:06/26/2012
No, this is an impossible task.
HTML is a static language. It is impossible to use a static language without any dynamic element (javascript, php, ssi, etc.) and have it change the page.
You will need to find a way to loosen the constrains for your project as it is currently not only impossible but illogical.
EDIT:
I thought of one potential way but it wouldn't be pretty.
You could use an <iframe src="date.asp"> and if the date.asp only returned the date then it would work. This is the only way possible.
as he others say you cannot achieve this without at least a bit of javascript. what you could do is use jquery to select all your date tags and then post an ajax to get the current date in your preferred format.
like so:
<script type="text/javascript">
$(document).ready(function(){
$("date").each(function(index, element) {
var d = $(this);
$.post("ullu.asp", {
ajax: true,
act: "currentdate",
format: d.attr("format")
}, function(data) {
d.after("<span>" + data + "</span>");
});
});
});
</script>
<h3>Date:<date format="%m/%d/%Y" /></h3>
then on ullu.asp:
<%
if request("ajax") = "true" then
dim d : d = DateTime.FormatDate(request("format"), now)
response.write d
end if
%>
DateTime is here a class of mine for formatting dates you could use your own implementation... Furthermore you could add another attribute to your tag like "src" to send your ajax there.
i know you wanted to do this without "using code" but that is not possible. with this solution you only have to add a bit of javascript which handles all your tags...
You can always make it an img, then use an on the fly img generator which generates text as an image from the server. You can use something like csImageFile for generating text in an image on the fly.
http://www.chestysoft.com/imagefile/default.asp
Your image would look like this:
<img src="date.asp" />
Then your date.asp file would be generating a new image (using response.contenttype="image/jpeg" with the current date on each call.
But your date would be displayed as an image, not text.
Or you can use an iFrame like the secretformula's answer, or Ajax/jQuery for this. But if you're not gathering the data from the server, then your date will from the client.

Adapting web pages for foreign language support

I have created a set of 13 HTML/CSS/JS templates for CMS integration in the English language.
I need to include support for foreign languages, specifically Russian, Chinese and Arabic. Initial searches online haven't turned up any central resource for guidance on what is required for supporting different languages in HTML.
I understand I'll need to look at things like my font-stacks and character encoding and the Arabic templates will need particular support with my entire layout switching for the right-to-left reading style.
Can anyone point me to some reliable resources for doing this in a standards-compliant way? All templates must meet WCAG 2.0 AA requirements.
Step 1
To start, let’s assume we have the following HTML:
<div>Hello there, how are you?</div>
This DIV layer contains our title. Now, we have decided we want this title to be available in multiple languages. Our first step is adding a class to the div so we can identify it later on:
<div class="title">Hello there, how are you?</div>
Step 2
With that ready, we’re just two steps away. First off, we are going to create an XML file that includes our translations. In this XML file, we can store translations for multiple phrases and we can easily add more languages at a later stage. We shall save this file as languages.xml and save it in the same folder as our HTML file.
<?xml version="1.0" encoding="UTF-8"?>
<translations>
<translation id="title">
<english>Hello there, how are you?</english>
<italian>Ciao, come stai?</italian>
</translation>
</translations>
You will store all phrases you want to translate between the <translations></translations> tags. You will store each phrase in a <translation></translation> tag. In order to identify which phrase is being translated, we need to add the id=”title”. The name should match the name of the CSS class you assigned in the HTML. Finally, we can put the translations inside and surround them by tags defining the language. For instance, we need to put the Italian text in between <italian></italian> tags. Keep in mind that you can easily change the names of these tags – For example, you may choose to use <eng></eng> and <ita></ita> instead.
Step 3
With that complete, you just need to add jQuery to read the XML file and replace the contents of your DIVs based on the language selected. Here you go:
<script src="path/to/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(function() {
var language = 'italian';
$.ajax({
url: 'language.xml',
success: function(xml) {
$(xml).find('translation').each(function(){
var id = $(this).attr('id');
var text = $(this).find(language).text();
$("." + id).html(text);
});
}
});
});
</script>
That’s all the code needed – Have a look at it again with comments this time:
// Include jQuery script
<script src="path/to/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
// $(function() { should be used
// each time you use jQuery
$(function() {
// Here we set the language
// we want to display:
var language = 'italian';
// In order to get the translations,
// we must use Ajax to load the XML
// file and replace the contents
// of the DIVs that need translating
$.ajax({
// Here, we specify the file that
// contains our translations
url: 'language.xml',
// The following code is run when
// the file is successfully read
success: function(xml) {
// jQuery will find all <translation>
// tags and loop through each of them
$(xml).find('translation').each(function(){
// We fetch the id we set in the XML
// file and set a var 'id'
var id = $(this).attr('id');
// This is the most important step.
// Based on the language we can set,
// jQuery will search for a matching
// tag and return the text inside it
var text = $(this).find(language).text();
// Last, but not least, we set the
// contents of the DIV with a
// class name matching the id in the
// XML file to the text we just
// fetched
$("." + id).html(text);
});
}
});
});
</script>
And that’s it! Refresh your page and the Italian version should load, replacing the default English one. In the example above, we set the language manually:
var language = 'italian';
We could just as easily set that via PHP:
var language = '<?php echo $sLanguage; ?>';
Or by reading it from the URL – you can use this jQuery Plugin to do that.
Bonus Trick
As you add more languages, you will realize that phrases are longer in certain languages and shorter in others. We might want to have custom CSS for each language. Taking the example above, we would initially have the following:
div.title { font-size:30px; }
What if we wanted the Italian to have a smaller font? Easy! We need to make a slight modification to our jQuery:
$(function() {
var language = 'italian';
$.ajax({
url: 'language.xml',
success: function(xml) {
$(xml).find('translation').each(function(){
var id = $(this).attr('id');
var text = $(this).find(language).text();
$("." + id).html(text);
// Here's the new line we're adding.
// We are assigned the DIV a new class
// which includes the old class name
// plus a "_language" - In this case,
// loading Italian would assign the DIV
// a "title_italian" class
$("." + id).addClass(id + '_' + language);
});
}
});
});
Now that we’ve added that line, we can just add the following CSS:
div.title { font-size:30px; }
div.title_italian { font-size:20px; }
Your Italian text should now be smaller. Note: In order for this to work, you must put the new language CSS definitions underneath the default one. Switching those two lines around will not work.
Sorry for the late answer, but better late than never... :-)
Francois answer is a good solution for a simple and quick solution.
For a more complete and flexible solution (with plural forms handling, for example...), please have a look at: i18next.
They provide:
support for variables
support for nesting
support for context
support for multiple plural forms
gettext support
sprintf supported
detect language
graceful translation lookup
jquery function
get string or object tree
get resourcefiles from server
resource caching in browser
post missing resources to server
highly configurable
custom post processing
translation ui
I'm using i18next solution myself, though I would personally prefer a server-side solution to avoid any additional burden on client side... :-)
N.B. I have no relation at all with i18next.com... :-)

Displaying the JSON in HTML input boxes using AJAX?

I'm very new at AJAX and Javascript and need a bit of help with this code.
Here is the bit of JSON I'm using
{"URL":"www.youtube.com","Total URLs":132,"Completed":63}
I need to get each one of these values and display in different HTML input text boxes using AJAX.
Current URL: <input type="text" name="urlqueue">
Total URLs: <input type="text" name="total">
Completed: <input type="text" name="completed">
Right now I have
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.form.total.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "test_results.php", true);
ajaxRequest.send(null);
You can see this doesn't work anymore. I use to have the file containing only 1 number and no JSON. Now I need to use the file for many results with JSON and need some direction.
How do I display the JSON in the HTML input boxes using AJAX?
Parse the JSON, either by using a JSON parsing library or by using eval. Note that using eval can be very dangerous, as you can introduce cross-site scripting vulnerabilities if it is used incorrectly.
The resulting object will have the values, so you can set each field individually by, for example:
document.form.total.value = jsonObject["Total URLs"];
Note that when you make an AJAX and retrieve the response, the response text is not JavaScript object. It's just string so you should evaluate the string to JavaScript Object. The following code will produce that in a quick way. But Douglas Crockford who is the master of JavaScript says that "eval is evil".
var data = eval('(' + ajaxRequest.responseText + ')');
document.form.total.value = data[Total URLs]
also I want to remember that avoid spaces in property names. For example, you should have a property named "Total_URLs" or "TotalURLs" etc. instead of "Total URLs"