Create HTML from JSON object - javascript

Here I have sme .ajax function that work well:
$( document ).ready(function() {
$('a#kom').click(function (e) {
var tabela = 'parcele';
$.ajax({
url: "getComments.php",
type: "POST",
async: true,
data: { ajdi:ajdi,tabela:tabela}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
console.log(data);
},
error:function(data) {
console.log(data);
}
});
});
});
and this function produce this JSON:
[{"datum":"2014-05-22","komentar":"Testiranje za komentare da vidimo kako moze da sluzi, dali radidobro, bla bla bla bla bla bla bla bla bla bla bla bla ... ..."}]
Iknow its a basic question but I cant find any good resource... How I can into .ajax function when function is success to create this html:
'<div class="notes">
<h4>Tekst zaglavlje</h4>
<h5>'+datum+'</h5>
<p>'+komentar+'</p>
</div>'
for every object I get from JSON... so like that:
success: function(data) {
// CREATE A HTML FROM JSON DATA FOR EACH JSON OBJECT. HOW?
console.log(data);
},
UPDATE WITH PHP
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
try {
$result = $db->prepare("SELECT * FROM komentari WHERE id_utabeli=:ajdi AND tabela=:tabela");
$result->execute(array(':ajdi' => $_POST['ajdi'], ':tabela' => $_POST['tabela']));
$result = $result->fetchAll();
$temp = array();
foreach($result as $r) {
$temp[] = array('datum' => (string) $r['datum'], 'komentar' => (string) $r['komentar']);
}
$table = $temp;
$jsonTable = json_encode($table);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo $jsonTable;
}
else {
echo 'ERROR 404';
}

You have a wrong dataType that should be:
dataType: "json",
because response is json not a html.
In your success function do this:
success: function(data) {
var htm = '';
$.each(data, function(i, resp){
htm +='<div class="notes">' +
'<h4>Tekst zaglavlje</h4>' +
'<h5>'+resp.datum+'</h5>' +
'<p>'+resp.komentar+'</p>' +
'</div>';
});
$('yourContainer').html(htm);
},
As your response seems to be an array [{},{}....] or multiple javascript objects so to produce such html markup you have to loop in that array with $.each() method and declare one blank var htm=''; before $.each() iteration and concatenate the resulting html out of your json, then place at the position of your container which can hold the produced html.
Find a Demo # Fiddle

Since you're using jquery, you can do this like follows:
$( document ).ready(function() {
$('a#kom').click(function (e) {
var tabela = 'parcele';
$.ajax({
url: "getComments.php",
type: "POST",
async: true,
data: { ajdi: ajdi, tabela: tabela },
dataType: 'json',
success: function(data) {
console.log(data);
$.each(data, function(i, item) {
// create html
var elem = '<div class="notes">
<h4>Tekst zaglavlje</h4>
<h5>' + item.datum + '</h5>
<p>' + item.komentar + '</p>
</div>'
$('body').append(elem); // append the item
});
},
error: function(data) {
console.log(data);
}
});
});
});

Your success function should look like this:
success: function(data) {
notes_div = $("<div/>");
hfour = $("<h4/>").text("Tekst zaglavlje");
hfive = $("<h5/>").text(data.datum);
para = $("<p/>").text(data.komentar);
notes_div.append(hfour).append(hfive).append(para);
$('#komenatri').append();
},
Other answers provided that just build your HTML as a string are not safe. They open you up to XSS (google it ;) ) but we fix that by making elements as JQuery objects and setting their .text() which makes the resultant content HTML safe.
You should also run your data through htmlspecialchars() in PHP before outputing it.
change:
$temp[] = array('datum' => (string) $r['datum'], 'komentar' => (string) $r['komentar']);
To
$temp[] = array('datum' => htmlspecialchars( (string) $r['datum'] ), 'komentar' => htmlspecialchars( (string) $r['komentar']) );
This will prevent users from injecting their own HTML into your pages with their comments.

success: function(data) {
for(var i = 0, ceiling = data.length; i < ceiling; i++) {
document.getElementById("komenatri").innerHTML +=
"<div class=\"notes\"><h4>Tekst zaglavje</hr><h5>" +
data[i].datum +
"</h5><p>" +
data[i].komentar +
"</p></div>";
}
}

Related

submit form to check something with ajax and jquery

