JQuery UI Tabs width JSON Response - json

I have some tabs with jquery ui. Each link should receive a json response, but I am unable to make it work.
This is the active one:
<li class="ui-state-default ui-corner-top ui-tabs-active ui-state-active" role="tab" tabindex="0" aria-controls="ui-tabs-1" aria-labelledby="ui-id-1" aria-selected="true">
comments
</li>
response is:
[{"created_at":"2013-07-12T22:51:46Z","id":8,"programa_id":88,"sent_at":"2013-07-12T22:51:46Z","texto":"testing","updated_at":"2013-07-12T22:51:46Z","user_id":null}]
I tried several things, but best approach is:
$( "#tab_messages" ).tabs({
heightStyle: "fill",
beforeLoad: function( event, ui ) {
ui.ajaxSettings.dataType = "json";
ui.ajaxSettings.dataFilter = function(data) {
var jsonData = $.parseJSON(data);
alert(jsonData[0].texto);
return jsonData[1].texto;
};
ui.jqXHR.error(function() {
ui.panel.html(
"Couldn't load this tab. We'll try to fix this as soon as possible. " +
"If this wouldn't be a demo." );
});
}});
});
Panel don't load (jqXHR.error appears), but if I return jsonData[1].texto, it works.

I don't know if it is the best solution, but if I delete ui.jqXHR.error function and set panel's html from dataFilter, it seems to work:
ui.ajaxSettings.dataFilter = function(data) {
var jsonData = $.parseJSON(data);
var htmlpanel = "";
$.each(jsonData, function(index, value){
htmlpanel += "<li>" + value.texto + "</li>";
});
ui.panel.html(htmlpanel);
};

Related

Some HTML buttons aren't working

I have a small website and it is complete. I am just a senior and it is just for a project on learning how to code. Everything works to perfection on the source computer that it was all coded on. I then exported the files and tried on several other computers. The files open up and everything looks okay, but two out of the five HTML buttons won't work. Is there a common reason why this is happening?
This is the java function for the button
$('#createPassSubmit').click(function() {
var create = true;
var location = $('[name="reason"]').val();
var passnumber = $('#passnumber').val();
var note = $('[name="notes"]').val();
var student = $('#studentID').val();
var teacher = $('#teacherID').val();
var dataString = "CreatePass="+create+"&reason="+location+"&notes="+note+"&studentID="+student+"&teacherID="+teacher+"&passnumber="+passnumber;
$.ajax({
method: 'POST',
url: 'ajax.php',
data: dataString,
success: function(data) {
if(JSON.parse(data) === 'ERROR') {
alert("Pass " + passnumber + " is currently in use");
}
else {
$('#form input[type=text]').val('');
$("#form select").val('')
$('#sname').val('');
}
}
});
});
});
Then this is the HTML button its self
<input type="button" id="createPassSubmit" value="Create">

Display a new html/web page in panel

I am developing an addon for firefox using addon-SDK method. I would like to know if there is anyway to change the html(contentURL) displayed in that panel to a new webpage upon clicking a link in that contentURL. Thanks in advance.
Vignesh here's code that receives the url clicked on:
https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/panel#Scripting_panel_content
var myScript = "window.addEventListener('click', function(event) {" +
" var t = event.target;" +
" if (t.nodeName == 'A')" +
" self.port.emit('click-link', t.toString());" +
"}, false);"
var panel = require("sdk/panel").Panel({
contentURL: "http://www.bbc.co.uk/mobile/index.html",
contentScript: myScript
});
panel.port.on("click-link", function(url) {
console.log(url);
});
panel.show();
So then you can change that to be instead of console.log(url) you can make it find your panel and changes its iframes location to that url. Im not sure how to do this with sdk methods, maybe someone else can share. I would try to do this though:
panel.port.on("click-link", function(url) {
panel.contentURL = url;
});
edit:
panel.contentURL = url may not work so you have to do it like this:
const { getMostRecentBrowserWindow } = require('sdk/window/utils');
var aXULBrowser = getMostRecentBrowserWindow();
aXULBrowser.getElementById('ID OF YOUR PANEL, probably same as id to your widget here').getElementsByTagName('iframe').contentWindow.location = url;

How convert JSON data to html table

I get real-time statistics for myself and the data in JSON format. The problem is, I can not figure how can I get this table in html web page.
Data can be found at: http://testinki.info/apidata/
I have tried something like this, but without success:
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://testinki.info/apidata/";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].apikey +
"</td></tr>"
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
Any ideas? How to solve the problem?
AngularJS might be a good solution for the task. With data from your link, code will look something like this:
Api key: {{data.apikey}}
<br>
User:
<pre>{{data.data|json}}</pre>
<br>
<table>
<tr ng-repeat="member in data.Members">
<td>{{member.name}}</td>
<td>{{member.info}}</td>
</tr>
</table>
angular
.module("app", [])
.controller("ctrl", function ($http, $scope, $http) {
$http
.get("http://testinki.info/apidata/")
.then(function (res) {
$scope.data = res;
})
})
JSBin example. I've changed $http to $timeout and predefined data since your API does not allow cross-origin requests.

