Getting a random value in ajax GET url - php

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>

Related

Get multiple image from variable by ajax

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.

ajax send a request in ajax and get the response

Morning! Please i will like to get some data from mySQL(like getting the number of rows of a mySQL table using ajax). Please how can i do it? Here are my 2 pages. The first one send a number to the php page and the second one do a request to the database and send the result to the page in ajax(the first one). The table voisin_par_distance has 3 columns: cel_id, cel_id_1 and cel_id_2 Thanks.
<!DOCTYPE html>
<html>
<body>
<script>
var xhr1 = new XMLHttpRequest();
var i=1;
var j=4;
xhr1.onreadystatechange = function() {
if (xhr1.status == 200 && xhr1.readyState == 4) {
document.getElementById('content').innerHTML = xhr1.responseText;
}
};
xhr1.open('GET', 'test.php?i='+i+'&j='+j, false);
xhr1.send('');
</script>
<?php
// I would line to get for example the number of rows of table voisin_par_distance which is returned by test.php
$m = (int) $_GET['n'];
echo $m;
?>
</body>
</html>
and this is the php page which is in the same directory.
<?php
$dbname='BD';
try {
$bdd = new PDO( 'mysql:host=localhost;dbname=BD', 'root', '' );
}
catch ( PDOException $e ) {
die("Could not connect to the database $dbname :" . $e->getMessage() );
}
$i = (int) $_GET['i'];
$j = (int) $_GET['j'];
//to select the number of rows of my table
$req = $bdd->prepare("SELECT serveur FROM voisin_par_distance WHERE cel_id_1=':cel_id_1' AND cel_id_2=':cel_id_2'");
$req->execute( array(
'cel_id_1' => $i,
'cel_id_2' => $j
) );
$nbre_ligne = count( $req );
?>
<!DOCTYPE html>
<html>
<body>
<script>
var nbre_ligne = <?php echo $nbre_ligne; ?>
var xhr = new XMLHttpRequest();
var a = 2;
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
document.getElementById('content').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'show_map.php?n='+nbre_ligne);
xhr.send('');
</script>
</body>
</html>
Best and Easy way to use ajax:
$.ajax({// on an event
type: "GET",
url: "test.php", #with valid path
data: {col1: "value1", col2: "value2"},
cache: false,
success: function (responce) {
// alert your response to check data
if (responce.length > 0) {
var data = JSON.parse(responce); // Parse JSON
//Your logic here
}
}
});
In Your PHP file, return data in json format. e.g.
echo json_encode(array('col1' => $val, 'col2' => $val2));
exit;
I hope this will help you.

CakePHP - Load view with php variables and return in ajax

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
});

Adding Pagination to Instagram Search API [AJAX + PHP]

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>

Ajax pagination for Instagram API tried to fix bug

I'm trying to fix Ajax pagination for Instagram API
Shown only 20 photos. "Load more" button didn't work.
In console:
Uncaught ReferenceError: maxid is not defined
Here is index.php:
<script>
$(document).ready(function() {
$('#more').click(function() {
var max_id = $(this).data('nextid');
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
max_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('#photos').append('<li><img src="' + src + '"></li>');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
</script>
<?php
require_once 'instagram.class.php';
$instagram = new Instagram(array(
'apiKey' => '*****',
'apiSecret' => '*****',
'apiCallback' => '******'
));
// Receive OAuth code parameter
$code = $_GET['code'];
if (true === isset($code)) {
$data = $instagram->getOAuthToken($code);
$instagram->setAccessToken($data);
$media = $instagram->getUserMedia();
}
?>
<ul id="photos">
<?php foreach( $media->data as $data ): ?>
<li><img src="<?php echo $data->images->thumbnail->url ?>"></li>
<?php endforeach; ?>
<?php echo "<br><button id=\"more\" data-maxid=\"{$media->pagination->next_max_id}\">Load more ...</button>"; ?>
ajax.php:
require_once 'instagram.class.php';
$instagram = new Instagram(array(
'apiKey' => '****',
'apiSecret' => '*****',
'apiCallback' => '*******'
));
// Receive OAuth code parameter
$code = $_GET['code'];
if (true === isset($code)) {
$data = $instagram->getOAuthToken($code);
// Initialize class for public requests
$instagram->setAccessToken($data);
$media = $instagram->getUserMedia();
// Receive AJAX request and create call object
$maxID = $_GET['next_max_id'];
$clientID = $instagram->getApiKey();
$call = new stdClass;
$call->pagination->next_max_id = $maxID;
$call->pagination->next_url = "https://api.instagram.com/v1/users/self/media/recent?client_id={$clientID}&max_id={$maxID}";
// Receive new data
$media = $instagram->pagination($call);
// Collect everything for json output
$images = array();
foreach ($media->data as $data) {
$images[] = $data->images->thumbnail->url;
}
echo json_encode(array(
'next_id' => $media->pagination->next_max_id,
'max_id' => $media->pagination->max_id,
'images' => $images
));
I am using https://github.com/cosenary/Instagram-PHP-API
Thank You!
How can it be clearer than:
Uncaught ReferenceError: maxid is not defined
maxid is not defined in your code. What is defined is max_id in this line:
var max_id = $(this).data('nextid');
It looks like
.data('nextid');
is a careless error as that doesn't exist in your DOM. Unless it's somewhere else and you haven't posted it.
Did you mean to have
.data('maxid');
?
There are just 2 locations with maxid:
Here:
$.ajax({
...
max_id: maxid
},
and here:
// Store new maxid
$('#more').data('maxid', data.next_id);
When you replace these occurences with your defined max_id (thanks to #mathieu) it should be fixed.
In your ajax.php you have a line:
$maxID = $_GET['next_max_id'];
This doesn't correspond to your call above, where you have a max_id. Seems like you mixed some next/max/id. If you look through your code and clean up these ids, it should work.
You need to pass the event argument with the click
and get the data from event.target.
Change the first lines of codes into this:
$('#more').click(function( event ) {
var max_id = $(event.target).data('nextid');

Categories