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
Related
Now I have a seperate script which uses jquery which calls data from an api
function sendRequest() {
$.ajax({
url: "http://localhost:3002/api/people",
type: "get", //send it through get method
data: {
filters
},
success: function(response) {
console.log("Response :" , response)
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
}
Now I have the html which is the script is being called on
<div class="item col-lg-4 grid-group-item list-group-item mh-animate">
<div class="vehicle-wrap">
<div class="v-image">
<div class="v-special"><i class="fas fa-star"></i> Special</div>
<img class="group list-group-image img-fluid" src="" alt="" />
</div>
<div class="v-info">
<h4 class="list-group-item-heading"> 2019 Ford F-150 XLT </h4>
<div class="v-info-details">
<div class="v-details">
<ul>
<li><strong>Body Style: </strong></li>
<li><strong>Model Code: </strong></li>
<li><strong>Engine: </strong></li>
<li><strong>Drive Type: </strong></li>
<li><strong>Transmission: </strong></li>
<li><strong>Ext. Color: </strong></li>
<li><strong>Int. Color: </strong></li>
<li><strong>MPG: </strong>19 City / 25 Hwy</li>
<li class="vinDisplay"><strong>VIN #: </strong><span></span></li>
<li><strong>Stock #: </strong></li>
</li>
</ul>
</div>
I could Even log the data when the page is being loaded
https://imgur.com/a/EQzDsMv
Now How I am going to plot those data from the request to the html ? Do i need templating engine like Nunjucks to that ? cause I am use to angular and other Frameworks I am just new on using jquery . Any idea?
From what I can understand, you are asking how to edit HTML with jQuery.
If so, then you can use
$("#elementIdGoesHere").html(dataGoesHere)
if you are selecting by ID and
$(".elementClassGoesHere").html(dataGoesHere)
if you are selecting by class name.
$(function() {
var ajaxJsonData = [{
name: 'a',
value: 'value1'
},
{
name: 'b',
value: 'value2'
},
{
name: 'c',
value: 'value3'
}
];
//var temp = '';
//for (var i = 0; i < ajaxJsonData.length; i++) {
//temp += '<div>name: ' + ajaxJsonData[i].name + ',value: ' + //ajaxJsonData[i].value + '</div>';
//}
var value = 'value';
var $temp = `
<div class="item col-lg-4 grid-group-item list-group-item mh-animate">
<div class="vehicle-wrap">
<div class="v-image">
<div class="v-special"><i class="fas fa-star"></i> Special</div>
<img class="group list-group-image img-fluid" src="" alt="" />
</div>
<div class="v-info">
<h4 class="list-group-item-heading"> 2019 Ford F-150 XLT </h4>
<div class="v-info-details">
<div class="v-details">
<ul>
<li><strong>Body Style: ${value} </strong></li>
<li><strong>Model Code: </strong></li>
<li><strong>Engine: </strong></li>
<li><strong>Drive Type: </strong></li>
<li><strong>Transmission: </strong></li>
<li><strong>Ext. Color: </strong></li>
<li><strong>Int. Color: </strong></li>
<li><strong>MPG: </strong>19 City / 25 Hwy</li>
<li class="vinDisplay"><strong>VIN #: </strong><span></span></li>
<li><strong>Stock #: </strong></li>
</li>
</ul>
</div>
`
setTimeout(function() {
$('.container').html($temp);
}, 2000);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"></div>
I simulated the ajax asynchronous request and then dynamically inserted the html fragment.
I have a code that take the value from SharePoint List using REST (ajax), as shown as below:
function getItems() {
$.ajax({
async: true,
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Network Tech')/items",
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function(data) {
data = data.d.results;
console.log(data);
$.each(data, function(index, value) {
var value = value.Service;
});
},
error: function(error) {
console.log(JSON.stringify(error));
}
})
}
I also have a HTML code for the web page, as shown as below:
<body>
<div class="container">
<div class="col-sm-1">
<h3><br><br>Networking<br></h3>
<div class="panel-group wrap" id="bs-collapse">
<div class="panel">
<div class="panel-heading panel-bg-1">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#" href="#0101" id="v1">Virtual Networking<br></a>
</h4>
</div>
<div id="0101" class="panel-collapse collapse">
<div class="panel-body">
Coming Soon
</div>
</div>
</div>
</div>
</div>
</div>
</body>
Right now I want to take the value from SharePoint List and display it inside the panel-body. I know how to display it on table but I don't know how to do it on this one. Please help me on this.
You can use this Library that developed by me. Get Here
Then you need to do small callback
var appUrl = GetUrlKeyValue("SPAppWebUrl");
var hostUrl = GetUrlKeyValue("SPHostUrl");
var list = SPMagic.ListManager(appUrl, hostUrl, "Network Tech");
list.getAllListItems("Id", 100,).then(function (res) {
console.log(res.d.resutls);
}, function(err){
console.log(err);
}
Then you can use KnockoutJS to do the Bindings for the table.
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>
I'm trying to send a PHP variable to JavaScript using AJAX and implementing to HTML, but the result doesn't show anything.
My HTML code:
<div class="contain" id="konten_data"
style="margin-top: 20px;"></div>
My JavaScript code:
function tampilDepan(id){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: 'action_type=tdepan&id='+id,
success:function(html){
$('#konten_data').html(html);
}
});
}
My PHP code (userAction.php):
($_POST['action_type'] == 'tdepan'){
$link = mysqli_connect("localhost", "root", "", "universitas");
$datas = mysqli_query($link, "SELECT * FROM mahasiswa where user='john' ");
if(!empty($datas)){
while ($datak = mysqli_fetch_assoc($datas)){
echo '<div class="row" style="margin-left: -90px;">
<div class="col-xs-6 col-sm-6 col-md-4">
<img class="img-thumbnail img-responsive"
src="images/test/'.$datak['gmb_batik'].'" alt=""></div>
<div class="col-xs-12 col-md-8">
<div class="content-box-large">
<p>'.$datak['desc_batik'].'</p>
</div>
</div>
</div>
<div class="row" style="margin-left: -90px; margin-top: 10px;">
<div class="col-xs-12 col-sm-6 col-md-4 col-md-offset-3">
<div class="content-box-large">
<h1 >asal <strong>'.$datak['asal_batik'].'</strong></h1>
</div>
</div>
<div class="col-xs-16 col-sm-6 col-md-2 col-md-offset-1">
<img class="img-thumbnail img-responsive"
src="login/admin/files/qrcode/'.$datak['qr_batik'].'"
alt="">
</div>
</div>
<div class="row" style="margin-left: -90px; margin-top: 10px;">
<div class="col-xs-12 col-sm-6 col-md-9 col-md-offset-4">
<div class="content-box-large">
<p>'.$datak['pola_batik'].' </p>
</div>
</div>
</div>';
}
}else {``
echo '<tr><td colspan="5">No user(s) found......</td></tr>';
}`
}
I don't know what is wrong, I hope somebody can help me.
Try to change the javascript code to
function tampilDepan(id){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: {action_type: "tdepan", id: id},
success:function(html){
$('#konten_data').html(html);
}
});
}
As you can see, data is passed as an object instead of a string.
Also, be aware that if no user was found, you are putting a <tr> inside a <div>.
try to change in your ajax call.
function tampilDepan(id){
var postData ={"action_type":tdepan,"id":id};
$.ajax({
type: 'POST',
url: 'userAction.php',
data: postData ,
success:function(html){
$('#konten_data').html(html);
}
});
}
try to use the format below in calling ajax:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{ "action_type":"' + tdepan + '", "id":"' + id + '"}',
url: 'userAction.php',
success: function (data) {
conosle.log(data);
},
error: function (error) {
console.log(error);
}
});
You are trying to get your data using konten_data probably by using jQuery selector $('#konten_data').val();
, but I don't see it in the PHP code as where you are pushing the data to render onto the DOM. Try setting the value of konten_data by adding an element before the success callback or on DOM render and you should be good from there.
I want to javascript loop for wrapping two line of products layouts after i got a respond from ajax.
Purposed: I want to get result like below
<div class="owl-item">
<div class="row item">
<div class="product">
<div class="image">
<img src="asset/img/main/9.jpg" alt="img">
<div class="promotion"><span class="discount">4</span></div>
<div class="description">
<div class="price"><span>1.0000</span></div>
<h4></h4><p>short detial</p>
</div>
</div>
</div>
</div>
<div class="row item">
<div class="product">
<div class="image">
<img src="9.jpg"alt="img">
<div class="promotion"><span class="discount">4</span></div>
<div class="description">
<div class="price"><span>2.0000</span></div>
<h4></h4>
<p>short detial</p></div>
</div>
</div>
</div>
</div>
As the above html planned I want to loop <div class="owl-item"> one times then I will loop <div class="row item"> two times So my html layout will wrap my products as the below images.
$.ajax({
type: "GET",
url: "<?php echo base_url('main/dataaccess'); ?>",
dataType: "json",
cache: false,
success: function (data, st) {
if (st == 'success') {
$.each(data, function (i, obj) {
var out = '<div class="row item">';
out += '<div class="product">';
out += '<div class="image">';
out += '<img src="asset/img/main/9.jpg" alt="img" class="img-responsive">';
out += '<div class="promotion"><span class="discount">' + obj.prodId + '</span> </div>';
out += '<div class="description"><div class="price"><span>' + obj.prodPrice + '</span></div><h4>' + obj.prodName + '</h4>';
out += '<p>short detial</p>';
out += '</div>';
out += '</div>';
$(out).appendTo("#ps");
});
$("#ps").owlCarousel({
navigation: false,
pagination: false,
items: 8,
itemsTablet: [408, 2]
});
}
}
});
This is the layout that i want to get
But as my code I will got layout as below that I don't want it
Are one of those classes that are applying to your div set as display:inline-block ? I suggest inspecting the rendered page to confirm that the divs are display: block.