I'm using the google news API and I want to add the value of the URL to be on the article title and convert the image from the JSON data to be viewable. Below is my code so far.
/*$.getJSON(url, function(data){
console.log(data);
});*/
$.ajax({
url:
"https://newsapi.org/v2/everything?apiKey=xxx&q=nrcs",
dataType: "json",
type: "get",
cache: false,
success: function (data) {
$(data.articles).each(function (index, value) {
//console.log(value);
$('#news').append('<div>' + '<h3 id="title" style="color:#B8860B;">' + value.title + '' + value.url + '</h3>' + '<p>' + '<span style="color:#C4BFBF; font-style: italic;">' + value.author + '</span>' + '<br>' + value.publishedAt + '<br>' + value.description + '</p>' + '</div>');
$('#link').append(value.url);
});
}
});
Judging just by this and not seeing the whole picture (returned Json, css styles and layout of the page; basically any conflicting factors) I’d try:
$.ajax({
url:
"https://newsapi.org/v2/everything?apiKey=xxx&q=nrcs",
dataType: "json",
type: "get",
cache: false,
success: function (data) {
$(data.articles).each(function (index, value) {
//console.log(value);
$('#news').append('<div>' + '<h3 id="title" style="color:#B8860B;">' + value.title + '' + value.url + '</h3>' + '<p>' + '<span style="color:#C4BFBF; font-style: italic;">' + value.author + '</span>' + '<br>' + value.publishedAt + '<br>' + value.description + '</p>' + '<br>' + value.url + '</div>');
});
}
});
Instead of appending to the appended div, add it direct within; check the console for any errors and if there are none your issue may be related to the container / style of your page.
Related
I'm currently working on a code that displays users activity log. Ajax will call the route and gets the response (json) results. I need to be able to display the log records on admin dashboard without refreshing the page.
Ajax
$(document).ready(function() {
$.ajax({
type: 'get',
url:"{{ route('users.activity') }}",
dataType: 'json',
success: function (data) {
$.each(data, function() {
$.each(this, function(index, value) {
console.log(value);
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
});
});
},error:function(){
console.log(data);
}
});
});
If I understood, you can do this:
$(document).ready(function() {
var requesting = false;
var request = function() {
requesting = true;
$.ajax({
type: 'get',
url:"{{ route('users.activity') }}",
dataType: 'json',
success: function (data) {
$.each(data, function() {
$.each(this, function(index, value) {
console.log(value);
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
requesting = false;
});
});
},error:function(){
console.log(data);
}
});
};
if(!requesting){
setTimeout(request, 1000);
}
});
Every seconds it does a request to your users.activity route, so there is an update every second.
You need to send last record id in server. so you can get only new data.
my updated answer based on #stackedo answer .
$(document).ready(function () {
var lastId = 0; //Set id to 0 so you will get all records on page load.
var request = function () {
$.ajax({
type: 'get',
url: "{{ route('users.activity') }}",
data: { id: lastId }, //Add request data
dataType: 'json',
success: function (data) {
$.each(data, function () {
$.each(this, function (index, value) {
console.log(value);
lastId = value.id; //Change lastId when we get responce from ajax
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
});
});
}, error: function () {
console.log(data);
}
});
};
setInterval(request, 1000);
});
In controller add were condition to query :
UserActivity::where('id','>',$request->id)->get();
I'm working on fetching data from a JSON URL in jQuery with $ajax call and I'm using bootstrap in the HTML.
$.ajax({
url: 'https://services.web.bilinfo.dk/api/vehicle/?user=demo&password=ocfB6XzF73&format=json',
type: 'GET',
data: {
format: 'JSON'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
success: function(data) {
$.each(data, function(index, data) {
$('.col-md-4')
.append("picture" + '<img src= "' + data[0].Pictures + '">')
.append("<h1> Model:" + data[0].Model + "</h1>")
.append("<h1> make:" + data[0].Make + "</h1>")
.append("<p> variant:" + data[0].Variant + "</p>")
.append("<p> registrationDate:" + data[0].RegistrationDate + "</p>");
})
},
});
The image doesn't seem to come out, but displays a broken img like thing, any hints or suggestions?
And right now I'm only getting one car out, at data[0].
Now I'm using a $.each, but what if I would receive all cars?
I would generate a complete example, but the access control on that site does not allow it.
In your success handler try:
$.each(data.Vehicles, function(index, item) {
$(".col-md-4")
.append("picture" + '<img src= "' + item.Pictures[0] + '">')
.append("<h1> Model:" + item.Model + "</h1>")
.append("<h1> make:" + item.Make + "</h1>")
.append("<p> variant:" + item.Variant + "</p>")
.append("<p> registrationDate:" + item.RegistrationDate + "</p>");
})
I have this code which is fetching data from service according to button click. What I want this when I click previous or next button, I want to change pagenumber on bottom of dataTable.
$('.paginate_button.previous', this.api().table().container())
.on('click', function(){
// alert("Doruk");
if(pageNumber > 1) {
$.ajax({
url: "http://192.168.1.171:8080/LogWS/rest/v1/logs/normalized-logs-paged?pageNumber=" + pageNumber-- + "&&pageCount=10",
type: "post",
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
processData: false,
headers: {
Authorization: "Bearer " + localStorage.getItem("globalAuthenticationKey")
},
data:
JSON.stringify(hostAddresses)
,
success: function (response) {
var Table = document.getElementById("applicationviewTableID");
Table.innerHTML = "";
for (var i = 0; i < response.logData.length; i++) {
var trHTML = '';
// var trHTML2 = '';
trHTML += '<tr><td>' + response.logData[i].ip + '</td><td>' + response.logData[i].application + '</td><td>' + "" + '</td>';
$('#applicationviewTableID').append(trHTML);
/* trHTML2 += '<tr><td>' + response.logData[i].ip + '</td><td>' + response.logData[i].application + '</td><td>' + response.logData[i].operation + '</td><td>' + response.logData[i].entityType + '</td><td>' + response.logData[i].entity + '</td><td>' + response.logData[i].time + '</td>'
$('#DetailedApplicationsMalwareTableBodyID').append(trHTML2);*/
}
console.log( $('.paginate_button.active')[0]);
},
Below code shows me html code piece that I want to change in console.
console.log( $('.paginate_button.active')[0]);
It shows
<li class="paginate_button active">1</li>
And I want to change that "1" inside "a" tag
How can I do that
You have to select the inner a-tag too.
Then you can get the text like this:
$('.paginate_button.active a').text();
or edit like this:
$('.paginate_button.active a').text("2")
I have this code to get data from back -end
$('#display').click(function () {
var vacancyId = $("#vacancy").val();
var model = {
vacancyId: vacancyId
};
$.ajax({
url: '#Url.Action("Links", "Questions")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
var question2 = data;
for (var i = 0; i <= question2.length - 1; i++) {
var videoHTML = '<div style="width:100%;overflow-y: scroll;background:white;height:72%">' + '<div style="float:left; width:50%;height:296px;border-style:solid;margin-bottom:10px;">' +
'<video style="width:100%;height:290px; object-fit: contain;" controls>';
videoHTML += '<source src="' + document.location.origin + "/uploads/" + question2[i].Linkes + ".webm" + '" type="video/webm">';
videoHTML += '</video>' + '</div>' + '<div style="float:right;width:48%;text-align:center;height:296px;border-style:solid;padding-top:30px;">' + '<div>' + '<b>' + "Ф.И.О: " + '</b>' + '<b>' + question2[i].FIO + '</b>' + '</div>' + '<div>' + '<b>' + "Город: " + '</b>' + '<b>' + question2[i].City + '</b>' + '</div>' + '<div>' + '<b>' + "Город: " + '</b>' + '<b>' + question2[i].Vozrast + '</b>' + '</div>'+'</div>'+'</div>';
$(".videolist").append(videoHTML);
}
}
});
});
This one return date of birthday '<b>' + question2[i].Vozrast + '</b>'
I need to display age.
How I can do this on client-side?
You can do this in server side or client side depend on you.
If you like to do it in client side and Vozrast type is Date, so you can use third libraries to do this e.g. Moment.Js
var years = moment().diff(Vozrast, 'years');
var days = moment().diff(Vozrast, 'days');
I do it like this on client side
var today = new Date();
var yyyy = today.getFullYear();
Get year like this
And get age like this
(yyyy - question2[i].Vozrast)
I am getting a users details from a MongoDB database like this:
$user=$collection->findOne(array('_id' => new MongoId($_SESSION['user']['userid'])));
if (!empty($user)){
json_encode($user);
print_r($user);
}
I can get an entire JSON array from the AJAX but not individual elements - I get undefined:
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(msg){
alert(msg);
}
});
The actual JSON is structured like this:
username: john
password: hello
email: me#mailserver.com
I'm stuck.
you returning array object from getUser.php but you display it as a normal variable
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(msg){
$.each(msg,function(key,value){
alert(value.id);
});
}
});
i guess this will work..
You need to get the return value
$encoded = json_encode($user);
print_r($encoded);
The method you are using does not encode in place. It returns a left side value.
success: function (response)
{
if(response != 'error')
{
//parse into JSON
var jsonObj = JSON.parse(response);
var HTML = '';
//extract single value using each
$.each(jsonObj, function(key, val) {
HTML += '<tr><td>' + val.id + '</td><td>' + val.first_name + '</td><td>' + val.last_name + '</td><td>' + val.gender + '</td>'
+'<td>' + dt + '</td><td>' + val.phone + '</td><td>' + val.mobile + '</td><td>' + val.email + '</td>'
+'<td>' + val.address + ',' + val.city + ',' + val.state + '</td><td>' + val.country + '</td>'
+'<td>' + val.zip + '</td><td>' + val.hobbies + '</td><td>' + 'INR ' +val.salary + '</td><td>' + val.countryCode + '</td>'
+'<td>' + val.username + '</td><td>' + val.pwd + '</td></tr>';
});