I am making a form to check a security code. In fact, I am new to ajax and jquery, so I tried what I can, but my code doesn't work. Can anybody help me?
php file :
<?php
include('/includes/db-connect.php');
if( isset($_POST["seccode"]) ){
$result=mysqli_query($con,"SELECT * FROM `certificate_acheived_tbl` WHERE `cert_check_code` = ".$seccode.")";
if( mysql_num_rows($result) == 1) {
echo "<script>alert('s')";
}
}
?>
js file:
$(function() {
$(".btn btn-success").click(function() {
var ID = $(this).attr('id');
$.ajax({
type: "POST",
url: "cert-check-ajax.php",
data: 'certcode='+ ID,
success: function() {
$('#someHiddenDiv').show();
console.log();
}
});
});
});
your code is bad... (sometimes mine too)
One first mistake : data: 'certcode='+ ID, in jQuery
and isset($_POST["seccode"]) in PHP 'certcode' != 'seccode'
so a better code.. ?
jQuery (I allways use JSON, it's more easy)
$(function () {
$(".btn btn-success").click(function() {
var
Call_Args = {
certcode: $(this).attr('id')
};
$.ajax({
url: 'cert-check-ajax.php',
type: 'POST',
data: Call_Args,
cache: false,
dataType: 'json',
success: function (data) {
console.log( data.acceptCod ); // or data['acceptCod'] if you want
$('#someHiddenDiv').show();
// ...
}
}); //$.ajax
}); // btn btn-success").click
});
PHP (with utf8 insurance, and good header / JSON encode response )
<?php
mb_internal_encoding("UTF-8");
include('/includes/db-connect.php');
$T_Repons['acceptCod'] = "bad";
if (isSet($_POST['certcode'])) {
$sql = "SELECT * FROM `certificate_acheived_tbl` ";
$sql .= "WHERE `cert_check_code` = ".$_POST['certcode'].")";
$result = mysqli_query($con, $sql);
$T_Repons['acceptCod'] = (mysql_num_rows($result) == 1) ? "ok" : "bad";
}
header('Content-type: application/json');
echo json_encode($T_Repons);
exit(0);
?>
you can use it
$(function() {
$(".btn btn-success").click(function() {
var ID = $(this).attr('id');
$.ajax({
type: "POST",
url: "cert-check-ajax.php",
data: {'seccode': ID}
}).done(function(data) {
$('#someHiddenDiv').show();
console.log(data);
});
});
});

show image from ajax response

I am getting response in jquery as below. I want to show images from the db through the ajax request.
My controller code :
public function images($id='')
{
$this->load->model('gallery');
$data = this->gallery_model->getimages($this->input->post('id'));
echo json_encode($data);
}
My ajax :
function imageslide(folderid){
$.ajax({
url: "<?php echo site_url() ?>/welcome/images",
type: "POST",
dataType: "json",
data: {id: folderid},
success: function(result) {
if(result){
resultObj = eval (result);
alert(JSON.stringify(resultObj));
}else{
alert("error");
}
}
});
The result which i received in the Network tab is
[{"id":"153","file_name":"DSC00081.JPG","created":"2017-05-23 09:36:32","modified":"2017-05-23 09:36:32","status":null,"folder_id":"50"},{"id":"154","file_name":"DSC00082.JPG","created":"2017-05-23 09:36:32","modified":"2017-05-23 09:36:32","status":null,"folder_id":"50"},{"id":"155","file_name":"DSC00083.JPG","created":"2017-05-23 09:36:32","modified":"2017-05-23 09:36:32","status":null,"folder_id":"50"}]
I do not know how to show image in the browser in the <img> tag. As you can see, I am getting jpeg in the alert window. Kindly help me through.. Thanks in Advance!
You can append the imagen using jQuery, for example with the first index of array:
$('#container').append('<img src="' + result[0].file_name + '" />');
If you want to add each image, you can use forEach loop.
result.forEach(function (image) {
$('#container').append('<img src="' + image.file_name + '" />');
});
Copying from your code
function imageslide(folderid){
$.ajax({
url: "<?php echo site_url() ?>/welcome/images",
type: "POST",
dataType: "json",
data: {id: folderid},
success: function(result) {
if(result){
resultObj = eval (result);
var HTMLbuilder = "";
for(var i = 0; i < resultObj.length; i++){
var imgHtml = "<img src='path-toImage/" + resultObj[i].file_name + "'>";
HTMLbuilder = HTMLbuilder + imgHtml;
}
$("#imgContainer").html(HTMLbuilder);
}else{
alert("error");
}
}
});
Don't forget to have the div with the appropriate ID on the HTML
<div id="imgContainer"></div>
On pure js:
Plunker
result.forEach(img => {
let element = document.createElement('img');
element.width = '100'
element.src = img.path;
parentEl.appendChild(element)
})
You have received JSON object in result. Just loop through it, using
$.each(result, function(key, value){
$('#container').append('<img src=" +value.file_name + " />');
})

Post to php file, and retrieve data with javascript

So i have a php file, that prints data from a table encoded on JSON format.
This is the php file:
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo "success";
else
echo "error";
}
echo json_encode($data);
?>
This is the javascript script:
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
if (data == "success") {
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
});
} else if (data == "error") {
alert("error");
}
}
});
});
So basically i a have where i have all items from the database select (list_all.php), and then when i click on a single item, the ID of that item is passed on the URL, and i retrieve it on the otherside with javascript. I dont use GET because this is with phonegapp, so i use a .js file called getURI.js.
First, the function gets the ID that was passed. Then it posts to the PHP file, and the PHP file will get the ID, and make the query for that single item on the database. Is successed, i wanted to store all that data on variables. But for some reason, im getting an error on the console saying
POST http://192.168.1.241:3000/proxy/http%3A%2F%2Fpedrofidalgo.pt%2Fbilapoint%2Flistar_sitio_single.php 500 (Internal Server Error)
THe server is responding correctly because others scripts on the app are working.
In PHP
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo json_encode(array('status' => true, 'data' => $data));
else
echo json_encode(array('status' => false, 'data' => $data));
?>
In Jquery
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
data = JSON.parse(data);
if (data['status']) {
$.each(data['data'], function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
} else {
alert("error");
}
}
});
});

