Instagram async feed - php

Following this post How to get a user's Instagram feed , i use it to display the last image
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/123456789/media/recent/?access_token=123456789.123asdsd.asdadasdas23423423&count=1");
$result = json_decode($result);
foreach ($result->data as $post) {
if(empty($post->caption->text)) {
// Do Nothing
}
else {
// Display img
}
}
How can be loaded asynchronous? Sometimes is takes even 2-3s to load and delays the entire page to be displayed. Tks for you time and help!

EDIT
tks to #steve, i solved it by query instagram api once per hour and save the response to instagram.json
get-social-media.php
function get_instagram($user_id=instagram_user_id,$count=1){
$instaurl = `https://api.instagram.com/v1/users/`.$user_id.`/media/recent/?access_token=instagram_access_token&count=`.$count;
$instacache = `instagram.json`;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL,$instaurl);
$instadata=curl_exec($ch);
curl_close($ch);
if(file_exists($instacache) && filemtime($instacache) > time() - 60*30){
//echo "ok instagram";
} else {
$jsonInstaData = json_decode($instadata,true);
file_put_contents($instacache,json_encode($jsonInstaData));
}
}
echo get_instagram();
and that ajax for frontend social-media-block.phtml (magento & bootstrap)
jQuery(document).ready(function($) {
$("#instagram-img").html("");
$.ajax({
type: "GET",
async: true,
contentType: "application/json; charset=utf-8",
url:"resources/socialmedia-cache/instagram.json",
dataType: "json",
cache: true,
beforeSend: function () {
$("#loading").show();
},
success: function (data) {
console.log(data);
$("#loading").hide();
if (data == "") {
$("#InstaContainer").hide();
} else {
$("#InstaContainer").show();
for (var i = 0; i < data["data"].length; i++) {
var dataForJson = JSON.stringify(data.data[i]);
var date = new Date(parseInt(data.data[i].caption.created_time) * 1000);
$("#instagram-img").append("<a target=`_blank` href=`" + data.data[i].link + "` title=`" + data.data[i].caption.text + "`><img src=`" + data.data[i].images.low_resolution.url + "` class=`img-responsive socialmedia-img`></img></a>");
$("#instagram-img").append("<p align=`left`><script>" + "jQuery(document).ready(function() { jQuery(`a.timeago`).timeago();});" + "</" + "script><a class=`timeago` style=`color:#484848;` title=`" +(date.getMonth()+1)+"/"+date.getDate()+"/"+date.getFullYear()+", "+date.getHours()+":"+date.getMinutes()+ "`>" +(date.getMonth()+1)+"/"+date.getDate()+"/"+date.getFullYear()+", "+date.getHours()+":"+date.getMinutes()+ "</a></p>");
}
}
}
});
});
this also works for facebook
for pinterest, i use http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1&q=https://www.pinterest.com/MyPinterest/feed.rss , a quick solution to convert the rss to json. since i need images larger than 236px, next parsed is 736px. also, the img src needs to be extracted from content
var string = data.responseData.feed.entries[i].content;
var filtered = string.replace('/236x/', '/736x/');
var source = filtered.match(/src\s*=\s*"(.+?)"/);
probably not the best code, but at least is a working solution.

Related

Slow response rate from Curl / Ajax

