jQuery append image from JSON source and loop - javascript

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>");
})

Related

JSON url to link

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.

filter duplicate rows with cake php and java script

I'm trying to filter table which is append using java script with cake php frame work .
and the following code is for adding this tables when i have click on add new magazine ,, but the problem is that , It's add double rows which has been added before . So i need to filter the added rows to delete the duplicated row.
/// function to show magazines data table
$('#add_researches_button').click(function () {
$("input[name='bstock_researchs_id[]']:checked").each(function (i) {
val[i] = $(this).val();
});
$.ajax({
type: "POST",
url: '../BstockIn/getResearchesIds/' + val,
dataType: "json",
success: function (data) {
$('#researches').css('display', 'block');
var res = $.parseJSON(data);
var CountResearches = 0;
jQuery.each(res, function (index, value) {
CountResearches++;
$("#researches").append("<tr><td>"
+ value.research_serial +
"</td><td>"
+ value.research_release_date +
"</td><td>"
+ value.research_release_hejry_date +
"</td><td>"
+ value.research_pages +
"</td><td>"
+ value.research_copies +
"</td></tr>"
);
});
/// function to show magazines data table
$('#add_researches_button').click(function() {
$("input[name='bstock_researchs_id[]']:checked").each(function(i) {
val[i] = $(this).val();
});
$.ajax({
type: "POST",
url: '../BstockIn/getResearchesIds/' + val,
dataType: "json",
success: function(data) {
$('#researches').css('display', 'block');
var res = $.parseJSON(data);
var CountResearches = 0;
jQuery.each(res, function(index, value) {
CountResearches++;
if ($("#researches tr[data-id='" + value.research_serial + "']").length == 0)
$("#researches").append("<tr data-id='" + value.research_serial + "'><td>" +
value.research_serial +
"</td><td>" +
value.research_release_date +
"</td><td>" +
value.research_release_hejry_date +
"</td><td>" +
value.research_pages +
"</td><td>" +
value.research_copies +
"</td></tr>"
);
});

incorporating pagination in ajax json

I have a ajax json retrieving all query results in a div.I'm not sure how to introduce pagination though.
<script>
$(document).ready(function () {
var hdnIds = document.getElementById('<%= HiddenField1.ClientID %>').value;
$.ajax({
type: "POST",
url: "WebService1.asmx/GetEmployees",
data: "{userid: " + JSON.stringify(hdnIds) + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (list) {
$("#Something").append("<ul id='bullets' class='ul1'></ul>");
for (i = 0; i < list.d.length; i++) {
$("#bullets").append("<li class='li1'>"
+ "<div style='float:left; width:20%'>"
+ "<img id='image' src='Handler3.ashx?id=" + list.d[i].id + "' />"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small; font-style:bold'>" + list.d[i].UserName + "</p>"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small'>" + list.d[i].Created_on + "</p>"
+ "</div>"
+ "<div style='float:left; width:80%'>"
+ "<p class='p11'>" + list.d[i].Statusmes + "</p>"
+ "</div>"
+ "</li>");
}
},
error: function (e) {
$("#Something").html("There was an error retrieving records");
}
});
});
</script>
And html as
<div id="Something"></div>
ANy help will be greatly appreciated!
First, I would read up on javascript templating. There are a lot of libraries out there that will allow you to remove the bloated html code from your JS code so that it's easier to manage. Something like this: https://github.com/BorisMoore/jquery-tmpl.
After that, you should put the responsibility of pagination on the server side and let the JS/Ajax handle the calls to retrieve the data set. For instance:
//server side
var start = request.params.start //retrieve start index for data set
var limit = request.params.limit //retrieve max number of data set size
return db.Model.find({start: start, limit: limit, ...})
//client side JS/Ajax
//load first page 0-9
$.ajax({
url: '/my/data/url',
params: {
start: 0, //start at first record in db
limit: 10 //only return 10 results
}
}).success(function(data) {
//render data set using template
$.template('#my-data-template', data).renderTo('#someDiv');
});
//load second page 10-19
$.ajax({
url: '/my/data/url',
params: {
start: 10, //start at nth record in db
limit: 10 //only return 10 results
}
}).success(function(data) {
//render data set using template
$.template('#my-data-template', data).renderTo('#someDiv');
});
If I understand the question correctly, you already know about append which is what you need, but you need to change all your ids to classes since there will be more than 1 of them. Then, put all of the html you want to append into a string and just append that html.
HTML:
<div id = "parent">
<div class = "Something"></div>
</div>
JAVASCRIPT (replace to the success AJAX call):
var htmlList = "<div class = "Something"><ul class='bullets ul1'>";
for (i = 0; i < list.d.length; i++) {
htmlList += "<li class='li1'>"
+ "<div style='float:left; width:20%'>"
+ "<img id='image' src='Handler3.ashx?id=" + list.d[i].id + "' />"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small; font-style:bold'>" + list.d[i].UserName + "</p>"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small'>" + list.d[i].Created_on + "</p>"
+ "</div>"
+ "<div style='float:left; width:80%'>"
+ "<p class='p11'>" + list.d[i].Statusmes + "</p>"
+ "</div>"
+ "</li>");
}
htmlList += "</ul></div>";
$("#parent").append(htmlList);

Recieving JSON from AJAX Call with MongoDB

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>';
});

ASP.NET MVC AJAX call returning value to view from controller

During AJAX call is it possible to return ViewData, TempData or a session back to the view? does these variables are included in the cycle? please comment
function submitForm(frm) {
var tdata = $(frm).serialize();
$.ajax({
url: "/Organization/EditOrganizationMeta",
data: tdata,
success: function (result) {
if (result["ErrorMessage"] == "No Error") {
$("#" + result["DivName"] + "1").hide();
$("#" + result["DivName"]).show();
$("#" + result["DivName"]).empty();
$("#" + result["name"]).attr("value", result["SavedValue"]);
$("#" + result["DivName"]).append("<b>" + result["SavedValue"] + "</b>");
$("#" + result["DivName"] + "2").empty();
$("#" + result["DivName"] + "2").append("<b>Record is successfully saved</b>");
}
else if (result["ErrorMessage"] != "") {
$("#" + result["DivName"] + "1").show();
$("#" + result["DivName"]).hide();
$("#" + result["DivName"]).empty();
$("#" + result["name"]).attr("value", result["PreviousValues"]);
$("#" + result["DivName"] + "2").empty();
$("#" + result["DivName"]).append("<b>" + result["PreviousValues"] + "</b>");
$("#" + result["DivName"] + "2").append("<b>" + result["ErrorMessage"] + "</b>");
}
},
type: "POST",
datatype: "json"
});
return false;
}
Bsaed on the JavaScript code that you just posted, I think that the best approach would be to return the parameters you want the success function to use as JSON.
To return an object as JSON from an ASP.NET MVC controller ActionResult, you have to do the following:
return Json(myObject); //where myObject is an object that contains all the information that you want to return.

Categories

Resources