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>
Related
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 + " />');
})
I'm new with JSON. I have a select box and JavaScript change() trigger on it. I execute MySQL query with Ajax based on selected value. Query results will be printed as a new row in HTML table.
But the new row isn't appending. What am I doing wrong?
HTML
<select id="orderAddProduct">
<option value=""></option>
<option value="0001">Product 1</option>
<option value="0002">Product 2</option>
</select>
<table id="orderTable">
<tr><th>ID</th><th>Name</th></tr>
</table>
JavaScript
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "POST",
url: "orderAddProduct.php",
data: {option: selectedValue},
datatype: "json",
success: function (data) {
alert("OK");
orderAddRow(data);
},
error: function () {
alert("ERROR");
}
});
});
function orderAddRow($item) {
$.each($item,function(index,value) {
var row = '<tr><td>'+value.id+'</td>'
+'<td>'+value.name+'</td></tr>';
$('#orderTable').append(row);
)};
}
PHP
try {
$pdo = new PDO(DB_TYPE . ':host=' . DB_HOST . '; dbname=' . DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
die("ERROR: " . $e->getMessage());
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("SET NAMES utf8");
$productId = $_REQUEST['option'];
$sql = $pdo->prepare("SELECT * FROM products_view WHERE id = ?");
$sql->execute(array($productId));
$row = $sql->fetch(PDO::FETCH_ASSOC);
$json_array = array("ID" => $row['id'], "name" => $row['name']);
echo json_encode($json_array);
Variable names?
function orderAddRow($item) {
^^^^^^----
var row = '<tr><td>'+value.id+'</td>'
^^^^^----
You define a $item parameter, but never use it in the function. Instead there's this mysterious/undefined value.
Ok, the master problem is that I didn't have JSON.parse() function in my code. Below is my finally working code.
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "GET",
url: "orderAddProduct.php",
data: {option : selectedValue},
datatype: "json",
success: function (response) {
response = JSON.parse(response);
if(response === undefined) {
alert("undefined");
} else {
orderAddRow(response);
}
},
error: function () {
alert("ERROR");
}
});
return false;
});
function orderAddRow($data) {
$.each($data,function(index,value) {
var row = '<tr><td>' + value.ID + '</td>'
+ '<td>' + value.name + '</td></tr>';
$('#orderTable').append(row);
});
}
success: function (data) {
alert("OK");
orderAddRow(data);
},
You are missing out the returned value.
below code working fine but I need to append option1 in href,
$(document).ready(function () {
$("#head_drop .dd-option").click(function () {
var option = $('.dd-option-value',this).attr('value');
var option1 = $('.dd-option-text',this).text();
// alert(option1);
$.ajax({
type: 'get',
url: '<?php echo $this->getBaseUrl();?>categories/index/city/',
data: {option: option},
success: function(data) {
$(location).attr('href',"<?php echo $this->getBaseUrl()?>");
}
});
});
});
now its return
http://example.com/
I want like http://example.com/option1
I tried $(location).attr('href',"<?php echo $this->getBaseUrl()?>"option1); but failed to get, Thanks...
If option1 is a variable all you need is to concatenate with a + -
$(location).attr('href',"<?php echo $this->getBaseUrl()?>" + option1)
You have your " at the wrong place, it should read:
$(location).attr('href',"<?php echo $this->getBaseUrl()?>option1");
Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}
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>";
}
}