How to append the JSON data to HTML in JavaScript?

I get some data using JSON array. I want to append each data in a div. But I don't get what's wrong in that?
controller
function get_performers()
{
$id = $this->input->post('id');
$exam = $this->input->post('exam');
$datas=$this->job->get_top_ten_st_data($id,$exam);
$out['student_details'] = $datas;
echo json_encode($out);
}
script
function get_performers(id,exam)
{
$.ajax({
url:"<? echo base_url();?>class_analysis/get_performers",
dataType: 'json',
type: "POST",
data: {id:id,exam:exam},
success:function(result) {
// alert("haii");
console.log(result);
result = JSON.parse(result);
var tab= "<div class='col-xs-2 blk-ht'> <span class='hd'>Names</span> </div>";
for(var i=0;i<result.student_details.length;i++)
{
tab=tab+"<div class='col-ds-1'><span class='subjNames'>" + result.student_details[i]["subject_name"]+ "</span></div> ";
}
jQuery("#subjectNames").append(tab);
}
});
}
Any problem in this?
Try html not append
jQuery("#subjectNames").html(tab);
Also if jQuery("#subjectNames") equal with null in your console this mean that you don't have element with id="subjectNames" in html not id="#subjectNames" or other. May be you use classes then try $(".subjectNames") with . not #
The Loop should work... Seems to be another problem with your result.
var tab= "<div class='col-xs-2 blk-ht'><span class='hd'>Names</span> </div>";
for(var i=0;i<20;i++)
{
tab=tab+"<div class='col-ds-1'><span class='subjNames'>" + "test: " + i + "</span></div> ";
}
jQuery("#subjectNames").append(tab);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="subjectNames"><div>
dataType: 'json' in $.ajax options - automaticaly parse your json
and USE JQUERY )))
IN SUCCES AJAX FUNCTION
$.each( result.student_details, function( key, value ) {
alert( key + ": " + value );
});
<?php
function get_performers()
{
$id = $this->input->post('id');
$exam = $this->input->post('exam');
$datas=$this->job->get_top_ten_st_data($id,$exam);
$out['student_details'] = $datas;
echo json_encode($out);
}
?>
<script>
$.ajax({
url:"<? echo base_url();?>class_analysis/get_performers",
dataType: 'json',
type: "POST",
data: {id:id,exam:exam},
success:function(result) {
$.each(response.student_details, function(key,value){
appendHtml(key,value);
});
}
});
function appendHtml(key,value)
{
var tab= "<div class='col-xs-2 blk-ht'> <span class='hd'>Names</span> </div>";
tab = tab+"<div class='col-ds-1'><span class='subjNames'>" +value+ "</span></div> ";
jQuery("#subjectNames").append(tab);
}
</script>

How to access array elements in ajax response received from PHP?

jQuery code of ajax function is as follows:
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
data: {
'request_type':'ajax',
'op':'get_city_state',
'zip_code' : el.val()
},
success: function(result, success) { alert(result.join('\n'));
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
});
}
});
});
PHP code snippet is as follows :
case "get_city_state":
// to get the city and state on zip code.
$ret = $objUserLogin->GetCityState($request);
if(!$ret) {
$error_msg = $objUserLogin->GetAllErrors();
list($data) = prepare_response($request);
$smarty->assign('data', $data);
} else {
$data = $objUserLogin->GetResponse();
echo $data;
}
die;
break;
In PHP code the $data contains data in following manner :
<pre>Array
(
[id] => 23212
[zip_code] => 28445
[place_name] => Holly Ridge
[state_code] => NC
[created_at] => 1410875971
[updated_at] => 1410875971
)
</pre>
From the above data(i.e. response which will be available in variable result in ajax response) I want to access only two fields place_name and state_code.
I tried printing the content of result variable using alert(result) in console but I get the word Array
How to achieve this is my doubt?
Thanks in advance.
You should encode your result to json. So instead of the statement echo $data
use
echo json_encode($data);
it will return your result in json format. like
{"id":23212,"place_name":"Holly Ridge"...}
and in your javascript your can access your data

Categories

Resources