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.
Related
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.
Ok, this has been driving me crazy for the past couple of days.
I have a form:
echo $this->Form->create(FALSE, array('id' => 'AdminGeneralReport', 'class' => 'ReportForm'));
echo '<div class="row">';
echo $this->Form->input('ReportCenter', array(
'type'=>'select', 'div' => 'form-group',
'options' => $centers,
'label' => 'المركز',
'class' => 'form-control report-center',
'selected' => isset($selections['CenterID'])? $selections['CenterID']['value'] : 'default'
));
echo $this->Form->input('ReportYears', array(
'type'=>'select', 'div' => 'form-group',
'options' => $years,
'label' => 'العام الدراسي',
'class' => 'form-control report-year',
'selected' => isset($selections['YearID'])? $selections['YearID']['value'] : 'default'
));
echo $this->Form->end();
Submit jQuery:
$('.ReportForm').off('submit').on('submit', function(e){
e.preventDefault();
var formID = $(this).attr('id');
var data = JSON.stringify($(this).serializeObject());
var url = base_url + "Reports/" + formID;
var targetSelector = $(this).attr('data-target') || '.results-row';
var $target = $(targetSelector);
// Show app loading
$('#AppLoading').show();
$.ajax({
url : url,
type : 'POST',
ContentType : 'application/json',
data : {'data': data}
}).done(function(response){
try{
response = JSON.parse($response);
if(response.status == 'success'){
$target.html(response.html);
}
else{
$('#AppWell').show('slow').children('p').html(response.msg);
}
}
catch (ex) {
var msg = 'عذراً، حدث خطأ في إنشاء التقرير. برجاء المحاولة لاحقاً';
$('#AppWell').show('slow').children('p').html(msg);
console.log('Exception :: ' + ex.toString());
console.log('Response :: ' + response);
}
}).fail(function(request, status, error){
var msg = 'عذراً، حدث خطأ في إنشاء التقرير. برجاء المحاولة لاحقاً';
$('#AppWell').show('slow').children('p').html(msg);
console.log('XXXXX Ajax Failure :: ' + error);
}).always(function(){
// Hide app loading
$('#AppLoading').hide();
});
});
Question/Need: I want to load another view and append it after this form using json or whatever the way it's possible.
This is part of the view I want to load:
<?php if(isset($selections['Filtered']) && $selections['Filtered'] == TRUE ){
echo '<div class="row">';
$Report = '';
if(isset($selections['SexID']) && $selections['SexID']['value'] != 'default'){
$Report .= '<div class="report-info">
<p class="title">الجنس</p>
<p class="value">'.$selections['SexID']['text'].'</p>
</div>';
}
if(isset($selections['GovID']) && $selections['GovID']['value'] != 'default'){
$Report .= '<div class="report-info">
<p class="title">المحافظة</p>
<p class="value">'.$selections['GovID']['text'].'</p>
</div>';
}
echo '</div>';
?>
<div class="cur-report custom-inverse">
<?=$Report;?>
</div>
And this is part of the PHP code:
// This is the function the ajax calls
public function AdminGeneralReport()
{
// Enable automatic view class switching on content types
public $components = array('RequestHandler');
// Disable auto rendering
$this->autoRender = false;
// Create new view to return to ajax request
$view = new View($this, false);
// Define selections array
$selections = array();
// Get AJAX data
$postData = $this->request->data;
// Decode post data to JSON object
$data = json_decode($postData);
// Create response object
$response = new stdClass();
$response->status = 'fail'; // Should be changed by success scenario
// ********* Center Condition ********* //
$centerCond = '';
// Check if Center is set
if($data->ReportCenter != 'default'){
$centerID = $data->ReportCenter;
$selections['CenterID']['value'] = $centerID;
$selections['CenterID']['text'] = $centers[$centerID];
$selections['Filtered'] = TRUE;
$centerCond = array('CenterID' => $centerID);
}
// *********************************************** //
// ********* Year Condition ********* //
$yearCond = '';
// Check if Academic Year is set
if($data->ReportYears != 'default'){
$yearID = $data->ReportYears;
$selections['YearID']['value'] = $yearID;
$selections['YearID']['text'] = $years[$yearID];
$selections['Filtered'] = TRUE;
$yearCond = array('YearID' => $yearID);
$allTerms = $this->Term->find('all', array('conditions' => array('YearID' => $yearID),
'fields' => array('ID', 'TermName')));
// Convert results from 3D array to 1D array
for($i = 0; $i < count($allTerms); $i++){
$terms[$allTerms[$i]['Term']['ID']] = $allTerms[$i]['Term']['TermName'];
}
$terms['default'] = 'الكل';
}
// *********************************************** //
if($selections){
$response->status = 'success';
}
else{
$response->msg = 'لا توجد بيانات لهذه الإختيارات';
}
$view->set(compact('results','selections'));
$view->set('_serialize', array('results', 'selections'));
$html = $view->render('Admin/General', FALSE);
$response->html = $html;
echo json_encode($response);
die();
}
NOTE: I have this configured in Config/router.php
/**
* Enable extensions routing for data views
*/
Router::parseExtensions('json');
FINALLY SOLVED!!!
I was confusing my self by trying to make it a data view json/xml... while all i needed to do was formatting the returned view:
The returned view has a lot of "\r\n\'\""...all the escape sequences that fail to be JSON parsed in jQuery code.
and i don't have to include the Router::parseExtensions('json'); as well as the public $components = array('RequestHandler');
So this is the PHP Code:
$results = array(); // Fill it
$selections = array(); // Fill it
...
// Disable auto rendering
$this->autoRender = false;
// Create new view to return to ajax request
$view = new View($this, false);
$view->set(compact('results','selections'));
$view->set('_serialize', array('results', 'selections'));
$html = stripcslashes( stripslashes( $view->render('Admin/General', FALSE) ) );
$response->html = $html;
echo json_encode($response);
die();
NOTE: stripcslashes() removes the "\r\n" escape sequences, while stripslashes will remove "\'\"" escape sequences
The jQuery Code:
$.ajax({
url : url,
type : 'POST',
ContentType : 'application/json',
data : {'data': data}
}).done(function(response){
try{
response = JSON.parse(response);
if(response.status == 'success'){
$target.html(response.html);
}
else{
// ERROR HANDLING
}
}
catch (ex) {
// ERROR HANDLING
console.log('Exception :: ' + ex.toString());
console.log('Response :: ' + response);
}
}).fail(function(request, status, error){
// ERROR HANDLING
console.log('XXXXX Ajax Failure :: ' + error);
}).always(function(){
// Hide loading
});
first post on stackoverflow!
Using a modified version of this script http://www.hongkiat.com/blog/instagram-photo-search/
I've changed it to a user search instead of a tag search.. adding the two api calls one for ID and then the other for Images by Username..
I've seen other examples of Pagination being used.. but not sure how to apply it to my current code.. Fairly new with the instagram API
Feel free to use my code! It's very nice ajax way of retrieving photos per user. I took out the CURL portion for readablility.
I would simply like to call something like 20 photos per page. THankS.
instasearch.php
<?php
header('Content-type: application/json');
define("YOUR_TOKEN", 'TOKEN HERE');
$query = $_POST['q'];
$userid = 'https://api.instagram.com/v1/users/search?count=1&q=' . $query . '&access_token='. YOUR_TOKEN;
$clnum = mt_rand(1,3);
// function get_curl($url) WOULD GO HERE //
// SEARCH FOR ID //
$response = get_curl($userid);
if ($response){
foreach(json_decode($response)->data as $item){
$id = $item->id;
$user[] = array(
"id" => htmlspecialchars($id),
);
}
}
// SEARCH BY ID //
$api ='https://api.instagram.com/v1/users/' . $id . '/media/recent/?' . '&access_token='. YOUR_TOKEN . '&count=33';
$response2 = get_curl($api);
$images = array();
if($response2){
foreach(json_decode($response2)->data as $item){
$src = $item->images->standard_resolution->url;
$thumb = $item->images->thumbnail->url;
$url = $item->link;
$count = $item->likes->count;
$images[] = array(
"src" => htmlspecialchars($src),
"thumb" => htmlspecialchars($thumb),
"url" => htmlspecialchars($url),
"count" => htmlspecialchars($count)
);
}
}
print_r(str_replace('\\/', '/', json_encode($images)));
//if($likes)
//print_r(json_encode($likes));
//
die();
?>
ajax.js
$(document).ready(function(){
var sfield = $("#s");
var container = $("#photos");
var timer;
function instaSearch() {
$(sfield).addClass("loading");
$(container).empty();
var q = $(sfield).val();
$.ajax({
type: 'POST',
url: 'http://192.168.0.3/igpanel/image-select/instasearch.php',
data: "q="+q,
success: function(data){
$(sfield).removeClass("loading");
$.each(data, function(i, item) {
var ncode = '<span class="p"><span id="likes"><i style="color:#E74C3C" class="fa fa-heart"></i> '+data[i].count+' likes</span><!----><img id="'+data[i].url+'" src="'+data[i].thumb+'"></span>';
$(container).append(ncode);
});
},
error: function(xhr, type, exception) {
$(sfield).removeClass("loading");
$(container).html("Error: " + type);
}
});
}
HTML
<section id="sform">
<input type="text" id="s" name="s" class="form-control" placeholder="Enter Username..." autocomplete="off">
</section>
<div id="image_container">
<section id="photos"></section>
</div>
EDIT: I've managed to address the issues above, but the max_id keeps getting returned as the same for every load, so the same 20 photos keep loading.
I'm trying to pull in Instagram photos from a hashtag, and then using an ajax feed to call the next set of photos when you scroll to the bottom of the page. Problem is, my ajax script is picking up a random value from somewhere and placing it at the end of my GET url, which renders the URL useless.
I've gone over all my code all day and can't find where it's wrong.
index.php
jQuery(document).ready(function(){
$('#imore').bind('click', function(){
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'),
$c = $('div#instphotos'),
$newItems = '';
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
tag: tag,
max_id: maxid
},
dataType: 'json',
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
var $newItems = $('<div class="mblock"><span class="number">1</span><div class=""><a href="'+data.images[i].src+'?loadtype=iframe" class="imagebox fancybox.iframe" ititle="<div class="posttitle">#</div><div style="float:right;margin-right:15px;"></div><div class="clear"></div>"><img src="'+data.images[i].thumb+'"></div>').css('opacity', 0);
$c.isotope( 'insert', $newItems ).fadeTo('fast', 1);
});
$('#imore').data('maxid', data.next_id);
}
});
});
});
<?php
/** Instagram PHP API */
require_once 'instagram.class.php';
// Initialize class with client_id
// Register at http://instagram.com/developer/ and replace client_id with your own
$instagram = new Instagram('19a4efd22cc1442d97057bd1083e3385');
// Get latest photos according to geolocation for Växjö
// $geo = $instagram->searchMedia(56.8770413, 14.8092744);
$tag = 'subarulove';
// Get recently tagged media
//$media = $instagram->getTagMedia($tag);
$media = $instagram->getTagMedia('breakfast',$auth=false,array('max_tag_id'=>$maxID));
// Display first results in a <ul>
echo '<div id="instphotos">';
$i = 1;
foreach ($media->data as $data) {
echo ' <div class="photo mblock"><span class="number">'.$i.'</span><div class=""><a href="'.$data->images->standard_resolution->url.'?loadtype=iframe" class="imagebox fancybox.iframe" ititle="<div class="posttitle">#'.$data->user->username.'</div><div style="float:right;margin-right:15px;"></div><div class="clear"></div>">'."\n";
echo ' <span class="roll"></span>'."\n";
echo ' <img src="'.$data->images->low_resolution->url.'"></a></div></div>'."\n";
$i++;
}
echo '</div>';
echo '<div id="imore" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'">Load more ...</div>';
?>
ajax.php
require_once 'instagram.class.php';
// Initialize class for public requests
$instagram = new Instagram('19a4efd22cc1442d97057bd1083e3385');
// Receive AJAX request and create call object
$tag = !empty($_GET['tag']) ? $_GET['tag']: null;
$maxID = !empty($_GET['maxid']) ? $_GET['maxid']: null;
$clientID = $instagram->getApiKey();
$call = new stdClass;
$call->pagination->next_max_id = $maxID;
$call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";
// Receive new data
$media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));
// Collect everything for json output
$images = array();
if($media){
foreach ($media->data as $data) {
$src = $data->images->standard_resolution->url;
$thumb = $data->images->low_resolution->url;
$url = $data->link;
$images = array();
foreach ($media->data as $data) {
$images[] = array(
$data->images->standard_resolution->url,
$data->images->low_resolution->url,
$data->link,
$data->likes->count
);
}
}
echo json_encode(array(
'next_id' => $media->pagination->next_max_id,
'images' => $images
));
}
?>
And in the console whenever it runs the ajax request it returns:
GET http://url.com/ajax.php?tag=breakfast&max_id=1400131855765479&_=1400114008166 500 (Internal Server Error)
The bold part is the random value that is getting inserted into the URL.
To add pagination, you will need to call the pagination method and then the subsequent requests use the next_id, also fixed the issue with the Strict Standards: Creating default object from empty value... error
A Cleaned up Example
<?php
require_once 'instagram.class.php';
// Initialize class for public requests
$instagram = new Instagram('19a4efd22cc1442d97057bd1083e3385');
// Receive AJAX request and create call object
$tag = !empty($_GET['tag']) ? $_GET['tag'] : 'subarulove';
$maxID = !empty($_GET['next_id']) ? $_GET['next_id'] : 0;
$clientID = $instagram->getApiKey();
$call = new stdClass;
$call->pagination = new stdClass();
$call->pagination->next_max_id = $maxID;
$call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";
// Receive new data
$media = $instagram->pagination($call, 8); //max to load
// Collect everything for json output
$images = array();
foreach ($media->data as $data) {
$images[] = array(
'url' => $data->images->standard_resolution->url,
'thumb' => $data->images->low_resolution->url,
'url' => $data->link,
'likes' => $data->likes->count
);
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
header('Content-Type: application/json');
exit(json_encode(array(
'next_id' => $media->pagination->next_max_id,
'images' => $images
)));
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Instagram pagination example using jQuery AJAX</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$('#imore').bind('click', function(){
var request = $.ajax({
url: "./index.php",
type: "GET",
data: { tag: $(this).data('tag'), next_id: $(this).data('next_id') },
dataType: "json"
});
request.done(function( data ) {
$.each(data.images, function(i, src) {
$('<img src="'+data.images[i].thumb+'">').appendTo("div#instphotos");
});
$('#imore').data('next_id', data.next_id);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
</head>
<body>
<div id="instphotos">
<?php
foreach ($images as $image){
echo '<img src="'.$image['thumb'].'">';
}
?>
</div>
<div id="imore" data-next_id="<?php echo $media->pagination->next_max_id; ?>" data-tag="subarulove">
Load more ...
</div>
</body>
</html>
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
);
});
}