Re-Render some data on the same template - javascript

I have a scenario where-in by-default I would be rendering some data from JSON on my JSP page. Now, I want to achieve a use-case wherein when I click on some menu-item it would trigger a function and that should in response update the template with the relevant data.
So for initial loading I am loading the data from JSON using:
$.getJSON( "/somelocation/test.json", function( data ) {
console.log(data); //json output
var template = $.templates("#theContent");
var htmlOutput = template.render(data, {selectedValue: "abc"});
$("#mainBody").html(htmlOutput);
});
Now I write the same logic in a function which will be triggered on the menu item click then on the JSP page I just see "#theContent" as an output. Can you please suggest what might be an issue.

If you pass a string to $.templates(someString), then JsRender will first attempt to treat it as a jQuery selector. If jQuery is loaded and the selector does return a script element for a template then that template will be used.
If the string is not valid selector or does not return a script element for a template block, then JsRender will fall back on treating the string as template markup.
You can test in the context of your code whether $("#theContent") does return a non-empty jQuery object. ($("#theContent").length === 1). It looks as if in your code it is not finding a script element with ID "theContent".

Related

Pass and use data from json to javascript

I have a javascript function that I am calling in a php page. I also added a json method to this function that pulls data from the database. Here's what it looks like:
$this->registerJsFile('/js/restaurant-reserve.js', ['depends' => [JqueryAsset::class]]);
$this->registerJs('restaurantReserve.init('. Json::encode($restaurant->workHours) .')');
As a result, at the end of the page, I get this data in the form:
restaurantReserve.init([{"id":86,"restaurant_id":1,"day":"Mon","open":"9.30","close":"14.30","created_at":"2022-02-22 10:56:15"}])
But I want to use this data in the javascript file itself, where the restaurantReserve function is located.
Because now I have to do it manually:
let json = [{"id":86,"restaurant_id":1,"day":"Mon","open":"9.30","close":"14.30","created_at":"2022-02-22 10:56:15"}]
How can I make json data come to javascript so that I can use it? To not write it by hand.
update
One of the answers came up to me, it was to add this line, which will globally declare this variable:
$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';');
But it turns out that this variable is declared after the execution of the script of this restaurant-reserve.js file where this variable is used, and I don’t understand a little how to make it higher.
Here is my final code in php file:
$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';');
$this->registerJsFile('/js/restaurant-reserve.js', ['depends' => [JqueryAsset::class]]);
$this->registerJs('restaurantReserve.init()');
And what I get as a result on the page, first comes the file, then this variable:
<script src="/js/restaurant-detail.js"></script>
<script src="/js/share.js"></script>
<script>jQuery(function ($) {
let json = [{"id"...}]
</script>
What can be done??
The second argument in registerJs is related to this issue.
That is, The second argument determines at which position the script should be inserted into the page. Possible values are:
View::POS_HEAD for head section.
View::POS_BEGIN for right after opening <body>.
View::POS_END for right before closing </body>.
View::POS_READY for executing code on the document ready event. This will automatically register jQuery and wrap the code into the appropriate jQuery code. This is the default position.
View::POS_LOAD for executing code on the document load event. Same as the above, this will also register jQuery automatically.
The first argument is the actual JS code we want to insert into the
page. It will be wrapped into a tag. The second argument
determines at which position the script should be inserted into the
page.
For scriptFiles you can also specify the place and time to load it. According to the dependencies and ....
It is better to refer to this link.
You may add following line in the code
$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';');
Updating the answer after reading your comments and further queries.
You may pass second one more parameters to registerJs function.
View::POS_READY or View::POS_BEGIN
Like :
$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';', View::POS_READY);

javascript replace string continueable

I got a code that replaces a string. Here is my HTML created by my PHP code.
...
foreach ($notes as $note) {
echo '<li><input name="noteTypeID" type="radio" class="noteTypeID" value="'.$note['NOTETYPEID'].'"></li>';
}
...
foreach (...) {
...
echo '<li class="getshrtcode">[srms_more_info id="'.$cnt.'" instanceID="'.$val_id.'" type="'.$val_type.'" noteCodeID="" planID=""]</li>';
...
}
my script is like this:
jQuery(document).ready(function(){
var noteTypeID = null;
var planID = null;
jQuery('.noteTypeID').click(function() {
noteTypeID = jQuery(this).val();
planID = prompt("Enter a Template planID value from axcelerate");
jQuery('.getshrtcode').each(function(){
jQuery(this).text(jQuery(this).text().replace('noteCodeID=""', 'noteCodeID="'+ noteTypeID +'"'));
jQuery(this).text(jQuery(this).text().replace('planID=""', 'planID="'+ planID +'"'));
});
});
});
the 1st change is fine but the next is not. I see that it can't re assign the .getshrtcode text because the planID and noteCodeID string have value. Is it possible to turn it noteCodeID="" planID="" again?
You are trying to set a non-DOM entity with jquery which is not possible. When you have a template engine to generate HTML, the template code gets executed and gives results before any javascript loads, so you cannot set template properties unless the template engine itself provides you a mechanism to do this.
If you really want the customer to specify a certain template plan ID to present him with something specific, you need to load your page through an AJAX call where you send a request to the server passing noteCodeID & planID and respond with the desired HTML that comes as a result of the custom template engine execution.
If you have custom attributes in your HTML that you want to set using jquery, then you can simply use attr function :
$('#foobar').attr('foo','bar');

