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
);
});
}
Related
I'am trying to get multiple images from variable have multiple images but i only get one.
the variable is $src.
// the frontend code
foreach ( $chapter['storage'][ $in_use ]['page'] as $page => $link ) {
$host = $chapter['storage'][ $in_use ]['host'];
$src = $host . $link['src'];
}
$this->send_json( 'success', '', $src );
// ajax code
$(function(){
$('.entry-content .entry-content_wrap').ready(function(){
var navigation = $('.single-chapter-select').find('option:selected').data('navigation');
$.ajax({
type: 'GET',
url: manga.ajax_url + '?' + navigation,
dataType: 'json',
success: function(data){
var imag_link = data.data.data;
console.log(imag_link);
$('.entry-content .entry-content_wrap').html('<img style="margin: -6px;width: 89%;pointer-events: none;" class="wp-manga-chapter-img" src="' + imag_link + '">');
},
})
})
})
In your PHP code you need to collect all of the URLs in an array and return it.
$sources = [];
foreach ( $chapter['storage'][ $in_use ]['page'] as $page => $link ) {
$host = $chapter['storage'][ $in_use ]['host'];
$src = $host . $link['src'];
$sources[] = $src;
}
$this->send_json( 'success', '', $sources );
In frontend you should loop over the sources and attach them to your html as you wish.
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.
I tried to create wordpress ajax call that should return images attached to a post but get_attached_media function returns an empty array. I can get any post data but not attached images. Here is what I have done:
in functions.php:
add_action('wp_ajax_getGallery', 'getGallery');
add_action('wp_ajax_nopriv_getGallery', 'getGallery');
function getGallery() {
$pid = $_REQUEST["post_id"];
$n = 1;
$gallery = get_attached_media('image', $pid);// this $gallery returns an empty array
foreach($gallery as $item) {
if ($n > 5) {
$img_object = wp_get_attachment_image_src($item->ID,'gallerythumb');
$img = $img_object[0];
$str .= '<div class="col-sm-2 col-xs-4"><div class="img-holder"><img class="img-responsive" src="' . $img . '" /></div></div>';
$n++;
}
}
echo $str;
die();
}
and in .js:
$(".post-link").click(function(){
var post_id = $(this).attr("rel");
$("#post-container").html("content loading");
$.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: {
action: 'getGallery',
post_id: post_id
},
success: function(data) {
console.log(data);
$("#post-container").html(data);
},
fail: {
}
});
return false;
});
Does anyone knows why I can't get images here? All code seams fine to me.
Thnx.
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 an ajax script, which I kinda understand, but still need some extra help.
$('.images').click(function(){
var imageId = $(this).attr('id');
alert(imageName);
$.ajax({
type: "get",
url: "imageData.php",
dataType: "json",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
alert(imageId);
$("#images_"+imageId).html(data);
}
});
//$('#images_'+imageId).toggle();
});
I have that code, it goes to this imageData.php file
<?php
if(isset($_GET)){
$images = "";
$path = 'img/';
$imageId = $_GET['getImageId'];
$sql = mysql_query("SELECT * FROM images WHERE iID = '".$imageId."'");
while($row = mysql_fetch_array($sql)){
$images .= $path.$row['images'];
}
$json = json_encode($images);
?>
<img src='<?php echo $json;?>'/>
<?php
}
?>
Why does it output error when I try to echo a string from $images, but it outputs correctly when I do echo $imageId;? I'm trying to output something from mysql, but not trying to output just the id.
Need help please, thank you
You don't need use json_encode here, there is not data that needs to be in JSON format. There is also no reason to loop over the result set, if the query only returns one image.
Try this:
<?php
if(isset($_GET['getImageId'])) {
$path = '';
$imageId = mysql_real_escape_string($_GET['getImageId']); // SQL injection!
$result = mysql_query("SELECT images FROM images WHERE iID = '".$imageId."'");
$row = mysql_fetch_array($result);
if($row) {
$path = 'img/' . $row['images'];
}
}
?>
<?php if($path): ?>
<img src='<?php echo $path;?>'/>
<?php endif; ?>
If the iID is actually an integer, you need to omit the single quotes in the query.
You also have to change the dataType from json to html, as you are returning an image tag (HTML) and not JSON:
$.ajax({
type: "get",
url: "imageData.php",
dataType: "html",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
$("#images_"+imageId).html(data);
}
});
Another option is to return only text (the link) and create the images on the client side:
<?php
if(isset($_GET['getImageId'])) {
$path = '';
$imageId = mysql_real_escape_string($_GET['getImageId']); // SQL injection!
$result = mysql_query("SELECT images FROM images WHERE iID = '".$imageId."'");
$row = mysql_fetch_array($result);
if($row) {
echo 'img/' . $row['images'];
}
}
?>
And in JavaScript:
$.ajax({
type: "get",
url: "imageData.php",
dataType: "text",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
$("#images_"+imageId).html('<img src="' + data + '" />');
}
});
As you may get many images because you use while loop you probably want to do this like so:
in php:
$x = 0;
$another = array();
while($row = mysql_fetch_array($sql)){
$another[$x] = $path.$row['images'];
$x++;
}
echo json_encode($another);
and in jquery (in your success callback):
$.each(data, function(i, v){
// Do the image inserting to the DOM here v is the path to image
$('#somelement').append('<img src="'+v+'"');
});
For outputing an image you must set src attribute of the image tag, if you already have one, or you can create it on the fly. See here how to do that > jQuery document.createElement equivalent?