Dynamically add elements with ajax and json breaks the page layout - javascript

I have a page structured with jquery mobile. If i populate a list with a static code:
<script>
document.write('<ul data-role="listview">');
document.write('<li data-icon="false"><img src="images/app/prod.jpg"><h2>Sisa</h2><p class="wrap">mortadella affettatagr.120</p><span class="ui-li-count">2,70 €</span></li>');
document.write('<li data-icon="false"><img src="images/app/prod.jpg"><h2>Sisa</h2><p class="wrap">mortadella affettatagr.120</p><span class="ui-li-count">2,70 €</span></li>');
document.write('</ul>');
</script>
i get this result: image
Now, i try to do it dinamically, reading from a database with ajax and json.
This is the code:
<script>
document.write('<ul data-role="listview">');
$.ajax({
url: 'db_to_app_prod.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
document.write('<li data-icon="false"><img src="images/app/prod.jpg"><h2>Sisa</h2><p class="wrap">mortadella affettatagr.120</p><span class="ui-li-count">2,70 €</span></li>');
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
document.write('</ul>');
</script>
And this is the result: image
As you can see, the layout is totally broken now. What happens? Why? How do i fix this to obtain dinamically the first result?
EDIT:
This is another try i did:
$(document).ready(function(){
$(document).bind('deviceready', function(){
//Phonegap ready
onDeviceReady();
});
//var output = document.getElementById("output");
var _ul = document.createElement('ul');
_ul.setAttribute("data-role", "listview");
$.ajax({
url: 'db_to_app_prod.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var _li = document.createElement('li');
_li.setAttribute("data-icon", "false");
_li.innerHTML = '<li data-icon="false">'+
'<a href="" id="'+item.id+'">'+
'<img src="http://gestisciapp.it/gruppodipalo/images/'+item.img+'">'+
'<h2>'+item.marca+'</h2>'+
'<p class="wrap">'+item.descrizione+'</p>'+
'<span class="ui-li-count">'+item.prezzo+' €</span>'+
'</a></li>';
_ul.appendChild(_li);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
document.getElementById("output").appendChild(_ul);
});

Something like this:
.....
success: function(data, status){
var _ul = $('<ul />').attr('data-role','listview');
$.each(data, function(i,item){
$('<li data-icon="false" />')
.append($('<a href="" id="'+item.id+'" />')
.append('<img src="http://gestisciapp.it/gruppodipalo/images/'+item.img+'" />')
.append('<h2>'+item.marca+'</h2>')
.append('<p class="wrap">'+item.descrizione+'</p>')
.append('<span class="ui-li-count">'+item.prezzo+' €</span>')
)//$('<a />')
//)//$('<li />') no need sorry
.appendTo(_ul);
});
$('#output').empty().append(_ul);
},
....
Also dataType:'json' not jsonp. see http://api.jquery.com/jquery.ajax/ specification
Update
Full working code. Works with your sample json.
$.ajax('tony.js?id=' + Math.random(), //fake json which match your structure
{
dataType: "json",
jsonp: "jsoncallback",
method: 'get',
contentType: 'application/json',
success: function (data, status) {
var _ul = $('<ul />').attr('data-role', 'listview');
$.each(data, function (i, item) {
$('<li data-icon="false" />')
.append($('<a href="" id="' + item.id + '" />')
.append('<img src="http://gestisciapp.it/gruppodipalo/images/' + item.img + '" />')
.append('<h2>' + item.marca + '</h2>')
.append('<p class="wrap">' + item.descrizione + '</p>')
.append('<span class="ui-li-count">' + item.prezzo + ' €</span>')
)//$('<a />')
.appendTo(_ul);
});
$('#output').empty().append(_ul);
},
error: function (xhr, d, s) {
$('#output').empty().html(s);
}
});
Full Working Example
Tested in Google mobile emulator tool.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<script type="text/javascript">
function getData() {
$.ajax('tony.js?id=' + Math.random(), //fake json which match your structure
{
dataType: "json",
jsonp: "jsoncallback",
method: 'get',
contentType: 'application/json',
success: function (data, status) {
var _ul = $('<ul />').attr('data-role', 'listview');
$.each(data, function (i, item) {
$('<li data-icon="false" />')
.append($('<a href="" id="' + item.id + '" />')
.append('<img src="http://gestisciapp.it/gruppodipalo/images/' + item.img + '" />')
.append('<h2>' + item.marca + '</h2>')
.append('<p class="wrap">' + item.descrizione + '</p>')
.append('<span class="ui-li-count">' + item.prezzo + ' €</span>')
)//$('<a />')
.appendTo(_ul);
});
$('#output').empty().append(_ul).enhanceWithin();//.listview();
},
error: function (xhr, d, s) {
$('#output').empty().html(s);
}
});
}
</script>
</head>
<body>
<button onclick="getData()">Get Data</button>
<div id="output"></div>
</body>
</html>

Related

Consume REST Service with Javascript/HTML

Below is code I use to get data from a SharePoint List with Javascript. What would I need to do to get it work on a site like JS Bin or JS Fiddle with an open/free REST service? (Like iextrading.com?)
<script type="text/javascript">
function getCompanies () {
var call = $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Bills')/items?$select=AccountNumber&$orderby=AccountNumber&$filter=(PackageID eq '" + pid + "')",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.success(function (data,textStatus, jqXHR){
$("#ResultsDiv").empty();
for (var i = 0; i < data.d.results.length; i++)
{
var item = data.d.results[i];
$("#ResultsDiv").append(item.AccountNumber + "<br/>");
}
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving Account Numbers: " + jqXHR.responseText);
});
}
</script>
<button onclick="getCompanies(); return false;" type="button">Get Item</button>
<hr width="50px" />
<div id="ResultsDiv"></div>
I looked at several examples on SO, but I couldn't get them to work on JS Bin or JS Fiddle.
I guess I worded my question poorly, because my original code was close to the answer.
function getMovies () {
var call = $.ajax({
url: "https://www.omdbapi.com/?i=tt3896198&apikey=[yourKeyHere]",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.success(function (data,textStatus, jqXHR){
$("#ResultsDiv").empty();
$("#ResultsDiv").append(data.Title);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}

jQuery AJAX to get Vimeo thumbnail

Can anyone see what i am doing wrong here? the youtube one is working but its not adding the image from thevideoThumbV function and cant work out why...
fiddle: https://jsfiddle.net/yurt5bb6/3/
function:
function videoThumbV(id) {
$.ajax({
type:'GET',
url: '//vimeo.com/api/v2/video/' + id + '.json',
jsonp: 'callback',
dataType: 'jsonp',
success: function(data){
var thumbnail_src = data[0].thumbnail_large;
return '<img class="vimeo-thumb" src="' + thumbnail_src + '"><div class="play-button"></div>';
}
});
}
You can't return stuff from synchronous call, you need to use a callback:
function videoThumbV(id, callback) {
$.ajax({
type:'GET',
url: '//vimeo.com/api/v2/video/' + id + '.json',
jsonp: 'callback',
dataType: 'jsonp',
success: function(data){
var thumbnail_src = data[0].thumbnail_large;
callback('<img class="vimeo-thumb" src="' + thumbnail_src + '"><div class="play-button"></div>');
}
});
}
videoThumbV(id, function(str) {
player.html(str);
});
JSFIDDLE

JSON to HTML not rendering into HTML via ID

I am using PHPstorm IDE and i'm trying to render the following JSON and it gets stuck showing only the <ul></ul> without spitting the <li>'s into HTML the each function. Any idea what could be the issue?
thanks.
Script.js:
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
var items = [];
$.each(data, function (key, val) {
items.push('<li id=" ' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
And the JSON:
{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}
My HTML is just an a href that spits out the click ID:
Get JSON
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
<button>Get JSON data</button>
By Using this Method You can Easily get Your JSON value In HTML
Try this one :)
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data){
var html = "<ul>";
items = data.map(function(obj){
html += "<li id='" + obj.id + "'>" + obj.mesi + "</li";
});
html += "</ul>";
$('body').append(html);
I would try with some like this
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
// uncomment line below if data is a single JSON
// data = [data]
var items = [];
// we create a list where we will append the items
var list = document.createElement("ul");
data.forEach(function(item){
// we create a list item
var listItem = document.createElement("li");
// we set the attributes
listItem.setAttribute("id", item.id ); // item.id or the property that you need
// we add text to the item
listItem.textContent = item.mesi;
// We append the list item to the list
list.appendChild(listItem);
});
// we append the list to the body
$("body").html(list);
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
Try like this:
success: function(data){
var items = '';
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
for multiple objects
success: function(datas){
var items = '';
$.each(datas, function (i,data) {
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
output
<ul>
<li id=" id">1</li>
<li id=" mesi">mesima 0</li>
<li id=" done_bool">1</li>
<li id=" id">2</li>
<li id=" mesi">mesima 1</li>
.
.
</ul>
Try like this:
$(function() {
$('#clickme').click(function() {
// fetch json file
$.ajax({
url : 'data.json',
dataType : 'json',
// please confirm request type is GET/POST
type : 'GET',
success : function(data) {
// please check logs in browser console
console.log(data);
var ulHtml = "<ul>";
$.each(data, function(key, obj) {
ulHtml += '<li id="' + obj.id + '">' + obj.mesi + '</li>';
});
ulHtml += "</ul>";
// please check logs in browser console
console.log(ulHtml);
$('body').append(ulHtml);
},
error : function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
alert(textStatus);
}
});
});
});
<button id="clickme">Get JSON data</button>
I log json data and created ul html, Please check logs in browser console
I'm not sure how you want to output each item, so I made a simple suggestion, you can easily change the HTML to what you need. Here is working code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
Get JSON
<script>
$(function() {
$('#clickme').click(function() {
//fetch json file
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, val) {
// the HTML output for each item
var done = (val.done_bool === '1') ? 'true' : 'false';
items.push('<li id=" ' + val.id + '">' + val.mesi + ': ' + done + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function() {
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
</script>
</body>
</html>
data.json
[{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}]
I also created a __jsfiddle__ so you can test it directly. (The AJAX call is simulated with the Mockjax library): https://jsfiddle.net/dh60nn5g/
Good to know:
If you are trying to load the JSON from another domain, you may need to configure CORS (Cross-origin resource sharing):
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Isn't this supposed to be a GET request? i think you are missing the method on your Ajax request. You should add
method: 'GET'
to your ajax request. I think this is a big deal in making ajax request.

How can i load data from ajax to Chosen jquery?

I have use chosen at http://harvesthq.github.io/chosen/ . Ok, i testing it load data from ajax . I founding anywhere, maybe no someone success with them.
<script src="theme/js/jQuery-2.1.3.min.js"></script>
<link href="theme/chosen_v1.4.2/chosen.css" rel="stylesheet" />
<script src="theme/chosen_v1.4.2/chosen.jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$(".cb_bu_info").chosen({
width: "95%",
source: function (data) {
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LIST_BU",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#cb_info").html('');
//$.each($.parseJSON(data.d), function (idx, obj) {
$.each(data, function (idx, obj) {
$("#cb_info").append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
//$("#cb_info").trigger("liszt:updated");
},
error: function (data) {
console.log(data.d);
}
});
}
});
$("#cb_info").trigger("liszt:updated");
});
</script>
<select id="cb_info" class="cb_bu_info"></select>
The data form ajax as
[{"BU_ID":"B01","BU_NAME":"Agro Feed","BU_DES":"Agro Feed","EDIT_DATE":"2015-05-05T00:00:00","EDIT_BY":"","FLAG":false},{"BU_ID":"B02","BU_NAME":"Agro Farm","BU_DES":"Agro Farm","EDIT_DATE":"2015-05-05T00:00:00","EDIT_BY":"","FLAG":false}]
Well , it's look ok , but when i run it , result not show in select option, see browser dev tool , I've not seen error. Anything is ok.What's the problem happen in here? Notes: only use Chosen Jquery
After checking out the Chosen docs, there seems to not be a "source" option. What you need to do is first run your Ajax call, then fill your select options. Once the select is all filled, then run Chosen on that select element.
I would use the following JS code:
var url = "../BUS/WebService.asmx/LIST_BU";
$.getJSON(url, function(json){
var $select_elem = $("#cb_info");
$select_elem.empty();
$.each(json, function (idx, obj) {
$select_elem.append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
$select_elem.chosen({ width: "95%" });
})
Ok, After some time with the help of suggestions from everybody, I have done
function load_cb_info() {
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LIST_BU",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#cb_info").html('');
$.each($.parseJSON(data.d), function (idx, obj) {
//$.each(data, function (idx, obj) {
$("#cb_info").append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
$("#cb_info").trigger("liszt:updated");
$("#cb_info").chosen({ width: "95%" });
},
error: function (data) {
console.log(data.d);
}
});
}
And , I think this is an answer and everyone else can find it .Thank you.
I have changed your jsfiddle. Try this out http://jsfiddle.net/GaganJaura/by4d528c/2/
I have moved the chosen() to bottom.
$("#cb_info").empty();
$.each(data, function (idx, obj) {
$("#cb_info").append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
$("#cb_info").trigger("liszt:updated");
$("#cb_info").chosen();
You can try as follows it works for me
$.ajax({
type: "POST",
url: url,
data: formData,
processData: false,
contentType: false,
success:function(data){
if($.trim(data) != "no"){
$("#PROGRAM_ID").html(data);
$("#PROGRAM_ID").trigger("chosen:updated");
}
}
});
try this. it works for me. please pay attention to the bold text
Ext.Ajax.request({
url:'<?php echo base_url()."index.php/";?>ttemuan31a/cari_divisi',
method:'post',
params:{
divisi:vdivisi
},
success:function(data)
{
$("#divisi").chosen();
//document.getElementById('detail_divisi').innerHTML=response.responseText;
$('#divisi').empty();
$.each(JSON.parse(**data.responseText**), function(i, item) {
$('#divisi').append('<option value="'+item.id+'">'+item.namadivisi+'</option>');
$("#divisi").trigger("chosen:updated");
});
}
});
}

How do I write the AJAX to post data

Fiddle
I am trying to learn AJAX from a tutorial.
I am able to grab the data I want and populate it in the DOM pretty easily.
What I'm struggling with is using 'POST' to edit it.
I created a simple page that lists 'friends' and 'ages' that pulls that data from here
http://rest.learncode.academy/api/learncode/friends
The names and ages populate correctly, but the code I'm writing to 'POST' to it is not.
Here is my javascript
<script>
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/learncode/friends',
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
});
});
</script>
HTML
<div class="large-12 columns" id="ajaxContainer">
<h1>
AJAX Container
</h1>
<h3>
Friends
</h3>
<ul id="friends">
</ul>
<h3>Add a friend</h3>
<p>
Name:
<input type="text" id="name" />
</p>
<p>
Age:
<input type="text" id="age" />
</p>
<button id="add-order"> submit</button>
</div>
I am guessing as to what you actually want, but it seems that you want the page to populate with whatever friends are currently in the database on first load, and then when you click add-order button, it adds new friends and updates your list. The first thing is that you are trying to POST to the learncode name, which you can't do. Change where it says "yourname" in the URLs below to something else. Here is what you should do:
<script>
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
$.ajax({
type: 'POST',
data: {"id":3, "age": $age.val(), "name":$name.val()},
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function () {
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function (data) {
$friends.html("");
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +'
</li>');
})
},
error: function () {
alert("error loading data");
}
});
},
error: function () {
alert("error loading data");
}
});
});
});
</script>
See the part that says
type : "GET"
-?-
change it to
type : "POST"
Then, the url parameter is what you are POSTing to-
And you are not actually sending any data -!
So, try this:
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'POST',
url: 'http://yourWebsite.com/someScriptToHandleThePost.php',
data: [{"id":1,"name":"Will","age":33},{"id":2,"name":"Laura","age":27}],
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
});
});
Then, you're going to need a PHP script to handle the POSTed data and return a response, which gets passed in the data param in success:function(data){}
start out with something simple, like this:
<?php
print_r($_POST);
?>
and change your success function to:
success: function(data) {
$("body").append("<pre>"+data+"</pre>");
}
and that should get you on the right track....

Categories

Resources