General Info
Hi guys,
I was deciding to post this or not due to the question but i said hell, why not!
What am i doing?
I have an array of music tracks which is pushed into a ajax request which i then loop through in php and pass each track into a curl request to then go off and pull down coverart for them specific tracks! The coverart of course is in .jpg or .png format of a link, so rihanna.jpg is returned. I then push them into another array which is my end result which is then pushed back to my ajax result (data) and i go from there.
My issue?
When i push in 60 tracks, the response is around 30 seconds which is a long ass wait! I am trying to retrieve information as quick as possible so i can update the end-users GUI without leaving them with a loading bar for periods of time while the data loads.
Now i looked into this and my theory behind why its so slow is either down to the api call is lacking in the response department or the curl is hogging and slowing it all down! I heard of curl_multi and all those but have never used nor do i no were to start! I am not even sure if that will solve this. Can someone please input on this to try ease my mind? Is this speed all i will ever get or is it possible to speed this up? Before i was creating ajax calls within a loop and i thought it was because of that so i did a change to push all the tracks into one array which is then passed into one ajax but it did not speed anything up.. Same response rate to be honest!
My PHP code:
function curlGet($url, $proxy = null)
{
$ch = curl_init($url);
#curl_setopt($curl, CURLOPT_HTTPHEADER, array("Connection: close"));
#curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
#curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
if (isset($proxy)) {
if ($proxy['enable'] === '1') {
$proxy['user'] === '' || #curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy['user'].':'.$proxy['pass']);
#curl_setopt($ch, CURLOPT_PROXY, $proxy['host']);
}
}
#curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 400);
#curl_setopt($ch, CURLOPT_TIMEOUT, 10);
#curl_setopt($ch, CURLOPT_HEADER, 0);
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$trackarray = $_POST['trackarray'];
$returnarray = [];
foreach($trackarray as $i => $track) {
$strippedarray = explode(" - ", $track, 2);
$strippedartist = $strippedarray[0];
$strippedtrack = $strippedarray[1];
$ArtistTrack = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=KEYHERE&artist=".$strippedartist."&track=".$strippedtrack."&format=json";
$ArtistL = "http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&api_key=KEYHERE&artist=".$strippedartist."&format=json";
$AToutput = json_decode(curlGet($ArtistTrack, $proxy), true);
$Aoutput = json_decode(curlGet($ArtistL, $proxy), true);
if($AToutput == "" || $AToutput['track']['album']['image']['3']['#text'] == "") //Artist-Track failed, lets try just arist!
{
if($Aoutput == "" || $Aoutput['artist']['image']['3']['#text'] == "") //If Artist Failed, serve default-coverart.png
{
array_push($returnarray, "../location/cover-default.png");
}
else //Artist success, serve artist.png
{
array_push($returnarray, $Aoutput['artist']['image']['3']['#text']);
}
}
else //Artist-Track Success, Serve artist-track.png
{
array_push($returnarray, $AToutput['track']['album']['image']['3']['#text']);
}
}
echo json_encode($returnarray);
My Javascript:
$('#spinner-db').removeClass('hide');
var windowwidth = $(window).width();
var blockwidth = 350;
var rowcount = parseInt(windowwidth / blockwidth);
var buffersize = parseInt(rowcount * 4);
var endindex = parseInt(buffersize * 2);
var loadimagearray = localcontent.slice(0,endindex);
var currentdatabase = "#database-entries";
$.ajax({
url : '/location/script.php?cmd=commandhere',
cache: false,
type: 'POST',
data: {trackarray: loadimagearray}
}).done(function(data)
{
$.each( loadimagearray, function( i, l ) //Loop through each item in array
{
if($(currentdatabase+' li[track-info="' + l + '"] img').attr('src') == "../assets/img/cover-default.png")
{
$(currentdatabase+' li[track-info="' + l + '"] img').attr('src',JSON.parse(data)[i]);
if(i == (loadimagearray.length - 1)) //Hide Loader
{
$('#spinner-db').addClass('hide');
}
}
});
});

post json to a codeigniter method in controller, formerly post was made in jquery

I need to post a json to a method in codeigniter 2.2.0, that post was made in a view with a jquery-ajax, like this:
function envia_mail_ajax(numero, form_data, ruta){
var iddiv="#mail_"+numero;
window.setTimeout(
function(){
$.ajax({
url: "<?php site_url('emailmasivo'); ?>/" +ruta+ "/" +numero,
cache: false,
type: 'POST',
data: form_data,
dataType: "json",
success: function(html){
$( iddiv ).append(html.mensaje+"\n"+'<br />');
}
});
}, 600);
}
and it was used like this (within a loop over i):
envia_mail_ajax(i,
{para:correos_e[i],id_masivos:id_masivos_e[i],id_mat_referencia:id_mat_referencia_e[i],
id_tipouser:id_tipouser_e[i],nombre:nombres_e[i], sexo:sexos_e[i], matricula:matriculas_e[i], passa:passa_e[i],id_cuenta:cuenta_id},
"<?php echo $r_ajax; ?>");
now, I´m writing all that in such a way that no view will be needed, in order to make it possible to run it from the terminal´s commands line, essentially, this is telling me to POST to the controller´s method "<?php echo site_url('emailmasivo'); ?>/" +ruta+ "/" +numero the data in form_data; to do this I wrote a method based in a lecture I found here POST json to PHP, my method is:
function procesaInfo($Arreglo, $numero){
$url = $Arreglo['r_ajax'];
$ch = curl_init(echo site_url('emailmasivo') . $url . "/" . $numero);
$jsonData = array(
'para' => $Arreglo['lista_mails']['correos_e'][$numero],
'id_masivos' => $Arreglo['lista_mails']['id_masivos_e'][$numero],
'id_mat_referencia' => $Arreglo['lista_mails']['id_mat_referencia_e'][$numero],
'id_tipouser' => $Arreglo['lista_mails']['id_tipouser_e'][$numero],
'nombre' => $Arreglo['lista_mails']['nombres_e'][$numero],
'sexo' => $Arreglo['lista_mails']['sexos_e'][$numero],
'matricula' => $Arreglo['lista_mails']['matriculas_e'][$numero],
'matriculas_e' => $Arreglo['lista_mails']['passa_e'][$numero],
//'id_cuenta' => $Arreglo['lista_mails']['cuenta_id'][$numero]
'id_cuenta' => $Arreglo['id_cuenta']
);
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
}
the problem is that when I try to use that method like this:
function proceso_envia($nuevoArreglo){
$hola = "hola";
//echo $cuenta_id = $nuevoArreglo['id_cuenta'].PHP_EOL;
//print_r($nuevoArreglo['lista_mails']['correos_e']);
if(count($nuevoArreglo['lista_mails']['correos_e']) != 0){
$j = 0;
for($i = $nuevoArreglo['ini'] ; $i < count($nuevoArreglo['lista_mails']['correos_e']) ; $i++){
if($nuevoArreglo['lista_mails']['correos_e'][$i] != NULL){
$j = $j+1;
sleep(1);
echo "si llega!".PHP_EOL;
$this->procesaInfo($nuevoArreglo, $i);
}
}
}
}
it seems that no data are being POST to my method, and worst, not even the method is being reached, how do I know? well, I used an echo "I´m here!"; at the very beginning of the proceso_envia function, and nothing was displayed... am I doing it right? how do I post correctly data to a CI method in a controller? thanx i.a. for your help!

I need to pullback data from a jquery ajax post and break the array out to seperate outputs

I need to get the array and instead of just pushing the data into an html div - get back the php variable.
My $.ajax post ----
<script type="text/javascript">
$(function() {
$("#login").click(function() {
var theName = $.trim($("#username").val());
if(theName.length > 0)
{
$.ajax({
type: "POST",
url: "callajaxdemo.php",
data: ({name: theName}),
cache: false,
dataType: "text",
success: onSuccess
});
}
});
$("#resultLog").ajaxError(function(event, request, settings, exception) {
$("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
});
function onSuccess(data)
{
$("#resultLog").html("Result: " + data);
//$.mobile.changePage('stats.html', { transition: 'slideup'}, true, true);
}
});
</script>'
My PHP file is -----
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$host = 'https://api.qpme.com/api/accounts/me';
$process = curl_init($host);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($process);
$content = json_decode($return);
/*
echo "<pre>";
print_r($content);
echo "</pre>";
*/
print $content->email . "<br>";
print "<h3>" . "Welcome" . ' ' . $content->firstName . ' ' . $content->lastName . '!' . "<h3>";
?>'
The goal would be to get back the array and then post certain parts of it to different jquery mobile pages.
You can send JSON data back to AJAX request.
Change your arrays to JSON like this:
echo json_encode($yourData);
To read this, you have to setup your script to accept JSON data
$.ajax({
type: "POST",
url: "callajaxdemo.php",
data: ({name: theName}),
cache: false,
dataType: "json", // <--- Here
success: onSuccess
});
Then you can access the properties as JavaScript Object.
function onSuccess(data)
{
// access using data.item1
// or data.item2 how you prepare your array
}

AJAX/PHP Not Working After Web Host upgrade

My web hosting company recently upgraded to Apache 2.2.22 and PHP 5.3.13 and since then a piece of script will not work correctly. The webpage is a radio streamer and now the part that updates the track info from a text file does not display at all. The streamer is working fine and so are other third-party widgets.
Here is part of the script to display the album cover:
updateNowPlayingInfo = function() {
var d = new Date();
$.ajax( '/php_proxy_simple.php?url=playingnow.txt&_=' + d.getTime(), {
complete: function( jqXHR, textStatus) { console.log( 'RMX Player XHR completed: ' +textStatus ); },
error: function( jqXHR, textStatus, errorThrown) { console.log( 'RMX Player XHR error:' + textStatus + ':' + errorThrown ); },
xhr: (window.ActiveXObject) ?
function() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
} :
function() {
return new window.XMLHttpRequest();
},
cache: true,
type: 'GET',
crossDomain: true,
dataType: 'text',
global: false, // #note was using false
ifModified: true,
success: function( data, textStatus, jqXHR ) {
//alert( playingData );
playingData = data.split("\n");
if ( playingData[2] && ! playingData[2].match( /no-image-no-ciu/ ) ) {
//playingData[2] = playingData[2].replace( 'SS110', 'AA280' ); // swap small image for medium
//console.log( playingData[2] );
playingData[2] = playingData[2].replace( '_SL160_', '_SX200_' ); // swap small image for large
$( "#nowplaying_album_cover img" ).attr( "src" , playingData[2] );
$( "#nowplaying_album_cover").show();
}
else $( "#nowplaying_album_cover").attr("src" , playingData[2] );
$( "#nowplaying_album_cover").show();
},
failure: function() { alert('failed to get play data') ; }
} );
And the php code:
<?php
// PHP Proxy example for Yahoo! Web services.
// Responds to both HTTP GET and POST requests
// Allowed hostname
define ('HOSTNAME', 'http://www.mysite.co/');
// Get the REST call path from the AJAX application
// Is it a POST or a GET?
ini_set( 'error_reporting', 0);
$path = ($_POST['url']) ? $_POST['url'] : $_GET['url'];
$url = HOSTNAME.$path.'?timestamp=' . time();
// Open the Curl session
$session = curl_init($url);
// If it's a POST, put the POST data in the body
if ($_POST['url']) {
$postvars = '';
while ($element = current($_POST)) {
$postvars .= urlencode(key($_POST)).'='.urlencode($element).'&';
next($_POST);
}
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $postvars);
}
// Don't return HTTP headers. Do return the contents of the call
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Make the call
$response = curl_exec($session);
// possibly include expires header to bust aggresive caching -expires=>’+1s’
header('Content-Type: text/html;charset=utf-8');
echo $response;
curl_close($session);
?>
I grabbed this from the raw log files:
"GET /playingnow.txt HTTP/1.1" 304
Not sure if that is relevant. Any help would be appreciated. Thanks
Fixed it, the file permission for the PHP file needed to be at 0644. Thanks.

Using jQuery to parse XML returned from PHP script (imgur.com API)

Here's my jQuery:
var docname = $('#doc').val();
function parseXml(xml)
{
$(xml).find("rsp").each(function()
{
alert("success");
});
}
$('#submit').click(function() {
$.ajax({
type: "GET",
url: "img_upload.php",
data: "doc=" + docname,
dataType: "xml",
success: parseXml
});
return false;
});
Note that #doc is the id of a form text input box and #submit is the submit button's id. If successful, I'd like a simple "success" javascript popup to appear.
Here's img_upload.php with my API key omitted:
<?php
$filename = $_GET["doc"];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
// $data is file data
$pvars = array('image' => base64_encode($data), 'key' => <MY API KEY>);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://imgur.com/api/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
curl_close ($curl);
?>
When directly accessed with a GET argument for "doc", img_upload.php file returns the following XML format:
<?xml version="1.0" encoding="utf-8"?>
<rsp stat="ok">
<image_hash>cxmHM</image_hash>
<delete_hash>NNy6VNpiAA</delete_hash>
<original_image>http://imgur.com/cxmHM.png</original_image>
<large_thumbnail>http://imgur.com/cxmHMl.png</large_thumbnail>
<small_thumbnail>http://imgur.com/cxmHMs.png</small_thumbnail>
<imgur_page>http://imgur.com/cxmHM</imgur_page>
<delete_page>http://imgur.com/delete/NNy6VNpiAA</delete_page>
</rsp>
What's the problem here?
Here's the Imgur API page for reference.
var docname = $('#doc').val();
Exactly where is this in your code and when will it be evaluated?
My guess is that it's executed either when the <script> tag has been parsed or you've wrapped it in a $(document).ready() handler. Either way it get's evaluated before the user has actually typed something into the input/text control and docname will therefore be '' or even null all the time. You want the script to fetch the value not until the user has pressed the submit button.
Try it with
$('#submit').click(function() {
$.ajax({
type: "GET",
url: "img_upload.php",
data: "doc=" + $('#doc').val(),
dataType: "xml",
success: parseXml
});
return false;
});
edit: Even better, make the data property an object and let jquery handle the escaping of the value.
data: {doc: $('#doc').val()}
It could be that you have not set the header in the php script - this should be your first line.
header('Content-Type: text/xml');

Categories