How to put JSON data into a HTML div? - javascript

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

Related

How to set the data in AJAX success function?

I have an ajax call that is returning me the data to be populated in a drop down list. Now, I need to be able to select a value which is returned and set the value of the drop down in the same function if possible. But by using $("#idOfDropDown").val(data), it is not getting set i.e While I am submitting the data, in the database all the options that were returned and populated are getting submitted and not the selected option. So, How do I set the selected value only?
Here's my AJAX function:
$.ajax({
type: "POST",
dataType: 'json',
url: "/Controller/Action",
data: {
param: param,
},
success: function(data) {
if (data.Response == "Unsuccessful") {
console.log("Unsuccessful");
} else if (data.Response == "Successful" || data.Response == "ConditionallySuccessful") {
for (var i = 0; i < data.ExteriorColor.Data.length; i++) {
$("#Exterior_Color").append($("<option></option>").val(data.ExteriorColor.Data[i]).html(data.ExteriorColor.Data[i]));
console.log(data.ExteriorColor.Data[i]);
}
var html = '<ul>'
for (var i = 0; i < data.Options.length; i++) {
html += '<li>' + data.Options[i] + '</li>';
}
html += '</ul>'
$("#twoColumnOptions").append(html);
$("#twoColumnOptions").data(html);
$("#Options").val(data.Options);
$("#Exterior_Color").val(data.ExteriorColor.Data).change(); //Value to be changed
if (data.ExteriorColor.isInstalled == true)
$("#Exterior_Color").attr("disabled", true);
}
},
error: function(result) {
console.log("Error while fetching data");
}
});
Try to trigger the change you made using .trigger('change') like:
$("#Options").val(data.Options).trigger('change');
//Or
$("#Options").val(data.Options).change();
I implemented something similar in my solution and my code is like this, you need to set the value like this:
success: function (response) {
var array = response;
if (array != '') {
for (i in array) {
$("#district").append("<option value='"+
array[i].Id + "'>" + array[i].DistrictName + "</option>");
}
}
},

Displaying php result in HTML using AJAX

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

Where in laravel 5.2

I am trying to retrieve zipcodes from the database where I am getting an error- Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given. I am not sure if my where in query is correct. Thanks in advance.
$countiesList array looks like = ["Beaverhead", "Big Horn",......]
function in the model is:
public static function counties_zip($countiesList)
{
$zipCodes= Zip::select('ZIPCode')
->distinct()
->whereIn('CountyName', $countiesList)
->orderBy('ZIPCode', 'asc')
->get();
return $zipCodes;
}
In the controller:
public function zipCodes(Request $request) {
$zipCodes = Zip::counties_zip($request->counties);
return json_encode($zipCodes);
}
and my jS:
$(".submit").on("click", function(){
myList = [];
$('.select2 option:selected').each(function() {
myList.push($(this).val())
});
$countiesList=myList;
console.log($countiesList);
$.ajax({
type: "get",
url: http_host + '/leads/regions/counties/zipcodes?counties=' + $countiesList,
data: { counties: $countiesList},
dataType: "json",
success: function (data) {
var htmlText = '';
for ( var i=0;i<data.length;i++ ) {
htmlText += '<div class="div-conatiner">';
htmlText += '<input type="checkbox">' + data[i].ZipCode;
htmlText += '<div>';
}
$(".main-div").append(htmlText);
}
});
});
I think it's because you're using a GET request to pass multiple counties values to your controller, but not using the right counties[] parameter in your request. Currently, if you were to do a dd($countiesList); in your function, you wouldn't get an array, as you're not passing it an array; your passing a single value.
To specify a parameter as an array in a GET request, you'd need to do:
/leads/regions/counties/zipcodes?counties[]=one&counties[]=two...
For every single counties value you're trying to filter down to.
You may want to look into structuring this as a POST request, as
data : {
counties: $countieList
}
should be properly handled as an array of values in a $.post(url, data, function(response){ ... }); or $.ajax(...) request.
In the javascript I used JSON.stringify to convert the javascript array to JSON array. Then in the model I decoded the JSON string using json_decode.
JS:
$(".submit").on("click", function(){
myList = [];
$('.select2 option:selected').each(function() {
myList.push($(this).val())
});
$countiesList=myList;
console.log($countiesList);
$.ajax({
type: "get",
url: http_host + '/leads/regions/counties/zipcodes?counties=' + $countiesList,
data: { counties: $countiesList},
dataType: "json",
success: function (data) {
var htmlText = '';
for ( var i=0;i<data.length;i++ ) {
htmlText += '<div class="div-conatiner">';
htmlText += '<input type="checkbox">' + data[i].ZipCode;
htmlText += '<div>';
}
$(".main-div").append(htmlText);
}
});
});
Model:
public static function counties_zip($countiesList)
{
$county= json_decode($countiesList, true);
$zipCodes= Zip::select('ZIPCode')
->distinct()
->whereIn('CountyName', $county)
->orderBy('ZIPCode', 'asc')
->get();
return $zipCodes;
}

