Displaying php result in HTML using AJAX - javascript

I am trying to display the result of my php in different <div>-s. My plan is that I make a query in my php and display the result in JSON format. Due to the JSON format my result can be displaying in different <div>. How can I reach that for example the "name" can be displayed between <div> tags?
The example result of php:
[
{
"id": 0,
"name": "example1",
"title": "example2"
},
{
"id": 0,
"name": "example1",
"title": "example2"
}
]
The attempt:
<div class="result"></div>
<script>
$.ajax({
type:'GET',
url:'foo.php',
data:'json',
success: function(data){
$('.result').html(data);
}
});
</script>

Hi try parsing the returned data into a JSON object :
<div class="result"></div>
<script>
$.ajax({
type:'GET',
url:'foo.php',
data:'json',
success: function(data){
// added JSON parse
var jsonData = JSON.parse(data);
// iterate through every object
$.each(jsonData, function(index, element) {
// do what you want with each JSON object
$('.result').append('<div>' + element.name + '</div>');
});
}
});
</script>
// PS code is untested.
// Regards

Do it like below:-
success: function(data){
var newhtml = ''; //newly created string variable
$.each(data, function(i, item) {//iterate over json data
newhtml +='<div>'+ item.name +'</div>'; // get name and wrapped inside div and append it to newly created string variable
});
$('.result').html(newhtml); // put value of newly created div into result element
}

You can create it like this:
for (var i = 0; i < res.length; i++) {
var id = $("<div></div>").html(data[i].id);
var name = $("<div></div>").html(data[i].name);
var title = $("<div></div>").html(data[i].title);
$('.result').append(id).append(name).append(title);
}

Related

