ajaxing data and displaying - javascript

I am trying to display some xml data from remote URL using jquery and ajax. In my xml, there are simply two elements to be accessed: title and url.
The structure of my xml file is as follows:
<list>
<lists>
<songs>
<title>Pumped Up Kicks - Foster the people</title>
<url>http://dc249.4shared.com/img/970884399/8b9afc1d/dlink__2Fdownload_2Fmf4- 10b_5F_3Ftsid_3D20111122-112912-f675aa20/preview.mp3</url>
</songs>
</lists>
</list>
And I have the following jquery code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://jeewanaryal.web44.net/SongsXML/nepaliSongs.xml",
dataType: "xml",
success: function (xml) {
var items = parseXml(xml);
doStuff(items);
}
});
});
function parseXml(xml) {
var items = [];
$(xml).find("songs").each(function () {
items.push({
name: $(this).find("title").text(),
value: $(this).find("url").text()
});
});
for (var i = 0; i < items.length; i++) {
$(".phoneGapAPI").append(items[i].name + " <button class=\"newsDiv\" onclick=\"openChildBrowser(" + items[i].value + ");\">click here</button> <br> <br />");
}
}
I can guess that I am doing wrong at the statement openChildBrowser("+items[i].value+");
How can I implement this? I need to pass the variable items[i].value inside the function openChildBrowser().
This code works fine displaying items[i].name but click here link does not let me to open that URL.

Jquery failed to to render your Xml (Error : XML Parsing Error: no element found Location: moz-nullprincipal:{9e622e17-2e96-4a4d-95e4-6f7b95d0b4d8} Line Number 1, Column 1:) .Try to add version information to that xml file.
like
<?xml version="1.0" encoding="ISO-8859-1"?>

Related

Replace javascript variable without id or class

I have this javascript and once the AJAX process is executed I want to replace this variable to some other variable.
window.onload = function() {
oldvariable = [];
var chart = new Chart("Container2", {
data: [{
type: "column",
dataPoints: oldvariable
}]
});
}
When I process the AJAX request and fetch JSON data which is stored in oldvariable, it is not written so I have few options. I tried ads they are working in HTML but not under script tag.
If I can define oldvariable='<div class="second"></div>'; and replace this with processed JSON data then it is working and giving correct output in HTML but in javascript < tag is not allowed as variable so we cant define oldvariable like that.
$( "div.second" ).replaceWith( ''+newvariable +'' );
So is there anyway I can replace javascript variable as HTML tags are not allowed in variable and without tag javascript can't replace.
I have one more probable solution.regex. Search for oldvariable in entire HTML code and replace with newvariable but that process will be very slow so what is the best way to do this.
My vairables are globally defined and AJAX request is in external file and above codes are embeded in HTML.
========edit
how we can replace oldvariable with newvariable in above javascript
====== ajax code- variable name is different
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var oldvariable = '',
downlo;
for (var i = 0; i < data.length; i++) {
downlo = data[i];
oldvariable += '' + downlo.ndchart + '';
}
$('#chek').html(oldvariable );
}
})
})();
});
you need to update chart datapoints and re-render the chart after ajax success like this
ajax :
...
success:function(response)
{
chart.options.data[0].dataPoints=response;
//response is (array) of dataSeries
chart.render();
}
.......
update 1 : As per your code data should be updated like this
.....
success:function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
.....
update 2:
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
})
})();
});

Output JSON to HTML

I am able to pull some data if I input the json manually into the JS...however, I am trying to pull it from a seperate file ('mindshare.json') and populate only certain fields (title, content, featured image).
When I use the code below, I get 3 columns of "undefined".
My question is, how do I:
Reference the ID of the post that will contain the title, content, image?
Do I have to add any other code to json file to call the nested tags?
Im a JSON noob, so I appreciate your patience.
Here's my code:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
var json = "mindshare.json";
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].title + "</td>");
tr.append("<td>" + json[i].content + "</td>");
tr.append("<td>" + json[i].source + "</td>");
$('.mindshare').append(tr);
}
});
</script>
<div class="mindshare">
</div>
</body>
</html>
The JSON file can be found at http://toolboxwebdesign.com/mindshare.json.
$.ajax({
dataType: "json",
url: 'http://toolboxwebdesign.com/mindshare.json',
success: function(result){
var json = JSON.stringify(result);
json = JSON.parse(json);
}
});
Now you should have your JSON values in the json variable
*There are some cases in which the ajax call with the json datatype does not give a valid json and it should be parsed to a string and back again to object to work.
Here's how you load the data from your json file and turn it into an HTML table :
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData.title+'</td>'));
row.append($('<td>'+cellData.content+'</td>'));
row.append($('<td>'+cellData.source+'</td>'));
});
table.append(row);
});
return table;
}
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://toolboxwebdesign.com/mindshare.json",
dataType: 'json',
success: function (data) {
$('.mindshare').append(arrayToTable(data));
}
});
});
Notes
You can't run AJAX calls locally. If you're running it on your laptop or desktop computer, you need to have a web server running.
Your json file needs to be hosted at the same domain as your JS code.
Your json needs to be valid. According to JSONLint, it is not!

