Display php data json_encoded with ajax - javascript

I convert my php code to json with json_encoded function.
After I write ajax code to display my data in ajax but when running don't display my data.
My json code:
[
{"Name":"fasher","Description":"2500 kg","Namyandegi":"20,500,000","Bazar":"22,410,000"}
,
{"Name":"shob","Description":"1000 kg","Namyandegi":"10,400,000","Bazar":"12,220,000"}
]
and ajax file:
<script type='text/javascript'>
$(document).ready(function(){
$.getJSON('saipa.php', function(data) {
$.each(data, function(key, val) {
$('ul').append('<li id="shoker">' + val.Name + ' ' + val.Description + ' ' + val.Namyandegi + ' ' + val.Bazar + '</li>');
});
});
});
</script>
<body>
<ul><li id="shoker"></li></ul>
</body>

Use the index overload $.each()
$.each(data, function(index) {
$('ul').append('<li id="shoker">' + data[index].Name + ' ' +
data[index].Description + ' ' +
data[index].Namyandegi + ' ' +
data[index].Bazar + '</li>'
);
});

Related

How do I display external API search results in a table?

I am a final year student and am creating a food log web application for my major project. I have created a search function that allows me to search and display external API results, but now I wish to display them in a table, can anyone help please?
I would prefer if it would be a table that can be filtered, eg, the columns ordered ascending/descending?
Thanks
function get foodItem(userInput) {
var storedSearchItem;
$('.resultContainer').html('');
$.ajax({
type: 'GET',
async: false,
url: 'https://api.nutritionix.com/v1_1/search/'+userInput+'?'+
'fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=325062a4&appKey=bf1a30b2066602dc6f33db888cd53bd3',
success: function(d) {
storedSearchItem = d.hits;
}
});
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}//ends get result function
function searchValue() {
var formVal = document.getElementById('itemSearch').value; //value from search bar
getFoodItem(formVal);
}
$('#searchForm').submit(function(e) {
e.preventDefault();
});`
You need to append your table in the success function
your code will look like something like this
success: function(d) {
storedSearchItem = d.hits;
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}

How to replace the values in javascript?

$(document).ready(function(){
$.ajaxSetup ({
cache: false
});
setTimeout(getData, 5000);
});
/* call the php that has the php array which is json_encoded */
function getData(){
$.getJSON('api.php', function(data) {
$('ul').empty();
/* data will hold the php array as a javascript object */
$.each(data, function(key, val) {
$('ul').append('<li id="' + key + '">' + val.date + ' ' + val.event + ' ' + val.region + ' ' + val.host + ' '+ val.type + ' ' + val.info + '</li>');
});
setTimeout(getData, 5000);
});
}
Output:
2016-09-09 09:12:18 WARN MRP SIU05 [main] Started, locked port 7075
How to replace (val.event) the occurrence of WARN on WARN2?
Please try below
//Here value is val.event
//value = val.event
var value = 'WARN2';
value = value.replace(value,'WARN');
console.log(value);

Reload JSON data from javascript

I am trying to reload data every 5 seconds using jQuery. The URL for the JSON data can be found at http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json
This is the code I am trying:
$.getJSON("http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json", function (json) {
$.each(json.data.games.game, function (i, value) {
$('#LMP').append('<div id="equipo"><div class="p1"><img src="img/lmp/' + value.away_name_abbrev + '.png' + '" alt=""></div><div class="p2"><div class="p2-1"> </div><div class="p2-2">' + value.status.inning + ' ' + value.status.top_inning + '</div><div class="clear"></div></div><div class="p3"><img src="img/lmp/' + value.home_name_abbrev + '.png' + '" alt=""></div><div class="clear"></div></div>');
});
});
One way to do it might look like this:
function getJson () {
$.getJSON("http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json", function (json) {
$.each(json.data.games.game, function (i, value) {
$('#LMP').append('<div id="equipo"><div class="p1"><img src="img/lmp/' + value.away_name_abbrev + '.png' + '" alt=""></div><div class="p2"><div class="p2-1"> </div><div class="p2-2">' + value.status.inning + ' ' + value.status.top_inning + '</div><div class="clear"></div></div><div class="p3"><img src="img/lmp/' + value.home_name_abbrev + '.png' + '" alt=""></div><div class="clear"></div></div>');
});
});
}
var i = setInteval(getJson, 5000);

JQuery $.getJSON confused me

I am completely confused by the $.getJSON function!
$.getJSON('http://api.worldweatheronline.com/free/v1/weather.ashx?key=mykey&q=' + lat + ',' + longi + '&fx=no&format=json', function(data) {
$('#weather').html('<p> Humidity: ' + data.current_condition.humidity + '</p>');
$('#weather').append('<p>Temp : ' + data.current_condition.temp_C + '</p>');
$('#weather').append('<p> Wind: ' + data.current_condition.windspeedMiles + '</p>');
});
This is the json that is at that url is:
{
"data":{
"current_condition":[
{
"cloudcover":"0",
"humidity":"82",
"observation_time":"04:07 PM",
"precipMM":"0.2",
"pressure":"997",
"temp_C":"11",
"temp_F":"52",
"visibility":"10",
"weatherCode":"356",
"weatherDesc":[
{
"value":"Moderate or heavy rain shower"
}
],
"weatherIconUrl":[
{
"value":"http:\/\/cdn.worldweatheronline.net\/images\/wsymbols01_png_64\/wsymbol_0010_heavy_rain_showers.png"
}
],
"winddir16Point":"WSW",
"winddirDegree":"240",
"windspeedKmph":"26",
"windspeedMiles":"16"
}
],
"request":[
{
"query":"Lat 51.24 and Lon -1.15",
"type":"LatLon"
}
]
}
}
It must be something to do with my syntax!
Try to pass callback=? as the callback function for using jsonp format
$.getJSON('http://api.worldweatheronline.com/free/v1/weather.ashx?key=mykey&q=' + lat + ',' + longi + '&fx=no&format=json&callback=?', function (data) {
$('#weather').html('<p> Humidity: ' + data.current_condition.humidity + '</p>');
$('#weather').append('<p>Temp : ' + data.current_condition.temp_C + '</p>');
$('#weather').append('<p> Wind: ' + data.current_condition.windspeedMiles + '</p>');
});
Try this :
$.getJSON('http://api.worldweatheronline.com/free/v1/weather.ashx?key=mykey&q=' + lat + ',' + longi + '&fx=no&format=json&callback=?', function (data) {
$('#weather').html('<p> Humidity: ' + data.data.current_condition[0].humidity + '</p>');
$('#weather').append('<p>Temp : ' + data.data.current_condition[0].temp_C + '</p>');
$('#weather').append('<p> Wind: ' + data.data.current_condition[0].windspeedMiles + '</p>');
});
because current_condition is an object array you can access it by using its index. addition data property because your JSON itself wrapped with data object.

Handling JSON Object With jQuery?

I'm having trouble handling a JSON object that I'm getting back from an AJAX request.
It's a simple flat JSON object, and all I want to do is write the responses back onto the page.
Can anyone point out how to loop over these objects and output the values? I just keep getting [undefined] or [object] written
Code here:
$.ajax({
type: "POST",
url: "func/chatResponse.php",
data: dataString,
success: function() {
$.getJSON('func/chatResponse.php?a=jsonLatest', function(data) {
$.each(data, function(index) {
//items.push('<li id="' + key + '">' + val + '</li>');
$('body').append('<li id="' + data.user + '">' + data.user + '</li>');
alert(data);
});
});
alert("done");
}
});
JSON sample here
[
{"user":"someguy","message":"my message","timestamp":"2011-04-19 17:26:09"},
{"user":"Cheyne","message":"Hey There ... Nice site","timestamp":"2011-04-19 17:26:09"}
]
data is the array, while you want the items inside the array.
$.each doesn't change data to become the items, instead it passes individual items as the second parameter to the function you supply:
$.each(data, function (index, item) {
// Use item in here
$('body').append('<li id="' + item.user + '">' + item.user + '</li>');
});
Alternatively, you can use data[index]:
$.each(data, function (index) {
// use data[index] in here
$('body').append('<li id="' + data[index].user + '">' + data[index].user + '</li>');
});
By the way, avoid ugly string concatenation with:
$('<li>', {id: item.user, text: item.user}).appendTo('body');
What you want is
$.each(data, function(index) {
//items.push('<li id="' + key + '">' + val + '</li>');
$('body').append('<li id="' + data[index].user + '">' + data[index].user + '</li>');
alert(data);
});

Categories