How to put JSON data into a HTML div?

Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.
function showEspece(espece, categorie, object) {
$.ajax({
type: 'POST',
url: 'getespece.php',
data: {
espece: espece,
categorie: categorie
},
dataType: 'json',
success: function(data) {
console.log(data);
$('#output').html(data); //what i try to do but don't work
},
error: function(xhr, status, error) {
console.log(error);
}
});
}
<div id="output"></div>
And here is what the variable data contains:
How can I show the variable's content in an HTML div - in a table particularly?
You can use pre tag to display JSON.
var data = {"NOMA":["Chachi","Rafiki","Chakra"],"SEXE":["F","M","F"],"DATENAISSANCE":["05-MAY-15","07-JAN-15","17-SEP-17"]};
$('pre').html(JSON.stringify(data, undefined, 2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>
Your data variable it's a JS object you need to convert it to string or the format you want to show it before calling $('#output').html(data).
You can do something like:
function showEspece(espece, categorie, object)
{
$.ajax({
type : 'POST',
url: 'getespece.php',
data: {espece: espece, categorie: categorie },
dataType: 'json',
success: function(data)
{
console.log(data);
data = JSON.stringify(data)
$('#output').html(data); //what i try to do but don't work
},
error: function(xhr, status, error) {
console.log(error);
}
});
}
as your json data children are array you can use $.each function:
Example:
var noma = data.NOMA;
var html_append = '';
$.each(noma, function(key,value) {
html_append += value +'<br>';
});
$('#output').html(html_append);
The same code you can use for also data.DATENAISSANCE and data.SEXE
Since your data returned is already in a JSON format, i suggest you to use $.getJSON and change your $_POST by $_GET variables in your getespece.php.
Also, your JSON Objects seems to be kind of not formatted correctly.. If you want to display your "especes" in an HTML table, the right JSON format could be something like this:
{
"Columns": [
"DateDeNaissance",
"Nom",
"Sexe"
],
"Especes": [{
"DateDeNaissance": "05-MAY-15",
"Nom": "Chachi",
"Sexe": "F"
}, {
"DateDeNaissance": "07-JAN-15",
"Nom": "Rafiki",
"Sexe": "M"
}, {
"DateDeNaissance": "17-SEP-17",
"Nom": "Chakra",
"Sexe": "F"
}]
}
Once you have this output from your PHP, change your JS to this:
$.getJSON("getespece.php", {
espece: espece,
categorie: categorie
})
.done(function(json) {
// Build the html Table
var html = "<table>\n";
html += "<thead>\n";
html += "<tr>\n";
// Columns
$.each(json.Columns, function(k, value) {
html += "<th>" + column + "</th>\n";
});
html += "</tr>\n";
html += "<tbody>\n";
// Rows
$.each(json.Especes, function(column, values) {
html += "<tr>\n";
// Cells
$.each(values, function(k, val) {
html += "<td>" + val + "</td>\n";
});
html += "</tr>\n";
});
html += "</tbody>\n";
html += "</table>\n";
$("#output").html(html);
});
var data = {
DATENAISSANCE: [...],
...
}
var root = document.getElementById("output");
var table = element("table");
root.appendChild(table);
var dataName;
for (dataName in data) {
if (data.hasOwnProperty(dataName)) {
var row = element("tr", element("th", dataName));
data[dataName].forEach(function (dataValue) {
row.appendChild(element("td", dataValue));
});
table.appendChild(row);
}
}
// Create a convenient function `element` which creates an element and sets its content
function element(nodeName, content, attributes, eventListeners) {
var node = document.createElement(nodeName);
appendChildren(node, content);
return node;
}
function appendChildren(node, content) {
var append = function (t) {
if (/string|number/.test(typeof t)) {
node.innerHTML += t;
} else if (t instanceof HTMLElement) {
node.appendChild(t);
}
};
if (content instanceof Array) {
content.forEach(function (item) {
append(item);
});
} else {
append(content);
}
}

Replace javascript variable without id or class

I have this javascript and once the AJAX process is executed I want to replace this variable to some other variable.
window.onload = function() {
oldvariable = [];
var chart = new Chart("Container2", {
data: [{
type: "column",
dataPoints: oldvariable
}]
});
}
When I process the AJAX request and fetch JSON data which is stored in oldvariable, it is not written so I have few options. I tried ads they are working in HTML but not under script tag.
If I can define oldvariable='<div class="second"></div>'; and replace this with processed JSON data then it is working and giving correct output in HTML but in javascript < tag is not allowed as variable so we cant define oldvariable like that.
$( "div.second" ).replaceWith( ''+newvariable +'' );
So is there anyway I can replace javascript variable as HTML tags are not allowed in variable and without tag javascript can't replace.
I have one more probable solution.regex. Search for oldvariable in entire HTML code and replace with newvariable but that process will be very slow so what is the best way to do this.
My vairables are globally defined and AJAX request is in external file and above codes are embeded in HTML.
========edit
how we can replace oldvariable with newvariable in above javascript
====== ajax code- variable name is different
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var oldvariable = '',
downlo;
for (var i = 0; i < data.length; i++) {
downlo = data[i];
oldvariable += '' + downlo.ndchart + '';
}
$('#chek').html(oldvariable );
}
})
})();
});
you need to update chart datapoints and re-render the chart after ajax success like this
ajax :
...
success:function(response)
{
chart.options.data[0].dataPoints=response;
//response is (array) of dataSeries
chart.render();
}
.......
update 1 : As per your code data should be updated like this
.....
success:function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
.....
update 2:
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
})
})();
});

Accessing specific data from csv file and show on html

Having some problems accessing specific data from a csv file. Currently I can see all data in the console but when I try to show a specific data getting undefined. For example in my console I get all data and I want to extract the subtitles and show it on the html in a class score-text.
My console looks like this:
subtitle 1,
name1,65%
name2,65%
name3,65%
name4,65%
total,70%
,
subtitle 2,
name1,65%
name2,65%
name3,65%
name4,65%
total,30%
,
subtitle 3,
name1,65%
name2,65%
name3,65%
name4,65%
total,60%
,
subtitle 4,
name1,65%
name2,65%
name3,65%
name4,65%
total,50%
$.ajax({
url: 'test.csv',
type: "GET",
dataType: "text",
success: function (data) {
var rows = data.split(/\n/);
for (var rowIndex in rows)
{
var columns = rows[rowIndex].split(/,/);
for (var colIndex in columns)
{
var colValue = columns[colIndex].trim();
console.log(colValue);
}
}
$(".score-text").each(function( index, value ) {
value.innerHTML = result[columns[2]] = rows[2];
});
}
});
Why don't you try putting the insertion part into the loop?
var columns = rows[rowIndex].split(/,/);
for (var colIndex in columns)
{
var colValue = columns[colIndex].trim();
console.log(colValue);
$(".score-text").append(colValue);
}

exclude certain object property in the foreach loop in jQuery AJAX

