How to load javascript values in html page - javascript

This is my script code where i will get a array list, then i have iterated and got each one in a variable. Now my requirement is to show this values in my html page which i have designed. I have to load the retried values in my page. The imageurl should be given inside the img src to show that image. Plus this should be dynamically incremented.
<script>
function getValueFromServer(e) {
//make the AJAX request to server
$.ajax({
type: "GET",
url: "http://example./../getAllBrandList",
dataType: "json",
//if received a response from the server
success: function( data) {
console.log(data);
var brands=data;
var i = 0
//our country code was correct so we have some information to display
for ( var i = 0; i < brands.allBrands.length; i++) {
var obj = brands.allBrands[i];
console.log(obj);
var fundedType= "LIVE";
var url=obj.url;
var imageUrl=obj.image_url;
var brandName=obj.brandName;
var description=obj.description;
var totalGoal=obj.total_goal;
var totalRaised=obj.total_raised;
var profitMargin=obj.profit_margin;
}
},
//If there was no resonse from the server
error: function(jqXHR, textStatus, errorThrown){
console.log("Something really bad happened " + textStatus);
$("#ajaxResponse").html(jqXHR.responseText);
},
//capture the request before it was sent to server
beforeSend: function(jqXHR, settings){
//adding some Dummy data to the request
settings.data += "&dummyData=whatever";
//disable the button until we get the response
$('#myButton').attr("disabled", true);
},
//this is called after the response or error functions are finsihed
//so that we can take some action
complete: function(jqXHR, textStatus){
//enable the button
$('#myButton').attr("disabled", false);
}
});
};
window.onload = getValueFromServer();
</script>
<div class="small-12 columns" onload="getValueFromServer()">
<ul class="small-block-grid-1 medium-block-grid-2 large-block-grid-3" id="brands">
<!-- <li class="item" >
<a href="" class="badge-live" data-badge="LIVE" ></a>
<a href=""><div class="offer">
<span class="link-overlay"></span>
<img src="" id="imageurl">
<div class="offer-info">
<h6 id="brandname"></h6>
<p class="offer-short" id="description"></p>
<p class="funded">
<span class="goal">
<strong id="totalgoal">$</strong> raised 1 day ago in 13 minutes
</span>
</p>
<div class="nice round progress"><span class="meter-reserved" style="width: 100%;"></span><span class="meter" style="width: 100%;"></span></div>
<div class="row offer-stats">
<div class="small-12 columns text-center">
<p>
<span id="profitmargin">%</span> Co-Op Profit Margin
</p>
</div>
</div>
<hr style="margin:0.5rem 0 1rem;">
<div class="row text-center offer-stats">
<div class="small-6 columns">
<p>
<span>96</span>following
</p>
</div>
<div class="small-6 columns" style="border-left: 1px solid #dbdbdb;">
<p>
<span>4</span>Months
</p>
</div>
</div></a>
<div class="text-center">
GET STARTED
</div>
</div>
</div>
</li> -->
</ul>
</div>