Showing results from JSON only when filter is selected

Objective
I want display results only when it's respective state is selected. Currently all results are shown by default when the page loads.
I do not want anything to load by default. When a state is selected then those results should populate.
Background
I have a location selection feature that I am working on at this CodePen.
It used MustacheJS for templating
and is populated by data in a JSON file by this script
$(function() {
$.getJSON('https://s3-us-west-2.amazonaws.com/s.cdpn.io/161741/labs.js', function(data) {
var template = $('#labsListStates').html();
var html = Mustache.to_html(template, data);
$('#states').html(html);
});
});
The results can be filtered by state with. It runs on this script
/* Filter for locations */
$('#lab-state-select').on('change', function (e) {
e.preventDefault();
var cat = $(this).val();
var nam = $(this).val();
$('#states > div').hide();
$('#states > div[data-category-type="'+cat+'"][data-category-name="'+nam+'"]').show();
});
Problems
I know that this is sloppy. I am not using pure JSON but actually creating a Javascript object. And even named the file to end with .js so that it would work. I read about how that is a bad practice at http://www.kryptonite-dove.com/blog/load-json-file-locally-using-pure-javascript
That taught me to look into a XMLHttpRequest. But even implementing that I am still confused how to display the data I need when I need it. I think I am on the correct track by looking into the
.on() but would appreciate some additional help.
You simply use $('#states > div').hide(); to hide the data right after you load the data: $('#states').html(html);.
You can check out the fork here: http://codepen.io/anon/pen/lBims
As for getting the JSON file, you can simply return it with any file type. You don't have to use a .js extension if it's just pure JSON output. And JSON is just a stringified representation for Javascript objects, so it's fine treating JSON as an object. In Fact that's what you're supposed to do. JSON = JavaScript Object Notation.

Displaying data from a database using jQuery and Javascript

I'm trying to display specific parts of a Cloudant database. This database contains many separate documents, and each document contains a category called "results". I'm trying to display whatever is in results. Each document is identified by its own id. I tried using the get() method in jQuery, but unfortunately it is not running successfully.
function grabData(){
var url = 'https://cloudant.com/futon/document.html?acharya%2Ftoxtweet/ff558f75077e8c758523cd3bd8ffdf88';
$.get(url, function(data) {
$('.result').html(data);
alert("Data loaded: " + data);
});
}
grabData();
I'm not entirely sure where I went wrong...Should I consider using SQL instead of ajax?
I think your issue it this:
replace this:
grabData();
with this:
$(document).ready(function(){
grabData();
});
or more shortened:
$(function(){
grabData();
});
The URL you are using is returning an entire webpage.
Your jQuery code is looking for an element on the current page with a class name of result and trying to change it's inner HTML to the response from the URL.
You didn't provide any additional code to look at, but I would assume that is not what you were expecting it to do.
I assume you are wanting to parse through the entire url, but in your current code the page will be processed as a raw string and not a DOM object. So you would have to parse through that string with regular expressions, etc.

How can one incorporate JSON data with the returned HTML on the first request to the home page?

My scenario is this - the user asks for the home page and then the javascript code of the page executes an ajax GET request to the same server to get some object.
The server keeps the home page as a jade template.
So, right now it takes two roundtrips to load the home page:
GET the home page
GET the JSON object
I am OK with it, but just out of curiosity - what are my options to incorporate the object requested later into the initial GET request of the home page?
I see one way is to have a hidden html element, which inner HTML would be the string representation of the object. A bit awkward, but pretty simple on the server side, given that the home page jade template is preprocessed anyway.
What are my other options?
Please, note that I am perfectly aware that sparing this one roundtrip does not really matter. I am just curious about the techniques.
Another option is to always return a JSON object, then the HTML for your home page would be the value of some property on this object. This would probably require some changes on your client-side logic, though.
One more option: instead of a hidden HTML input/textarea containing a JSON string, the home page code could contain a script block where an object literal is declared as a variable. Something like this:
<script>
var myObj = ... // Your JSON string here.
// myObj will be an object literal, and you won't need
// to parse the JSON.
</script>
The initial GET request will retrieve just that document. You can have additional documents loaded defined as scripts at the bottom of your page, so you don't need to do a XHR, for the initial load.
For instance:
GET /index.html
//At the bottom you have a <script src="/somedata.js"></script>
GET /somedata.js
//here you define you var myObj = {}.... as suggested by bfavertto
Depending on which server side technology are you using, this could be for instance in MVC3
public partial class SomeDataController : BaseController
{
public virtual ContentResult SomeData()
{
var someObject = //GET the JSON
return Content("var myObj = " + someObject, "application/javascript");
}
}
You can embed the Json data inside a hidden tag in your HTML. At runtime, your javascript reads the data from this hidden tag instead of making a Json call (or make the call if this data is not available).
<!--the contents of this div will be filled at server side with a Json string-->
<div id="my-json-data" style="display:hidden">[...json data...]</div>
on document ready:
var jsonStr = document.getElementById( "my-json-data" ).innerHTML;

Categories

Resources