Html table row not appending to specified table

I am trying to add the json string to an html table. The object data is correct but it is not appending to the table. What am I doing wrong with my jquery append statement?
function GetSongs(id) {
$.ajax(
{
type: "Get",
url: "#Url.Action("GetSongs", "Game")",
data: { playlistId : id },
success: function (data) {
json = data;
obj = JSON.parse(json);
for (var i = 0; i < data.length; i++) {
$('#song-table').append('<tr>'+ htmlEncode(obj[i].SongURL) +'</tr>');
}
}
});
}
HTML Table:
<div id="player-playlist">
<table id="song-table" style="width:420px">
<tr>
<th>Song</th>
</tr>
<tr>
<td>http://www.youtube.com/v/CFF0mV24WCY</td>
</tr>
</table>
</div>
First try to debug the output what data you getting on ,is it a JSON string you returning from server side, also try to append td inside tr, and for htmlEncode write the custom function htmlEncode as shown below
function GetSongs(id) {
$.ajax(
{
type: "Get",
url: "#Url.Action("GetSongs", "Game")",
data: { playlistId : id },
success: function (data) {
console.log(data);
json = data;
obj = $.parseJSON(json);
for (var i = 0; i < data.length; i++) {
$('#song-table').append('<tr><td>'+ htmlEncode(obj[i].SongURL) +'</td></tr>');
}
}
});
}
function htmlEncode (value) {
if (value) {
return jQuery('<div />').text(value).html();
} else {
return '';
}
}
remove htmlEncode() because it is not defined in your js, define it or remove it
for (var i in obj) {
$("#song-table").append("<tr><td>"+ obj[i].SongURL +"</td></tr>");
}
OR
for (var i in obj) {
$("#song-table").append("<tr><td>"+ htmlEncode(obj[i].SongURL) +"</td></tr>");
}
function htmlEncode(string)
{
var pre = document.createElement('pre');
var text = document.createTextNode(string);
pre.appendChild(text);
return pre.innerHTML;
}//end htmlEncode it escapes HTML
You are trying to append it to <tr> rather than <td>. Change it to:
$('#song-table').append('<tr><td>'+ htmlEncode(obj[i].SongURL) +'</td></tr>');

JSON Data is not populated into the Dropdownlist

I have the following code in my js file. When i alerted and checked the value of key, its being coming from JSON response, but when i checked my val, its shown as [object object]. So i tried using val.value, the value comes to be undefined.
FYI: I am getting the correct response from my controller through Json, i have checked it, all i want to know is how to populate text value into the dropdown.
$(document).ready(function () {
BindTitle();
});
function BindTitle() {
$.ajax({
"url": "/Admin/GetTitleList/",
"type": "get",
"dataType": "json",
"success": function (data) {
var appenddata;
$.each(data, function (key, val) {
appenddata += "<option value = '" + key + " '>" + val.text + " </option>";
});
$("#TitleId").html(appenddata);
}
});
}
Your way of building dropdown wont work on ie8
try
$.ajax({
url: "/Admin/GetTitleList/",
type: "GET"
success: function (data) {
var items = $('#id of your dropdown');
items.empty();
$.each(data, function (i, drddata) {
items.append($('<option/>', { value: drddata.Value, html: drddata.Text
});
});
},
error: function () {
}
});

Categories

Resources