not tested but should work using innerHTML to write list to brands ul
function getValueFromServer(e) {
//make the AJAX request to server
$.ajax({
type: "GET",
url: "http://example./../getAllBrandList",
dataType: "json",
//if received a response from the server
success: function( data) {
console.log(data);
var brands=data;
var i = 0
//our country code was correct so we have some information to display
for ( var i = 0; i < brands.allBrands.length; i++) {
var obj = brands.allBrands[i];
console.log(obj);
var fundedType= "LIVE";
var url=obj.url;
var imageUrl=obj.image_url;
var brandName=obj.brandName;
var description=obj.description;
var totalGoal=obj.total_goal;
var totalRaised=obj.total_raised;
var profitMargin=obj.profit_margin;
document.getElementById("brands").innerHTML += '<li class="item" >\
<a href="" class="badge-live" data-badge="LIVE" ></a>\
<a href=""><div class="offer">\
<span class="link-overlay"></span>\
<img src="'+imageUrl+'" id="imageurl">\
<div class="offer-info">\
<h6 id="brandname">'+brandName+'</h6>\
<p class="offer-short" id="description">'+description+'</p>\
<p class="funded">\
<span class="goal">\
<strong id="totalgoal">$'+totalGoal+'</strong> raised 1 day ago in 13 minutes\
</span>\
</p>\
<div class="nice round progress"><span class="meter-reserved" style="width: 100%;"></span><span class="meter" style="width: 100%;"></span></div>\
<div class="row offer-stats">\
<div class="small-12 columns text-center">\
<p>\
<span id="profitmargin">%'+profitMargin+'</span> Co-Op Profit Margin\
</p>\
</div>\
</div>\
<hr style="margin:0.5rem 0 1rem;">\
<div class="row text-center offer-stats">\
<div class="small-6 columns">\
<p>\
<span>96</span>following\
</p>\
</div>\
<div class="small-6 columns" style="border-left: 1px solid #dbdbdb;">\
<p>\
<span>4</span>Months\
</p>\
</div>\
</div></a>\
<div class="text-center">\
GET\ STARTED\
</div>\
</div>\
</div>\
</li>';
}
},
//If there was no resonse from the server
error: function(jqXHR, textStatus, errorThrown){
console.log("Something really bad happened " + textStatus);
$("#ajaxResponse").html(jqXHR.responseText);
},
//capture the request before it was sent to server
beforeSend: function(jqXHR, settings){
//adding some Dummy data to the request
settings.data += "&dummyData=whatever";
//disable the button until we get the response
$('#myButton').attr("disabled", true);
},
//this is called after the response or error functions are finsihed
//so that we can take some action
complete: function(jqXHR, textStatus){
//enable the button
$('#myButton').attr("disabled", false);
}
});
};
window.onload = getValueFromServer();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="small-12 columns" onload="getValueFromServer()">
<ul class="small-block-grid-1 medium-block-grid-2 large-block-grid-3" id="brands">
</ul>
</div>

Related

Ajax status update in one page with one button

