I am trying to display json_encode data from my back end controller to view using together with AJAX. The AJAX runs successfully and received the response that I needed. However, i am unable to display out on my HTML.
I have double-checked that there is certainly a response coming from the back end. Please do help me.
AJAX jQuery
$.ajax({
type: 'post',
url: 'index.php/Status/facility',
dataType: "json",
data: {id:id},
success: function (response) {
var len = response.length;
console.log(len);
for(var i=0; i<len; i++){
var id = response[i].facility_id;
var username = response[i].name;
var tr_str = "<li class='pointer' id='" + (i+1) + "' onclick='changeClass(this.id)'><a>" + name +"</a></li>";
$("#tabAjax").append(tr_str);
}
$('#exampleModalCenter').modal('show');
}
});
HTML
<ul class="nav nav-pills" id="tabAjax"></ul>
Controller
public function facility(){
echo json_encode($data);
//$this->load->view('templates/student/footer');
}
Response
{"facility_list":[{"facility_id":"1","name":"Table 1","facility_category":"1"}]}
I believe you need to access the data within facility_list so to do so firstly get a reference to that level of the response data and then iterate through it's child objects
var json=response.facility_list;
for( var n in json ){
var obj=json[n];
var id=obj.facility_id;
var name=obj.name;
var cat=obj.facility_category;
var tr_str = "<li class='pointer' data-category='"+cat+"' id='" + (n+1) + "' onclick='changeClass(this.id)'><a>" + name +"</a></li>";
$("#tabAjax").append( tr_str );
}
The best way to implement this handle it at backend. You can prepared html at backend and send prepared html in response(in any key of array) and append according that. That will be more easy to handle response and no need to reload page every time.
$response = array(array('facility_id' => 1, 'facility_category' => 2, 'name' => 'abc'));
$returnResponse = array('status' => 'false', 'data' => '');
$str = '';
foreach ($response as $key => $resp) {
$str .= '<li class="pointer" data-category="' . $resp['facility_category'] . '" id="' . ($key+1) . '" onclick="changeClass(this.id)"><a> ' . $resp['name'] . ' </a></li>';
}
$returnResponse['status'] = true;
$returnResponse['data'] = $str;
Now in js file you can use:-
var html = response.data;
and append above html where you want.
Related
I want to add a link inside AJAX and needs a html.tpl[i]['nip'] in a tag because I want to display another view that required data with the chosen nip.
This is for PHP language in framework CodeIgniter and getting data from CURL. I have tried different ways to solve it but still, display wrong when I add link function, the AJAX is not working (not display the data).
I expect the output is when the link of detail is click the will display the view of data required with the nip. I expect the output is the table working properly and can choosing the link and can display the view that the data is required with the nip.
What's going wrong?
+"<td><a href='<?php echo site_url('admin/detail/');?>' >detail</a></td>"
document.addEventListener("DOMContentLoaded", () => {
$.ajax({
url: "<?php echo site_url('Admin/piljur');?>",
dataType: "json",
type: "POST",
cache: false,
success: function(html) {
var data = "";
for (var i = 0; i < html.tpl.length; i++) {
data += "<tr><td>" + (i + 1) + "</td>" + "<td>" + html.tpl[i]['nip'] + "</td>" + "<td>" + "<td><a href='<?php echo site_url('admin/detail/'//i want to adding the value (html.tpl[i]['nip']);?>' >detail</a></td>" + "</tr>";
}
$("#datatabel").append(data);
}
})
You could separate the detail url into a variable to be used later after the ajax call success, like this :
document.addEventListener("DOMContentLoaded", () => {
let detail_url = '<?php echo site_url('admin/detail/'); ?>';
$.ajax({
url: "<?php echo site_url('Admin/piljur');?>",
dataType: "json",
type: "POST",
cache: false,
success: function(html) {
var data = "";
for (var i = 0; i < html.tpl.length; i++) {
data += "<tr><td>" + (i + 1) + "</td>" +
"<td>" + html.tpl[i]['nip'] + "</td>" +
"<td><a href='" + detail_url + html.tpl[i]['nip'] + "' >detail</a></td></tr>";
}
$("#datatabel").append(data);
}
});
}
I wrote a php script which accept POST request from ajax and give the response back. All working fine. But the receiving string split letter by letter I can't understand what is the reason.
Here is my AJAX code,
$("#btn").click(function(){
console.log($("#search_bar").val());
var dataV;
var htmlText = '';
var containerbootsrap = '';
var filename = '';
var index_no;
$.ajax({
type: "POST",
crossDomain: true,
url: "http://localhost:8090/ontology/setText",
data: $("#search_bar").val(),
contentType: 'text/plain',
// dataType: "json",
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
// htmlText += '<div class="div-conatiner">';
// htmlText += '<p class="p-name"> Name: ' + data[item] + '</p>';
// htmlText += '<img class="imageload" src="' + data[item] + '" />';
// htmlText += '</div>';
// filename = data[item].replace(/^.*[\\\/]/, '')
$.ajax({
data: 'index_no=' + index_no,
url: 'retrivedata.php',
method: 'POST', // or GET
dataType: 'json',
success: function(msg) {
console.log(msg);
for(var item in msg){
console.log ("item: " + item);
console.log ("data: " + msg[item]);
}
$('#home').hide();
containerbootsrap += '<div class = "container" id="search_container">';
containerbootsrap += '<div class = "row homepage">';
containerbootsrap += '<div class = "col-md-5 col-md-offset-3">';
containerbootsrap += '<a href="#" class="thumbnail">';
containerbootsrap += '<img class="imageload" src="' + msg + '" />';
containerbootsrap += '<h3 id="video_name"> ' + filename + ' </h3>'
containerbootsrap += '</a>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
$('body').append(containerbootsrap);
}
});
// $.post('retrivedata.php', { num: 5 }, function(result) {
// alert(result);
// });
// $('#home').hide();
}
// $('body').append(containerbootsrap);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( jqXhr );
alert(jqXhr)
}
});
});
php code is below
<?php
$index_no = $_POST["index_no"];
// echo $index_no * 2;
include('dbConnection.php');
$query = mysql_query("SELECT * FROM video_data WHERE index_no = $index_no");
while ($row = mysql_fetch_assoc($query)) {
$imagePath = $row['thumbnail_url'];
$videoPath = $row['video_url'];
// echo $imagePath;
// echo $videoPath;
echo json_encode($imagePath);
}
?>
I need the output as : 'imagepath'
but it is giving the output as split letter by letter.
here is the real output
Output
but i need the output in one line. like /video_frames/bb/frame136.jpg
please help me to figure out where I am going wrong.
Well, in the php code where you're returning the value you need to specify an array not an string. The variable there $imagePath seems to be a string. You can do something like this.
echo json_encode(array('result' => $imagePath));
This will give you your result in the 'result' key. You can parse it and use it.
You need to parse the returned JSON string into an array. One way to do it is by adding data = $.parseJSON(data) in the ajax success callback (highlighted below). I was able to recreate the same thing you're seeing and adding this line fixed it. Hope this helps. parseJSON()
...
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
data = $.parseJSON(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
...
Better way to check the type of value in variable you are getting first like
data = '{"name": "Bhushan"}' //string value
data = {name: "Bhushan"} //object value
//for testing you can use either, this will make it unbreakable for this context
if(typeof(data) == 'string')
{
data = JSON.parse(data)
}
//rest of code
This will give your module good stability otherwise you may get json parse unexpected token o.
I have created an AJAX function and wondered why my JS was giving errors.
$(document).ready(function() {
$('#more').click(function() {
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'),
url = $(this).data('root'),
id = $(this).data('id'),
count = $(this).data('count');
$.ajax({
type: 'GET',
url: '/ajax',
data: {
tag: tag,
max_tag_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('section#images').append('<img src="' + data[src].images.standard_resolution.url + '">');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
I have created a page that takes data from the instagram API and stores the data in an array so when I click more it loads more images into a container div.
Edit:
Below is the code on the php ajax page that encodes the array into json output:
$instagram = new Instagram\Instagram;
$instagram->setAccessToken($_SESSION['instagram_access_token']);
$token = $_SESSION['instagram_access_token'];
//$clientID = $_SESSION['client_id'];
$current_user = $instagram->getCurrentUser();
$tag = $instagram->getTag('folkclothing');
$media = $tag->getMedia(isset($_GET['max_tag_id']) ? array( 'max_tag_id' => $_GET['max_tag_id'] ) : null);
// Collect everything for json output
$images = array();
foreach ($media as $data) {
/* $collection = array($data->images->standard_resolution->url,$data->link,$data->getId(),$data->likes->count); */
/*
$images[] = $data->images->standard_resolution->url;
$images[] = $data->link;
$images[] = $data->getId();
$images[] = $data->likes->count;
*/
/*
$data_url[] = $data->images->standard_resolution->url;
$data_link[] = $data->link;
$data_id[] = $data->getId();
$data_likes[] = $data->likes->count;
$images[] = array($data_url);
*/
$images[] = array($data->images->standard_resolution->url,$data->link,$data->getId(),$data->likes->count);
}
echo json_encode(array(
'next_id' => $media->getNextMaxTagId(),
'images' => $images
));
The above code creates an array and then it gets converted to a json object but I am unsure how to split it into nested arrays for the image url, image id, likes and the image link. Is this possible to get nested arrays?
End of edit
It did work but I want to find specific elements inside this array so I created the AJAX function above.
The error I get is:
Uncaught TypeError: Cannot read property 'images' of undefined
Any help would be great.
try to replace
$.each(data.images, function(i, src) {
$('section#images').append(
'<img src="' + data[src].images.standard_resolution.url + '">'
);
});
with
$.each(data.images, function(i, src) {
$('section#images').append(
'<img src="' + src.standard_resolution.url + '">'
);
});
For the answer to this I ended up building my array up properly and using the json_encode
to get it all listed properly so I could pull the right data out like so.
ajax.php:
foreach ($media as $data) {
$images[] = array(
"data_url"=>$data->images->standard_resolution->url,
"data_link"=>$data->link,
"data_text"=>$data->getCaption(),
"data_id"=>$data->getId(),
"data_likes"=>$data->likes->count
);
}
echo json_encode(array(
'next_id' => $media->getNextMaxTagId(),
'images' => $images
));
This created the correct array of data.
I then corrected the js for it to work.
JS code:
$(".loading").hide();
$(document).ready(function() {
$('#more').click(function() {
var tag = $(this).data('tag'),
maxid = $(this).data('maxid');
$.ajax({
type: 'GET',
url: '/ajax',
data: {
tag: tag,
max_tag_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
var $content = $('<article class="instagram-image"><form class="forms" action="/image" method="post"><a class="fancybox" href="'+ data.images[i].data_link +'"><img alt="' + data.images[i].data_text + '" src="' + data.images[i].data_url + '" alt="' + data.images[i].data_text + '" /></a><button class="ajax instabtn like icon-heart" type="submit" name="action" value="Like"></button><input type="hidden" name="id" value="'+ data.images[i].data_id +'"><p>'+ data.images[i].data_likes +'</p></form></article>');
$('section#images').append($content).fadeIn(1000);
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
I hope this helps people out who need that extra bit of information.
try this
....
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('section#images').append(
'<img src="' + data[i].images.standard_resolution.url + '">'
//----^----here
);
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
Change data access in image tag
from
data[src].images.standard_resolution.url
^^^
to
data[i].images.standard_resolution.url
^
Here you are using Array of data.images, so you should use index of data.images
Try it like,
if(data.images)// check if data.images found, otherwise it will give error
{
$.each(data.images, function(i, src){
$('section#images').append(
'<img src="' + data.images[i].standard_resolution.url + '">'
// use i ----^----here
// or use src.standard_resolution.url directly
);
});
}
I have a Jquery Function that basically retrieves a list of users from the data base and inserts the information into divs. The problem is that im getting double reults, this is my first time retrieving from the database, Ive only ever sent to the database.. Any Help will be Greatly appreciated.
Thanks :)
Heres the Jquery Code:
$(function () {
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var mobile = row[2];
var address = row[3];
var email = row[4];
$.each(rows, function() {
$('#contain').append('<div id="name">' + '<span>' + name + '</span>' + '</div>' + '<div id="id">' + id + '</div>' + '<div id="mobile">' + mobile + '</div>' + '<div id="address">' + address + '</div>' + '<div id="email">' + email + '</div>');
});
}
}
});
});
and the PHP:
$result = mysql_query("SELECT * FROM $tableName");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
I think the problem is here:
$.each(rows, function (){
$('#contain').append('<div id="name">'+'<span>'+name+'</span>'+'</div>'+'<div id="id">'+id+'</div>'+'<div id="mobile">'+mobile+'</div>'+'<div id="address">'+address+'</div>'+'<div id="email">'+email+'</div>');
});
you should do just
$('#contain').append('<div id="name"><span>'+name+'</span></div><div id="id">'+id+'</div><div id="mobile">'+mobile+'</div><div id="address">'+address+'</div><div id="email">'+email+'</div>');
I am trying to populate a selected menu when the page is created but there are no options that show.
$(document).ready(function() {
$.ajax('patientlist.php', function(data){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option value="' + data[i].patient_id + '">' + data[i].patient_firstname + data[i].patient_lastname + '</option>';}
$('#patientselect').append(html);
});
});
my patientlist.php
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname` FROM `patients` WHERE `company_id` = " . $user_data['company_id'] . " ORDER BY `patient_firstname`");
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
echo json_encode( $data );
}
My result from the php page
[{"patient_id":"9","patient_firstname":"Adam","patient_lastname":"Steve"}] etc...
Really appreciate any help, been stuck on this for a week!
So, posting again.
First of all, you should put the echo json_encode( $data ); out of your while loop
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode( $data );
Second, your $ajax syntax isn't correct, change this to $.post and tell the $.post request you are expecting a 'json' response from patientlist.php
$(document).ready(function() {
$.post('patientlist.php', {}, function(data){
/* code */
}, 'json'); // <= set data type json here
});
When retrieving a valid json string, you can iterate over data by using the $.each method
$.each(data, function(index, patient) {
console.log(patient.patient_id); // or use patient['patient_id']
});
At least you will now receive a valid request.
Noticing your HTML, do not use .append if it is not a DOM element, you are just building html elements as a string, so use instead
$('#patientselect').html(html);