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.
Related
I was integrating a PHP code to ping sitemap to google and Bing. The code executed perfectly but to be a fact if i'm initiating the request from a ajax call. It does not return back
Below is the Jquery code i'm using to make ajax call
$("body").on('click', 'button#sitemap_google_submit', function(event){
toastr.info("Would require few seconds, Please wait, do not refresh Page..",
"Submitting Sitemap to Google!",
{ progressBar:!0,
showMethod:"slideDown",
hideMethod:"slideUp",
timeOut:2e3,
preventDuplicates: true,
positionClass: "toast-bottom-right"
}
);
$("button#sitemap_google_submit").attr("disabled", true);
$("button#sitemap_google_submit").html("<i class='ft-loader spinner'></i> Submitting to Google..");
$.ajax({
url: '/bypasser/modules/seoController.php',
type: 'POST',
dataType: 'JSON',
data: {type: 'submit', console: 'google'},
})
.done(function(resp) {
$("button#sitemap_google_submit").attr("disabled", false);
$("button#sitemap_google_submit").html("<i class='fa fa-google fa-lg'></i> Submit to Google");
toastr[resp.type](resp.message,
resp.heading,
{ showMethod:"slideDown",
hideMethod:"slideUp",
preventDuplicates: true,
positionClass: "toast-bottom-right"
});
});
});
on PHP side i'm using below request
<?php
include("appController.php");
$reqType = preg_replace("/[^a-zA-Z]/", "", $_REQUEST['type']);
class seoController Extends appController
{
public function submitGoogle($url)
{
$url = "http://www.google.com/webmasters/sitemaps/ping?sitemap=".$this->websiteBaseURL().$url;
$returnCode = $this->myCurl($url);
if($returnCode == 200) {
echo json_encode(array("type" => "success",
"heading" => "Success!",
"message" => "Sitemap Submitted to Google!!")
);
}else{
echo json_encode(array("type" => "warning",
"heading" => "Warning!",
"message" => "Problem occured while submitted SiteMap, try again after Sometime!"
)
);
}
}
function myCurl($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER , true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode;
}
}
$seoController = new seoController();
if($reqType == "submit" &&
preg_replace("/[^a-z]/", "", $_POST['console']) == "google")
$seoController->submitGoogle("sitemap.xml");
?>
The JSON encodes displays perfectly in the preview panel of network tab of inspect element, but somehow it does not return the response to ajax, what is the issue?
Set
curl_setopt($ch, CURLOPT_HEADER , false); // we don't want headers
instead of
curl_setopt($ch, CURLOPT_HEADER , true); // we want headers
we don't want the headers as well, as far a i understand your question, you may be looking for ping status code only!
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.
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
}
I have to simulate AJAX request in PHP, exactly as is in jQuery. My current code is here:
Original AJAX call (mustn't be modified)
$.ajax({
type: "POST",
url: "/someFile.php",
data: data,
success: function(response) {
some_code_here;
},
error: function() {
some_code_here;
}
});
Current PHP code - trying to simulate JS's code behaviour above
function _misc_test() {
$data = json_decode("xxx"); // The "xxx" is placeholder for the same string, as is in data var in JS above
$ajaxResponse = _make_post_request('/someFile.php', $data);
print_r($ajaxResponse);
}
function _make_post_request($url, $data) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
And unfortunatelly, the PHP code doesn't seems to generate exactly the same packets like JS code - that's what I need. Can anyone give me a hand please?
EDIT: maybe it's important, that data variable in JS holds complex JS object like this one:
{"options":{"userIP":"89.102.122.16","playerType":"flash","playlistItems":[{"Type":"Archive","Format":"MP4_Web","Identifier":"209 452 80139\/0042","Title":"Nezn\u00e1m\u00ed hrdinov\u00e9","Region":"","SubtitlesUrl":"http:\/\/img2.ceskatelevize.cz\/ivysilani\/subtitles\/209\/209452801390042\/subtitles-1.txt","Indexes":null,"Gemius":{"Param":[{"Name":"materialIdentifier","Value":"209 452 80139\/0042"},{"Name":"testParam","Value":"testValue"}]}}],"previewImageURL":null}}
in js : data: $('form').serialize();
in php :
How to post data in PHP using file_get_contents?
$jsonstr = '{"options":{"userIP":"89.102.122.16","playerType":"flash","playlistItems":[{"Type":"Archive","Format":"MP4_Web","Identifier":"209 452 80139\/0042","Title":"Nezn\u00e1m\u00ed hrdinov\u00e9","Region":"","SubtitlesUrl":"http:\/\/img2.ceskatelevize.cz\/ivysilani\/subtitles\/209\/209452801390042\/subtitles-1.txt","Indexes":null,"Gemius":{"Param":[{"Name":"materialIdentifier","Value":"209 452 80139\/0042"},{"Name":"testParam","Value":"testValue"}]}}],"previewImageURL":null}}';
print_r(
$data = json_decode($jsonstr ,true)
);
$data_url = http_build_query ($data);
$data_url = str_replace("amp;","",$data_url); //fix for & to &
$data_len = strlen ($data_url);
$url = 'http://domain.com/returnPost.php';
$result = file_get_contents ($url, false,
stream_context_create (
array ('http'=>
array ('method'=>'POST'
, 'header'=>"Connection: close\r\nContent-Length: $data_len\r\n"
, 'content'=>$data_url
))
)
);
print_r(
$result
);
in returnPost.php
print_r($_POST);
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');