I am trying to update the status for my orders on the same page where it's displayed with an ajax HTML.
Displaying works just fine, but I want to set the status the the next one with only one click so I figured to use ajax for it too.
My ajax PUT for the next status
$(function () {
$(document).on('click', 'button#order_update', function (e) {
e.preventDefault();
let newStatus = '';
if ($(this).data('status') == 'pending') {
newStatus = 'confirm';
} else if ($(this).data('status') == 'confirm') {
newStatus = 'processing';
} else if ($(this).data('status') == 'processing') {
newStatus = 'picked';
}
let formStatusData = new FormData();
formStatusData.append('order_id', $(this).data('order'));
$.ajax({
type: 'PUT',
url: '{{ route("update-order-status") }}',
data: formStatusData,
success: (response) => {
console.log(response);
$(this).data('status', newStatus);
$(this).text(newStatus.charAt(0).toUpperCase() + ' order');
}
});
});
});
My ajax for the html
$.ajax({
type: 'GET',
url: '/order/view/all',
dataType: 'json',
cache: false,
success:function(response){
$('#pimage').attr('url','/'+response.product.product_thambnail);
var product_name = $('#pname').text();
var id = $('#product_id').val();
var quantity = $('#qty').val();
var OrderView = ""
$.each(response.orders, function (key,value){
var productsList = '';
$.each(value.product, function (key,value) {
productsList += `
<div class="row gx-4">
<div class="col-lg-3">
<div class="pos-task-product">
<div class="pos-task-product-img">
<div class="cover" style="background-image: url(${value.product_thambnail});"></div>
</div>
<div class="pos-task-product-info">
<div class="flex-1">
<div class="d-flex mb-2">
<div class="h5 mb-0 flex-1">${value.product_name_en}</div>
<div class="h5 mb-0">${value.pivot.qty} DB</div>
</div>
</div>
</div>
<div class="pos-task-product-action">
Complete
Cancel
</div>
</div>
</div>
</div>
`;
});
OrderView += `<div class="pos-task">
<div class="pos-task-info">
<div class="h3 mb-1" id=""><td>Üzenet: ${value.notes}</td></div>
<div><div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div></div>
<br>
<!-- You can safely remove this if not needed
<div class="mb-3">${value.product_id}</div>
<div class="h4 mb-8">${value.product_name}</div>
-->
<td> </td>
<div class="mb-2">
<span class="badge bg-success text-black fs-14px">${value.status}</span>
</div>
<div><span class="text">${value.created_at}</span> Beérkezett</div>
</div>
<div class="pos-task-body">
<div class="fs-16px mb-3">
Completed: (1/4)
</div>
${productsList}
</div>
</div>`
});
$('#OrderView').html(OrderView);
}
})
}
OrderView();```
**Im currently trying to use this button inside the HTML ajax**<div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div>
I tried using processData: false, but it just kills the process and the button is unusable. Please help.
Your problem is that you have many identifiers # with the same name.
id must be unique.
Replace in code
$(document).on('click', 'button#order_update'
to
$(document).on('click', 'button.order_update'
and
<button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button>
to
<button type="button" class="btn btn-outline-theme rounded-0 w-150px order_update" data-status="${value.status}" data-order="${value.status}">Confirm Order</button>
You still have the problem that you didn't close the class quote after w-150px, I closed it in the formatted code

JavaScript ajax didn't working.Where am I going wrong?

<div class="media-bottom">
#Html.TextAreaFor(model => model.Message, new { #class = "ui form", #rows = "5", #maxlenght = "300", #placeholder = "Paylaşmak istedikleriniz" })
</div>
<br />
<div class="footer-logo">
<button class=" mini ui right labeled right floated icon button" id="Button_Click" onclick="javascript: Button_Click();">
<i class="right arrow icon"></i>
Paylas
</button>
<div class="container bootstrap snippets bootdey downlines">
<div class="row">
<div class="col-md-6 col-xs-12">
<section class="widget">
<div class="widget-body">
<div class="widget-top-overflow windget-padding-md clearfix bg-info text-white">
</div>
<div class="post-user mt-n-lg">
<span class="thumb-lg pull-left mr media-object">
<img class=" img-circle" src="https://bootdey.com/img/Content/user_3.jpg" alt="...">
</span>
<span class="thumb-lg pull-right mr star">
<img src="~/Content/img/star.png" />
</span>
<div class="Thanksicon">
</div>
<div class="namespace">
<h5 class="mt-sm fw-normal text-black txt post">
#Html.DisplayFor(model => model.FullName)
<br />
<small class="text-black text-light departmen post">#Html.DisplayFor(model => model.Departmen)</small>
</h5>
</div>
</div>
<br />
<br />
<div class="text-light fs-mini m" id="Label1">
<div id="label1">
<p class="article">
#Html.DisplayTextFor(model=>model.Message)
</p>
</div>
<div class="thanksnames">
<span class="thumb-xs avatar mr-sm">
<img class="img-circle thank" src="https://bootdey.com/img/Content/user_2.jpg" alt="...">
</span>
<div class="mt-sm fw-normal text-black " id="person"> <small class="text-black text-light">Rose Tyler</small></div>
</div>
<br />
<div class="img"></div>
<div class="fs-mini text-muted text-right"><time class="time-table-top"></time></div>
</div>
</div>
</section>
</div>
</div>
</div>
This is my javascript
$(function () {
$('#Button_Click').on('click', function () {
$.ajax({
type: "POST",
url: '#Url.Action("Share")',
data: {
fullname: $("#username").val(),
departmen: $("#departmen").val(),
textarea: $(".ui.form").val()
},
datatype: "json",
success: function (data) {
$('.downlines').html(result);
}, error: function (data) {
}
});
});
});
This is my controller httppost
[HttpPost]
private JsonResult Share(SocialMedia data,string id)
{
var employee = _employeeRepository.GetById(id);
ViewBag.IsOwner = id == Session.GetEmployeeNo();
if (Session["MediaList"] == null)
{
Session["MediaList"] = new List<SocialMedia>();
}
var fullname = data.FullName;
var departmen = data.Departmen;
var textarea = data.Message;
foreach (MediaList list in data.MediaLists)
{
list.FullName = fullname;
list.Departmen = departmen;
list.Message = textarea;
list.Date = DateTime.Now.ToLocalTime();
if(data.Photo!=null)
{
list.Photo = data.Photo;
string fileName = Path.GetFileNameWithoutExtension(list.Photo);
list.Photo = "~/Image/" + fileName;
string _path = Path.Combine(Server.MapPath("~/Image/"),fileName);
}
}
return Json(new { data = PartialView("~/Views/SocialMedia/DisplayTemplates/MediaList.cshtml") });
// return PartialView("~/Views/SocialMedia/DisplayTemplates/MediaList.cshtml",
//return Json(new { success = true, message = GlobalViewRes.CreatedSuccessfully }, JsonRequestBehavior.AllowGet);
}
When I write an article and press the button, I want the page to appear below without refreshing and I want it to be repeated. It should be with the whole design. But when I press the button, I made ajax, but my ajax does not work, where am I going wrong?
Sorry for my English:)
success: function (data) {
$('.downlines').html(result);
}, error: function (data) {
}
You handle the data named 'data'. Then you are trying use it like 'result'. What is result, where is it came from? Whatever, try this
$('.downlines').html(data)

Read URL From Javascript variable into HTML

I have a card in my web page that reads in Automation Data and displays it in the card my the page. I am about to read in all the needed data except for the URL to the automation test summary.
Here is my code:
function Cox() {
jQuery.ajax({
method: "POST",
dataType: "JSON",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function(data) {
console.log(data);
var total = data[0];
var passed = data[1];
var failed = data[2];
var time = data[3];
var url = data[4];
document.getElementById('coxTotal').innerHTML = "Total tests: " + total;
document.getElementById('coxFailed').innerHTML = "Failed tests: " + failed;
document.getElementById('coxPassed').innerHTML = "Passed tests: " + passed;
document.getElementById('coxRunTime').innerHTML = "Run Time: " + time;
document.getElementById('coxUrl').innerHTML = "url " + url;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card text-white bg-primary o-hidden h-100">
<a class="card-header text-white clearfix small z-1" href="#">
<span class="float-left">COX Sanity Run </span>
</a>
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-fw fa-tasks"></i>
</div>
<div id="coxTotal" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
<div id="coxFailed" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
<div id="coxPassed" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
<div id="coxRunTime" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left">View Details</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
</div>
When I try to load the URL into the HMTL like I did for the other 4 variables it does not seem to work correctly. Any ideas?
UPDATE:
Thank you for the helpful comments on how to clean up my code. I have aded it in and it has made it a lot cleaner. I have also found the following post that has provided a solution to my issue. Thanks
document.getElementById to include href
You will get the error message as "Uncaught ReferenceError: Cox is not defined" because you are calling 'Cox()' function before define it. DOM will process line by line and during that time, the function does not exist.
I changed your code and mentioned below. it will work as you expected. :)
I called 'Cox()' function after definition. You can change the place where ever you want but after definition.
<html>
<body>
<div class="card text-white bg-primary o-hidden h-100">
<a class="card-header text-white clearfix small z-1" href="#">
<span class="float-left">COX Sanity Run </span>
</a>
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-fw fa-tasks"></i>
</div>
<div id="coxTotal" class="mr-5"></div>
<div id="coxFailed" class="mr-5"></div>
<div id="coxPassed" class="mr-5"></div>
<div id="coxRunTime" class="mr-5"></div>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left">View Details</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function Cox()
{
jQuery.ajax({
method: "POST",
dataType: "JSON",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function (data) {
console.log(data);
var total = data[0];
var passed = data[1];
var failed = data[2];
var time = data[3];
var url = data[4];
document.getElementById('coxTotal').innerHTML = "Total tests: " + total;
document.getElementById('coxFailed').innerHTML = "Failed tests: " + failed;
document.getElementById('coxPassed').innerHTML = "Passed tests: " + passed;
document.getElementById('coxRunTime').innerHTML = "Run Time: " + time;
document.getElementById('coxUrl').innerHTML = "url " + url;
}
});
}
Cox();
</script>
</body>
</html>
You should only call Cox() once: when the page loads as it targets all the divs anyway. Also, Cox() is undefined because you call it before you define it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function Cox() {
jQuery.ajax({
method: "POST",
dataType: "JSON",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function(data) {
console.log(data);
var total = data[0];
var passed = data[1];
var failed = data[2];
var time = data[3];
var url = data[4];
document.getElementById('coxTotal').innerHTML = "Total tests: " + total;
document.getElementById('coxFailed').innerHTML = "Failed tests: " + failed;
document.getElementById('coxPassed').innerHTML = "Passed tests: " + passed;
document.getElementById('coxRunTime').innerHTML = "Run Time: " + time;
document.getElementById('coxUrl').innerHTML = "url " + url;
}
});
}
window.onload = function(){
Cox();
}
</script>
<div class="card text-white bg-primary o-hidden h-100">
<a class="card-header text-white clearfix small z-1" href="#">
<span class="float-left">COX Sanity Run </span>
</a>
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-fw fa-tasks"></i>
</div>
<div id="coxTotal" class="mr-5">
</div>
<div id="coxFailed" class="mr-5">
</div>
<div id="coxPassed" class="mr-5">
</div>
<div id="coxRunTime" class="mr-5">
</div>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left">View Details</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
</div>

knockout carrying the data to Multiple View

Below is my code which is knocokout js,i have ListviewModel which is related to two views 1st and second view as below,Both views using the class name UserDetailsView, i am binding two views 1st and second view as below,my problem is, i have click event on the 1st view "Userview" i need to get data of clicked event which is $root.UserView, when i click this it should get all related value and pass to second view so i can bind the data using knockout js ,i am getting the value but unable to bind the data when i clicked $root.UserView so i used jquery in second view for binding, but Now requirement is changed i need make another click event in second view so i can carry data to another view,before that i need to bind the second view with Knockout js how it can be done need help
function ListviewModel()
{
var self = this;
self.Listarray = ko.observableArray();
self.getUserList = function () {
var ListModel = {
userId: UserID
}
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(ListModel),
url: serverUrl + 'xxx/xxx/xxx',
success: function (data) {
self.Listarray($.map(data, function (item) {
return new Listdata(item);
}));
}
});
};
//Click Function for UserPersonalview
self.UserView = function (Listarray) {
$("#userId").text(Listarray.userIdId());
$("#userName").text(Listarray.UserName())
document.getElementById('userProfilePic').setAttribute('src', "data:" + Listarray.ProfilePictype() + ";base64," + Listarray.ProfilePicBase64());
window.location.href = "#UserPersonalview";
}
self.UserProfile = function () {
console.log(self.Listarray());
}
}
//Model
function Listdata(data)
{
var self = this;
self.userId = ko.observable(data.userId);
self.userName = ko.observable(data.userName);
self.userProfilePicBase64 = ko.observable(data.userProfilePicBase64);
self.userProfilePictype = ko.observable(data.userProfilePictype);
self.userProfilepic = ko.computed(function () {
return "data:" + self.userProfilePictype() + ";base64," + self.userProfilePicBase64();
});
}
//1st View
<div data-role="view" id="Userview" class="UserDetailsView" data-layout="default">
<div data-role="content" style="background-color:#fff!important">
<div>
<ul style="list-style: none;" data-role="listview" id="hierarchical-listview" data-bind="foreach:Listarray">
<li style="background-color:#FFF" data-bind="click:$root.UserView">
<div style="width:100%;">
<div style="width:50%;float:left">
<span data-bind="text:$data.userId" style="display:none"></span>
<img data-bind="attr: { src:$data.userProfilepic }" onclick="Imagepopover()" />
<label style="width: 25%!important;" class="firendslisttext" data-bind="text:$data.userName"></label>
</div>
<div style="width:50%;float:left;margin: 0px -20px;">
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
//second View
<div data-role="view" id="UserPersonalview" >
<header data-role="header">
<div data-role="navbar" class="UserDetailsView">
<div class="content-header ">
<ul style="list-style: none;" >
<li data-bind="click:$root.UserProfile">
<div class="km-leftitem">
</div>
<div class="block2" >
<div class="inner" style="float:left" >
<span id="userId" style="display:none"></span>
<img data-responsive="" width="40" height="40" id="userProfilePic" src="" style="border-radius: 50%;" />
</div>
<div class="inner" style="float:left;margin-left:15px">
<label id="userName" style="width: 100%!important;"></label>
</div>
</div>
<div class="km-rightitem">
<a data-align="right"><img src="images/icon-add.png" style="height:50px" /></a>
</div>
</li>
</ul>
</div>
</div>
</header>
<div data=role="content"><div>
</div>

How to templating json using jquery

Let's say my json like this and i have 3 different data
[
{
"Pair":"",
"Id":"8ca2df56-2523-4bc3-a648-61ec4debcaaf",
"PubDate":"/Date(1463775846000)/",
"Provider":null,
"Market":""
},
{
"Pair":"",
"Id":"74b2d7c7-bc2c-40ee-8245-7c698befa54d",
"PubDate":"/Date(1463775247000)/",
"Provider":null,
"Market":""
},
{
"Pair":"",
"Id":"0ee3cd96-1df8-49ba-b175-7a75d0840973",
"PubDate":"/Date(1463773687000)/",
"Provider":null,
"Market":""
}
]
What I already try
JQUERY
$.ajax({
type: 'GET',
url: 'news.json',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
console.log(data);
$.each(data, function(index, element) {
$( ".content-news h3" ).append( data[0].Title );
**/** Stuck Here and it only call 1 data but i already use each function **/**
});
}
});
HTML
<div class="news">
<div class="ano">
<div class="content-news">
<h3 id="jtitle"> **/** I Want to Show Id Here **/** </h3>
<h4 id="jprovider" class="author">**/** I Want To Show PubDate **/**</h4>
<p id="jsummary">
**/** I Want to Show Provider Here **/**
</p>
<div class="img-head" id="img-container">
<!-- <img src="" alt="img" class="img-responsive">-->
</div>
</div>
<div class="social-control">
<div class="head-control">
<p id="jdate" class="inline gray"></p>
<p class="pull-right">show more</p>
</div>
<div class="clear"></div>
<div class="footer-control">
<p><i class="ion-ios-heart ion-spacing"></i>20</p>
<p><i class="ion-chatbox ion-spacing"></i>2 comments</p>
<p><i class="ion-android-share-alt ion-spacing"></i>share</p>
</div>
</div>
</div>
</div>
JSFiddle
I managed to out only 1 result. Can you guys give a hint or tips show me how to templating jquery using json. Please be easy on me. Thanks
THIS IS THE RESULT WHAT I GET RIGHT NOW, Only 1 data display..
You can access the properties via the index on the data property as so:
$.ajax({
type: 'GET',
url: 'news.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function(data) {
//console.log(data);
$.each(data, function(index, element) {
console.log(
data[index].Id,
data[index].Pair,
data[index].PubDate,
data[index].Provider,
data[index].Market
);
});
}
});
Which produces
8ca2df56-2523-4bc3-a648-61ec4debcaaf /Date(1463775846000)/ null
74b2d7c7-bc2c-40ee-8245-7c698befa54d /Date(1463775247000)/ null
0ee3cd96-1df8-49ba-b175-7a75d0840973 /Date(1463773687000)/ null
To handle the templating you can create a function that returns the markup for each item:
function template(title, provider, summary) {
var $temp = $('<div/>');
$temp.append($('<h3/>', {
text: title
}));
$temp.append($('<h4/>', {
text: provider,
class: 'author'
}));
$temp.append($('<p/>', {
text: summary
}));
console.log($temp);
return $temp;
}
$.ajax({
type: 'GET',
url: 'https://cdn.rawgit.com/enki-code/4ec2b6efa84dfed8922b390d2a1a4c5a/raw/dc94405f12d1d5105e54584a6c53ca30d1863b4a/so.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function(data) {
//console.log(data);
$.each(data, function(index, element) {
$('.content-news').append(template(data[index].Id, data[index].PubDate, data[index].Provider));
console.log(
data[index].Id,
data[index].Pair,
data[index].PubDate,
data[index].Provider,
data[index].Market
);
});
}
});
Here is an updated version of your fiddle as an example.
You'll likely have to make a few small adjustments to the CSS and whatnot to get it looking how you like.
you json file have array of objects so first you need to loop for the objects one by one
also don't use each for serialized array cause it takes more time just use the normal for loop
answer is here jsfiddle.net/robert11094/65zjvy5k/3
or just use this html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://subscriptions.fxstreet.com/json/news.aspx?c=A0DC975D13C44CE697EC&i=englishnewscharts',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
console.log(data);
for (var i=0;i<data.length;i++){
var html=
'<div class="ano">'+
' <div class="content-news">'+
' <h3 id="jtitle"> '+data[i].Id+' </h3>'+
' <h4 id="jprovider" class="author">'+data[i].PubDate+'</h4>'+
' <p id="jsummary">'+
data[i].Provider+
' </p>'+
' <div class="img-head" id="img-container">'+
' <!-- <img src="" alt="img" class="img-responsive">-->'+
' </div>'+
' </div>'+
' <div class="social-control">'+
' <div class="head-control">'+
' <p id="jdate" class="inline gray"></p>'+
' <p class="pull-right">show more</p>'+
' </div>'+
' <div class="clear"></div>'+
' <div class="footer-control">'+
' <p><i class="ion-ios-heart ion-spacing"></i>20</p>'+
' <p><i class="ion-chatbox ion-spacing"></i>2 comments</p>'+
' <p><i class="ion-android-share-alt ion-spacing"></i>share</p>'+
' </div>'+
' </div>'+
'</div>';
$('.news').append(html);
}
}
});
});
</script>
<div class="news">
<div class="ano">
<div class="content-news">
<h3 id="jtitle">Hello World</h3>
<h4 id="jprovider" class="author">David</h4>
<p id="jsummary">
This is content
</p>
<div class="img-head" id="img-container">
<!-- <img src="" alt="img" class="img-responsive">-->
</div>
</div>
<div class="social-control">
<div class="head-control">
<p id="jdate" class="inline gray"></p>
<p class="pull-right">show more</p>
</div>
<div class="clear"></div>
<div class="footer-control">
<p><i class="ion-ios-heart ion-spacing"></i>20</p>
<p><i class="ion-chatbox ion-spacing"></i>2 comments</p>
<p><i class="ion-android-share-alt ion-spacing"></i>share</p>
</div>
</div>
</div>
</div>
Try to use $.parseJSON or $.getJSON. It will be easier to find problems.
Reference: jQuery API

Categories