is there a way to set a var = to content of external file in javascript?

I have to pass some result string to the view after sucessful ajax post. At the moment my js is placed in the view and the callback function creates a resultstring and then posts it to the results div. Since I have some blade syntax in the string that is being generated by the callback function it works until I leave the js in the blade.php view file, if I put the javascript in public/js/some.js blade doesn't parse that syntax and the result is the view is rendered with the syntax instead of data. So I was thinking: Can I put the sting in a separate view/js/result.blade.php and in the jquery function do somtehing like:
var resultStr = (content of view/js/result.blade.php)
for(var i=0; i<obj.length; i++){
resultStr
};
$("#results").html(resultStr);
If so, how do I load the external file into partialstring?
My guess is that as it's a blade file it will be parsed.
#c-smile tried this code but is not working, the file is opened but then the view doesn't get the data
jQuery(function ($) {
$(document).ready(function () {
var form = $('form');
form.submit(function (e) {
e.preventDefault();
$.get("js/blade/filler.blade.php", function (data) {
var resultStr = data;
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: form.serialize(),
success: function (data) {
var obj = (data);
for (var i = 0; i < obj.length; i++) {
resultStr;
}
$("#results").html(resultStr);
}
});
});
});
});
});
That's subject of AJAX functionality.
With jQuery you would do it as:
$.get( "view/js/result.blade.php", function( data ) {
var resultStr = data;
...
});

How do I extract data from xml and post to a div using jquery/javascript

I am trying to get the title for a twitch.tv stream from an xml file using either jQuery or JavaScript and then post that title to a div (as a section header). The title is found in the <status> section of the xml file.
Below the code I currently have which doesn't seem to be working:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://www.twitch.tv/meta/koibu.xml",
dataType: "xml",
success: function(xml) {
var xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$(xml).find('meta status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
}
});
});
Here is a jsfiddle -with my broken script in- to play with.
Edit: solved it using a json call instead of reading xml
$(document).ready(function(){
var names = ["koibu"];
var obj = jQuery.parseJSON('{"name": {"life": "{life}","logo": "{logo}","status": "{status}","preview": "{preview}","url": "{url}"}}');
grabJSON();
function grabJSON() {
setTimeout(grabJSON,1000);
for (index = 0; index < names.length; ++index) {
$.getJSON("https://api.twitch.tv/kraken/channels/" + names[index] + "/?callback=?", function (json) {
$('#lefttitle').empty(),
$('#lefttitle').append("<h2>" + json.status + "</h2>");
});
}
}
});
This also allows me to set up a nice little array to grab more data from multiple channels if I want to extend it in future.
If you're not suffering from CORS, then the actual problem is below
$(xml).find('status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
xml variable represents the unparsed XML.
It has to like
$xml = $(xmlDoc);
$xml.find('status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
I managed to get your XML file, and the status tag contains Monday Mafia!

Javascript failing in external file only

Can anyone tell me why I get an error on the 2nd line saying 'unexpected string' but works fine when I have it directly on my view (i'm using MVC 3, not that it makes a difference):
function getUsers(processId) {
$.ajax({
url: "#Url.Action('GetProcessApprovers', 'Risk')",
data: { processId: processId },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
var items = "<option value=\"\">-- Please select --</option>"
if (data != "") {
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
}
$("#ProcessOwnerId").html(items);
}
});
};
Because your url: "#Url.Action('GetProcessApprovers', 'Risk')", only executes in the context of the view, not in an external JS file. It's razor code.
You need to pass the url to the Javascript in some other way, perhaps as a parameter of your function.
getUsers(processId, ajaxUrl)
Another way would be to write out the url from the HtmlHelper into a data attribute in your view and then pick it up in your Javascript.
HTML
<div id="someContainer" data-url="#Url.Action('GetProcessApprovers', 'Risk')">...
JS
var url = $("#someContainer").attr("data-url");
Your url parametre is has the issue.
please change it like this:
url: '#Url.Action("GetProcessApprovers", "Risk")',
Hope it works

Categories

Resources