I am posting data to google sheets using php, everytime I post the data it get added on the sheet correctly, but i get the error message as
We8d#39;re sorry, a server error occurred. Please wait a bit and try
again.
My php curl post code is:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $gsurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$res = json_decode($output, 1);
My GS App Script is :
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000);
try {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1;
var row = [];
for (i in headers){
if (headers[i] == "Timestamp"){
row.push(new Date());
} else {
row.push(e.parameter[headers[i]]);
}
}
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally {
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
Please help me.
Related
I've been trying to select values (students data) from mysql database table and looping through database to send to an API using PHP CURL Post request but it's not working.
This is the API body:
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.schooldomain.com"
}
Parameters I want to send are "admissionNumber" and "class" parameters while "appDomain" is same for all. Here's my code:
if(isset($_POST['submit'])){
$body = "success";
$info = "yes";
class SendDATA
{
private $url = 'https://url-of-the-endpoint';
private $username = '';
private $appDomain = 'http://schooldomain.com/';
// public function to commit the send
public function send($admNo,$class)
{
$url_array= array('admissionNumber'=>$admNo,'class'=>$class,'appDomain'=>$this-> appDomain);
$url_string = $data = http_build_query($url_array);
// using the curl library to make the request
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $url_string);
curl_setopt($curlHandle, CURLOPT_POST, 1);
$responseBody = curl_exec($curlHandle);
$responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
return $this->handleResponse($responseBody,$responseInfo);
}
private function handleResponse($body,$info)
{
if ($info['http_code']==200){ // successful submission
$xml_obj = simplexml_load_string($body);
// extract
return true;
}
else{
// error handling
return false;
}
}
}
$sms = new SendDATA();
$result = mysqli_query( $mysqli, "SELECT * FROM school_kids");
while ($row = mysqli_fetch_array($result)) {
$admNo = $row['admNo'];
$class = $row['class'];
$sms->send($admNo,$class,"header");
echo $admNo. " ".$class;
}
}
The question is rather unclear; when you say "this is the API body", I presume this JSON fragment is what the REST API at https://url-of-the-endpoint expects. If so, you are building your request body wrong. http_build_query creates an URL-encoded form data block (like key=value&anotherKey=another_value), not a JSON. For a JSON, here's what you want:
$data = array('students' => array
(
array('admissionNumber' => $admNo, 'class' => $class)
),
'appDomain':$this->appDomain
);
$url_string = $data = json_encode($data);
Also, you probably want to remove the HTTP headers from the response:
curl_setopt($curlHandle, CURLOPT_HEADER, false);
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');
}
}
});
});
Recently tasked to monitor external webpage response/loading time via CACTI. I found some PHP scripts that were working (pageload-agent.php and class.pageload.php) using cURL. All was working fine until they requested it to be transferred from LINUX to Windows 2012R2 server. I'm having a very hard time modifying the scripts to work for windows. Already installed PHP and cURL and both working as tested. Here are the scripts taken from askaboutphp.
class.pageload.php
<?php
class PageLoad {
var $siteURL = "";
var $pageInfo = "";
/*
* sets the URLs to check for loadtime into an array $siteURLs
*/
function setURL($url) {
if (!empty($url)) {
$this->siteURL = $url;
return true;
}
return false;
}
/*
* extract the header information of the url
*/
function doPageLoad() {
$u = $this->siteURL;
if(function_exists('curl_init') && !empty($u)) {
$ch = curl_init($u);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, false);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
$pageBody = curl_exec($ch);
$this->pageInfo = curl_getinfo($ch);
curl_close ($ch);
return true;
}
return false;
}
/*
* compile the page load statistics only
*/
function getPageLoadStats() {
$info = $this->pageInfo;
//stats from info
$s['dest_url'] = $info['url'];
$s['content_type'] = $info['content_type'];
$s['http_code'] = $info['http_code'];
$s['total_time'] = $info['total_time'];
$s['size_download'] = $info['size_download'];
$s['speed_download'] = $info['speed_download'];
$s['redirect_count'] = $info['redirect_count'];
$s['namelookup_time'] = $info['namelookup_time'];
$s['connect_time'] = $info['connect_time'];
$s['pretransfer_time'] = $info['pretransfer_time'];
$s['starttransfer_time'] = $info['starttransfer_time'];
return $s;
}
}
?>
pageload-agent.php
#! /usr/bin/php -q
<?php
//include the class
include_once 'class.pageload.php';
// read in an argument - must make sure there's an argument to use
if ($argc==2) {
//read in the arg.
$url_argv = $argv[1];
if (!eregi('^http://', $url_argv)) {
$url_argv = "http://$url_argv";
}
// check that the arg is not empty
if ($url_argv!="") {
//initiate the results array
$results = array();
//initiate the class
$lt = new PageLoad();
//set the page to check the loadtime
$lt->setURL($url_argv);
//load the page
if ($lt->doPageLoad()) {
//load the page stats into the results array
$results = $lt->getPageLoadStats();
} else {
//do nothing
print "";
}
//print out the results
if (is_array($results)) {
//expecting only one record as we only passed in 1 page.
$output = $results;
print "dns:".$output['namelookup_time'];
print " con:".$output['connect_time'];
print " pre:".$output['pretransfer_time'];
print " str:".$output['starttransfer_time'];
print " ttl:".$output['total_time'];
print " sze:".$output['size_download'];
print " spd:".$output['speed_download'];
} else {
//do nothing
print "";
}
}
} else {
//do nothing
print "";
}
?>
Thank you. any type of assistance is greatly appreciated.
Thanks guys and gals got it working
//create a function
function get_stock_data($symbol){
//set up the url to be called
$revenue_url = "http://finance.yahoo.com/q/is?s=".$symbol;
//curl call:
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $revenue_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// grab URL and pass it to the browser
$result = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
//finish by returning the result
return $result;
}
//REQUEST WILL BE POPULATED IF EITHER GET OR POST IS SET!
$data = null; // this will hold our data, declared here for accessibility
if(isset($_REQUEST['symbol']) && $_REQUEST['symbol'] != ''){
//call our get_data function
$data = get_stock_data($_REQUEST['symbol']);
}
// data returned from our get_stock_data() call.
$ppe = $data['ppe'];
$revenue = $data['revenue'];
$income = $data['income'];
$market_cap = $data['market_cap'];
$depreciation = $data['depreciation'];
$rate_of_return = $data['rate_of_return'];
$rate_of_return_w_ppe = $data['rate_of_return_w_ppe'];
$debt = $data['debt'];
}
Add following code in your update button(page) script at last
<script type="text/javascript">
var php_var = "<?php echo $symbol; ?>";
locationInfo="stock_next.php?symbol="+php_var;
setTimeout(function(){
location =locationInfo
},2000)
</script>
Your page will be automatically updated after some seconds
I want to read the content of a URL in javascript. The URL is not on my domain so I need a middle layer that can access cross domain.
I tried to use a PHP function to read the URL and return the result to javascript using jquery but it didn't work.
Here is my trial:
I created a php file named "phpjs_test.php"
<?php
function get_data(){
$url='http://asmary.dreameg.com/texttable.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
$content = htmlspecialchars($content);
curl_close($ch);
$content = nl2br($content);
return $content;
}
?>
and this is the javascript code:
<script>
$(document).ready(function () {
//httpQuery("http://asmary.dreameg.com/texttable.txt");
getOutput();
});
function getRequest() {
var req = false;
try {
// most browsers
req = new XMLHttpRequest();
} catch (e) {
// IE
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
return req;
}
function getOutput() {
var ajax = getRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
document.getElementById('output').innerHTML = ajax.responseText;
}
};
ajax.open("GET", "phpjs_test.php", true);
ajax.send(null);
}
I'm completely new to PHP so I don't know even the PHP function is correct or not.
You should just use jQuery ajax methods instead of creating XMLHTTPRequest you don't have to bother with adding more code for IE plus you're already loading the jQuery library. Also if you set the header to Allow-Origin-Access in your PHP file and specify the other domain you're requesting from then you can make an AJAX request and get the response otherwise it will return nothing or in your dev tools network tab it will show a 403 - Forbidden.
Access-Control-Allow-Origin syntax
Change the PHP file to:
<?php
$url='http://asmary.dreameg.com/texttable.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
$content = explode('~',$content);
foreach($content as $c)
{
$records[] = explode('|',$c);
}
$content = json_encode($records);
echo $content;
?>
Javascript will receive a json array like this
[["1","name1","10","city1"],["2","name2","20","city2"],["3","name3","30","city3"],["4","name4","40","city4"],["5","name5","50","city5"],["6","name6","60","city6"],["7","name7","7","city7"],["8","name8","80","city8"],["9","name9","90","city9"],["10","name10","100","city10"],["11","name11","11","city11"],["12","name12","12","city12"],["13","name13","13","city13"],["14","name14","14","city14"],["15","name15","15","city15"],["16","name16","16","city16"],["17","name17","17","city17"],["18","name18","18","city18"],["19","name19","19","city19"],["20","name20","20","city20"],[""]]