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

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.

Related

Yii Cgridview update function not working

I've been working for this for a very long time and I'm nowhere near to understanding what I'm doing so wrong (yii beginner so please show some patience with me).
I have this code in my view code
echo CHtml::dropDownList('symptomCategory',
'', // selected item from the $data
$this->getSymptomCategories(),
array(
'id'=>'categorySelectDropDown',
'prompt'=>"Select Symptom Category",
));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'symptoms-grid',
'selectableRows'=>1, //ability to select one symptom at a time
'dataProvider'=>$model2->search(),
//'htmlOptions'=>array('id'=>'symptomsSelectGrid'),
'columns'=>array(
'symptomCode',
'title',
'inclusions',
'exclusions',
'symptomCategory',
),
));
And my js function is this:
$('#categorySelectDropDown').change(function()
{
var symptomCategory = $('#categorySelectDropDown').val();
$('#symptoms-grid').yiiGridView('update',
{
data: symptomCategory.serialize()
});
return false;
});
I've tried with $(this).serialize() too. Anyway.
According to examples I've found online this should work, but nope, it doesn't update the cgridview. $this->getSymptomCategories() returns an array of array('A'=>'A','B'=>'B' ect. ect.)
BTW I am creating a model2 = new Symptoms; inside a view rendered by a controller of a different model because I want to use the choice from the gridview to fill in a form of the other model. Any help, documentation (haven't found any useful online), advice, ect will be really appreciated. Thank you for oyur time
Try this way of updating yiiGridView
$.fn.yiiGridView.update('symptoms-grid', {
data: $('#symptomCategory').serialize() // your form id
});
There can be many reasons why yiiGridView seems like it is not updating, one of the them is that AJAX request is not being sent, another common reason is that search condition logic is not correct, or the requested action does not pass the post data to the model, resulting in the same data being returned, making it look like it is not updating.
See if the AJAX request going to the server from firebug/console etc. If it is going then check if the post data is correct and finally check the model+controller logic is correct and the criteria of CActiveDataProvider is reflecting your search condition

How to make a form submit return the specified result using AJAX & JSON?

I'm working on a basic year, make, model dependent drop down menu, but started working backwards. I'm currently working on making my success callback dependent on the model drop down selection. For instance, if I choose 2006, lexus, is250, I only want my success callback to display that vehicle.
Most of my code can be found http://codepen.io/cfavela/pen/bozie/ (make sure to collapse the CSS page to make it easier to read)
My results page (modelsTest.html) contains the following:
{
"Car": "2012 Chevrolet Avalanche",
"Price": "$10,999",
"Features": "Soft seats!"
"Img": "/css/img/2012_Avalanche.jpeg"
}
What I've tried to do is add another car using an array and $.each, but the problem with this result is that it returns every vehicle if I click on search. How can I make the success callback dependent on the model selected?
As I commented above, according to this SO How to read the post request parameters using javascript, you can not get post data at client side level, you would need a server side to do that.
So you could try using GET and form your query ($('#vehicle').val()) as part of query string, then base on the query string, do some javascript logic at modelsTest.html and return the json you want. (but I don't think this will work, because I don't think you can return pure json in a real html file, so guessing your modelsTest.html just contain json. but I could be wrong hence I leave this as a possible solution)
or do the filtering in the success: function() before append to the msg.

Select2 issue more than one result

I have a problem with Select2 where it will only allow one section in the <input>. I cannot use <select> with the multiple as it is a limitation of select2 apparently when using ajax for data results.
Sample code (json data is at the bottom) http://jsfiddle.net/YeEmP/
id: function(data){
return {
product_id: data.product_id
};
}
I suspect the problem is with the above code but can't be sure. When searching for a model eg D7000 it appears correctly like the example shown here
However if I search for another model number i.e D7100 it will say no results found but the ajax request returns the model just as if it was D7000.
If I search for the model it didn't recognise first it works, vice versa.
I'm not sure what I am doing wrong but my complete code can be found in the jsfiddle link, it might not work as my datasource is ajax in the example but I have passed the json array as a commented out section.

parse foursquare json without 3rd party

Im using foursquare API in a web app, and I have the call to foursquare and the results dead on, but I can't parse it out in the way that I want. I don't want to use a 3rd party parser because those have confused me thoroughly. I want the app to alert out a list of clickable venue names, by distance, and when clicked a variable is assigned to the lat and lng of that venue.
$(document).ready(function(){
$.getJSON("https://api.foursquare.com/v2/venues/search?ll=-27.58818,-48.523248&
client_id=9&client_secret=9&v=20111107",
function(data){
//code here
});
});
The results look like this:
{"meta":
{"code":200},
"response":
{"venues":
[{"id":"4c158143a1010f47a1364e18",
"name":"Parma Pizza",
"contact":{"phone":"+554832346363","formattedPhone":"+55 48 3234-6363"},
"location":{"address":"R. Lauro Linhares, 1052",
"lat":-27.588341,
"lng":48.5232834,
"distance":18,
So far ive tried 3rd party Jackson with fail, alerting out names with fail, document.write with fail, and some type of .$each remover which also failed. Please help I am so stuck.
jQuery is already parsing your JSON file with $.getJSON. Unless you're using an old browser you don't need a 3rd party JSON parsing library. (Although you should include JSON3.js in your code base just in case someone trying to use your site is in an old browser. Just include it. You don't need to do anything else other than that.)
The data variable being passed into the callback function is a JavaScript object. You can then just do data.meta.code to get the value of code (200), or data.response[0].name to return Parma Pizza.
As for generating your list you're going to have to do the hard work. You can use $.each to iterate though the places easily though:
$.getJSON("https://api.foursquare.com/v2/venues/search?ll=-27.58818,-48.523248&client_id=9&client_secret=9&v=20111107", function(data){
$.each(data.response, function(index, elm){
console.log(elm.name);
});
});
Will print out a list of all the venue names returned from your query.
# Celeste
I think you can fix it by adding .venues in the code from tkone.
Atleast this worked for me.
$.getJSON("https://api.foursquare.com/v2/venues/search?ll=-27.58818,-48.523248&client_id=9&client_secret=9&v=20111107", function(data){
$.each(data.response.venues, function(index, elm){
console.log(elm.name);
});
Sorry for not commenting on tkone's answer, but I don't have reputation enough to comment :/ strange system ....

webOS/Ares : read JSON from URL, assign to label

I've used the webOS Ares tool to create a relatively simple App. It displays an image and underneath the image are two labels. One is static, and the other label should be updated with new information by tapping the image.
When I tap the image, I wish to obtain a JSON object via a URL (http://jonathanstark.com/card/api/latest). The typcial JSON that is returned looks like this:
{"balance":{"amount":"0","amount_formatted":"$0.00","balance_id":"28087","created_at":"2011-08-09T12:17:02-0700","message":"My balance is $0.00 as of Aug 9th at 3:17pm EDT (America\/New_York)"}}
I want to parse the JSON's "amount_formatted" field and assign the result to the dynamic label (called cardBalance in main-chrome.js). I know that the JSON should return a single object, per the API.
If that goes well, I will create an additional label and convert/assign the "created_at" field to an additional label, but I want to walk before I run.
I'm having some trouble using AJAX to get the JSON, parse the JSON, and assign a string to one of the labels.
After I get this working, I plan to see if I can load this result on the application's load instead of first requiring the user to tap.
So far, this is my code in the main-assistant.js file. jCard is the image.
Code:
function MainAssistant(argFromPusher) {}
MainAssistant.prototype = {
setup: function() {
Ares.setupSceneAssistant(this);
},
cleanup: function() {
Ares.cleanupSceneAssistant(this);
},
giveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
},
jcardImageTap: function(inSender, event) {
//get "amount_formatted" in JSON from http://jonathanstark.com/card/api/latest
//and assign it to the "updatedBalance" label.
// I need to use Ajax.Request here.
Mojo.Log.info("Requesting latest card balance from Jonathan's Card");
var balanceRequest = new Ajax.Request("http://jonathanstark.com/card/api/latest", {
method: 'get',
evalJSON: 'false',
onSuccess: this.balanceRequestSuccess.bind(this),
onFailure: this.balanceRequestFailure.bind(this)
});
//After I can get the balance working, also get "created_at", parse it, and reformat it in the local time prefs.
},
//Test
balanceRequestSuccess: function(balanceResponse) {
//Chrome says that the page is returning X-JSON.
balanceJSON = balanceResponse.headerJSON;
var balanceAmtFromWeb = balanceJSON.getElementsByTagName("amount_formatted");
Mojo.Log.info(balanceAmtFromWeb[0]);
//The label I wish to update is named "updatedBalance" in main-chrome.js
updatedBalance.label = balanceAmtFromWeb[0];
},
balanceRequestFailure: function(balanceResponse) {
Mojo.Log.info("Failed to get the card balance: " + balanceResponse.getAllHeaders());
Mojo.Log.info(balanceResponse.responseText);
Mojo.Controller.errorDialog("Failed to load the latest card balance.");
},
//End test
btnGiveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
}
};
Here is a screenshot of the application running in the Chrome browser:
In the browser, I get some additional errors that weren't present in the Ares log viewer:
XMLHttpRequest cannot load http://jonathanstark.com/card/api/latest. Origin https://ares.palm.com is not allowed by Access-Control-Allow-Origin.
and
Refused to get unsafe header "X-JSON"
Any assistance is appreciated.
Ajax is the right tool for the job. Since webOS comes packaged with the Prototype library, try using it's Ajax.Request function to do the job. To see some examples of it, you can check out the source code to a webOS app I wrote, Plogger, that accesses Blogger on webOS using Ajax calls. In particular, the source for my post-list-assistant is probably the cleanest to look at to get the idea.
Ajax is pretty much the way you want to get data, even if it sometimes feels like overkill, since it's one of the few ways you can get asynchronous behavior in JavaScript. Otherwise you'd end up with code that hangs the interface while waiting on a response from a server (JavaScript is single threaded).

Categories

Resources