Fiddle Example
I have a php file to return json data for main content data as well as an additional property for pagaination data. I want to know if it's possible to exclude the property for the pagination data when reiterating over the data in a foreach loop to avoid the undefined warning.
var data = [{"larger_than_1":true,"current_page_no":110,"otherpageno":"100,101,102,103,104,105,106,107,108,109,111,112,113,114,115,116,117,118","current_not_equal_total":"true","nextpage":111,"website":"www.google.com"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"}];
The pagination data is always the first property, I tried if(item[i]!== 0) but it doesn't work.
Ajax:
$(document).ready(function(){
$.ajax({
url: "pagination.php",
type: "POST",
dataType: "json",
success:function(data) {
var item_html = "";
console.log(data[0]);
item_html += '<h3>'+data[0].larger_than_1+'</h3>';
$.each(data,function(index,item)
{
if(item[index]!== 0)
{
item_html += '<p>'+item.kal+'</p>';
}
});
$('#area').append(item_html);
}
});
});
Change item[i] to i in your if statement.
jsFiddle
You need to determine the data which need to be exclude. but as its coming as first value you can simply use index to filter out desired data. i.e. if(i!= 0):
var data = [{"larger_than_1":null,"current_page_no":110,"otherpageno":"100,101,102,103,104,105,106,107,108,109,111,112,113,114,115,116,117,118","current_not_equal_total":"true","nextpage":111,"website":"www.google.com"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"}];
var item_html ="";
jQuery.each(data, function(i, item) {
if(i!= 0)
{
item_html += '<p style="margin:5px;background:beige">'+item.kal+'</p>';
}
$('#area').append(item_html);
});
Working Demo

Append some items to a div, and the rest to another div in jQuery

I'm writing a script to parse a JSON file, and I seem to have got myself into a tricky situation. Can I append half of the returned items in one div element and the other half in another div elemet?
Here is the original markup:
<div class="feed"><div class="displayfeed main"></div></div>
<div class="feed"><div class="displayfeed second"></div></div>
I want the page to display like this after appending the returned data:
<div class="feed">
<div class="displayfeed main">
<h3>item1's title</h3> //Half of the items in "div.main"
.......
</div>
</div>
<div class="feed">
<div class="displayfeed second">
<h3>item2's title</h3> //Half of the items in "div.second"
...........
</div>
</div>
JS Code:
$.ajax({
url: source,
success: function (data) {
var item_html =
$(data.items).each(function (index, item) {
'<h3>'+item.title+'</h3>';
});
//Any way to append some of them in ('.main') and the rest in ('.second')?
$('.displayfeed').append(item_html);
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
I'm looking for any possible suggestions, otherwise I have no choice but to parse the same feed twice. Any help would be appreciated.
Updated:
I've set up a FIDDLE using Gogole news feed in JSON format converted by YQL as an example
Use multiply selector.
$.ajax({
url: source,
success: function (data) {
var item_html_main = "";
var item_html_second = "";
// assign values to item_html_main and item_html_second variables
$('.displayfeed.main').append(item_html_main);
$('.displayfeed.second').append(item_html_second);
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
I don't know what structure you have but you can try this:
$.ajax({
url: source,
success: function (data) {
var item_html_main = "";
var item_html_second = "";
// assign values to item_html_main and item_html_second variables
var count = data.count;
var half = count/2;
var counter = 0;
for(item in data) {
if(counter < half) {
item_html_main += item;
} else {
item_html_secodn += item;
}
counter++;
}
$('.displayfeed.main').append(item_html_main);
$('.displayfeed.second').append(item_html_second);
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
You can try something like this. if it does not matter which posts is displayed in which container
$.ajax({
url: "<your-URL>",
success: function (data) {
var length = 0;
var items = data.query.results.item;
items = items.map(function(item){
return '<h3>'+item.title+'</h3>';
});
var half = items.length/2;
for(var i = 0; i < items.length; i++)
if(i < half)
$('.main').append(items[i]);
else
$('.second').append(items[i]);
length++;
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
Of course, but you need some separator or something
You can append all to your first div and then copy the part you want in the second div out of the first.
Example
item_html
<h2>Headline</h2>
<span>
News Text
</span>
js
$('.displayfeed').append(item_html);
sec = $('.displayfeed').find('span').html();
$('.displayfeed').find('span').remove();
$('.displayfeed second').append(sec);

Categories

Resources