Why is & turning into & after page load?

I'm using Firefox and working on a page when I notice that & turns into &.
Usually I can fix this by using html_entitiy_decode() - but in this case it's not working.
Then I discovered this. The alert is fired once the page is loaded.
Before
After
The data is loaded using PHP / Yii - not through JS / Ajax. I am however adding / removing brands using JS Knockout.
<ul data-bind="template: { name: 'brand-item-template', data: $root.brands}">
<li>
<span id="<?= $brand->id?>" data-bind="text: brand_name, attr: {'id': brand_id}"><?= $brand->name; ?></span>
</li>
</ul>
Update
I've discovered that this JS Knockout code is what makes the change. But this code should not be triggered until I add a brand. So why is this affecting my &s?
It's the self.addBrand = function() that makes the change. If I remove this function and leave the rest as it is, everything is fine. Can it be a Knockout bug?
$('#store.manage-special-offers').exists(function(){
Store.mangeSpecialOffers();
});
function manageBrandListModel() {
var self = this;
var store_id = $('.data-item-id').val();
var exiting_list = $('.brand-list ul').clone();
// Data
self.brands = ko.observableArray(create_list(exiting_list));
self.brand_name = ko.observable();
self.brand_id = ko.observable();
self.store_id = ko.observable(store_id);
// This is the function that makes the chage
self.addBrand = function() {
if (self.brand_name() != "") {
// Update DB
$('#store.manage-brands').exists(function(){
$.ajax({
url: site_url + '/associatebrand',
type: "POST",
dataType: 'json',
data: {
Brand: {
brandId : self.brand_id(),
storeId : self.store_id(),
add : true
}
},
success: function (data) {
// Add brand to GUI list
self.brands.push(new brand(self.brand_id(), self.brand_name()));
self.brand_name("");
}
});
});
}
}.bind(self);
(...)
function create_list(exiting_list){
var arr_list = [];
$(exiting_list).find('li').each(function(e,li){
var id = $(li).find('span').prop('id');
var name = $(li).find('span').html(); // <--- This is the problem. Must be .text()
arr_list.push(new brand(id,name));
});
return arr_list;
}
Can anyone explain why this is happening?
The credit should really go to both JeremyCook and Quentin for pointing me in the right direction.
$(exiting_list).find('li').each(function(e,li){
var id = $(li).find('span').prop('id');
var name = $(li).find('span').html(); // <--- This is the problem. Must be .text()
arr_list.push(new brand(id,name));
});
What I did wrong was that I used .html() and the text was returned in HTML format. Changing this to .text() solved my problem.

Parse JSON from twitter using JQUERY

I want to search a tweet from twitter, it will depend on text or hashtag. Then Show it on <div id="result"> . but i get confused because my code doesn't show the tweet.
Here is my code to read JSON from twitter search :
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#btn').click(function()
{
$.getJSON("http://search.twitter.com/search.json?q="+$('#search').val(),function(data)
{
$.each(data.results, function(i,data){
var from = data.from_user;
var tw_content = data.text;
$('#result').append("<p>User : "+from+"<br>Tweet : "+tw_content+"</p>");
});
});
});
});
</script>
<input type="text" id="search"/><input type="button" id="btn" value="cari">
<div id="result">
</div>
And while I run this, nothing happen. anyone can help me ?
I would do something like below:
$(document).ready(function() {
// Declare variables to hold twitter API url and user name
var twitter_api_url = 'http://search.twitter.com/search.json';
var twitter_user = 'behudinnystrom';
// Enable caching
$.ajaxSetup({ cache: true });
// Send JSON request
// The returned JSON object will have a property called "results" where we find
// a list of the tweets matching our request query
$.getJSON(
twitter_api_url + '?callback=?&rpp=5&q=from:' + twitter_user,
function(data) {
$.each(data.results, function(i, tweet) {
// Uncomment line below to show tweet data in Fire Bug console
// Very helpful to find out what is available in the tweet objects
//console.log(tweet);
// Before we continue we check that we got data
if(tweet.text !== undefined) {
// Calculate how many hours ago was the tweet posted
var date_tweet = new Date(tweet.created_at);
var date_now = new Date();
var date_diff = date_now - date_tweet;
var hours = Math.round(date_diff/(1000*60*60));
// Build the html string for the current tweet
var tweet_html = '<div class="tweet_text">';
tweet_html += '<a href="http://www.twitter.com/';
tweet_html += twitter_user + '/status/' + tweet.id + '">';
tweet_html += tweet.text + '<\/a><\/div>';
tweet_html += '<div class="tweet_hours">' + hours;
tweet_html += ' hours ago<\/div>';
// Append html string to tweet_container div
$('#tweet_container').append(tweet_html);
}
});
}
);
});
DEMONSTRATION
You should use jsonp to get the result, because jsonp provides a method to request data from a server in a different domain
Check this FIDDLE
I use $.ajax function with dataType: jsonp here
Check this and this for JSONP