Display Progress message after calling api url - url-routing

we select checbox & onclick button "Show Status" , I am calling external webservice api url & updating the "status" column [4th in below image] values in Database.....
once we got success response we are displaying alert message....
Requirement :
but now i want to display Progress like "1% completed , 2 % completed" , so on.... :
status page
<button type= "button" id="show_status" >Show Status</button>
script
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function()
{
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var jsonString = JSON.stringify(selected);
$.ajax
({
type: "POST",
url: "api.php",
data: {data : jsonString},
success: function(response)
{
response = $.parseJSON(response);
alert("completed");
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
}
});
});
api.php
<?php
$data = json_decode(stripslashes($_POST['data']));
$response = array();
foreach($data as $id){
$post_data['username']='a';
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
//print_r($orderResults); die;
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
echo json_encode($response);
?>

Please try this script and code
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function(){
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var count = selected.length
var perPlush = 100/count;
var per = 0;
for (var i = 0; i <= count; i++) {
$.ajax
({
type: "POST",
url: "api.php",
data: {id : selected[i]},
success: function(response)
{
response = $.parseJSON(response);
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
per = per + perPlush;
console.log(Math.round(per) + " % Complated");
$("#progress").html(Math.round(per) + " % Complated");
}
});
}
});
Your api.php file
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX);
require_once("dbcontroller.php");
$db_handle = new DBController();
$id = $_POST['id']; //960856092
$response = array();
$orderid = $id;
$hide = '';
$post_data['awb']=$orderid;
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "http://plapi.ecomexpress.in/track_me/api/mawbd/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec ($ch);
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
if($orderResults){
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
else{
$response[$orderid] = ['status' => 'Order already placed'];
}
echo json_encode($response);
?>

Related

Sending JSON HTTP request using Guzzle HTTP: Result parameters are not as expected

I want to send a JSON request to an endpoint but the results that I get don't match the parameters requested.
This is the array
$datas = [
"institutionCode" => $institutionCode,
"brivaNo" => $brivaNo,
"custCode" => $custCode
];
This is the response using Guzzle HTTP
try {
$response = $client->request($verb, $endpoint,
[
"headers" =>
[
"Authorization" => "Bearer " . $token,
"BRI-Timestamp" => $timestamp,
"BRI-Signature" => $signature,
],
"json" => $datas
]
);
return $response;
}
catch (\GuzzleHttp\Exception\RequestException $e) {
return $e->getResponse();
}
This is the response from the endpoint
{
"status": false,
"errDesc": "Institution Code Tidak Boleh Kosong",
"responseCode": "03",
"data": {
"{\"institutionCode\":\"J104408\",\"brivaNo\":\"77777\",\"custCode\":\"7878787878\"}": ""
}
}
Why does the "data" not match the data array I have given above and instead creates a new pattern with a backslash in it?
This is the native way using cURL PHP
if there is someone can turn it into a Guzzle Http, it will help me,
after I tried this code, it also didn't help at all
$institutionCode = "J104408";
$brivaNo = "77777";
$custCode = "123456789115";
$payload = "institutionCode=".$institutionCode."&brivaNo=".$brivaNo."&custCode=".$custCode;
$path = "/v1/briva";
$verb = "DELETE";
$base64sign = generateSignature($path,$verb,$token,$timestamp,$payload,$secret);
$request_headers = array(
"Authorization:Bearer " . $token,
"BRI-Timestamp:" . $timestamp,
"BRI-Signature:" . $base64sign,
);
$urlPost ="https://sandbox.partner.api.bri.co.id/v1/briva";
$chPost = curl_init();
curl_setopt($chPost, CURLOPT_URL,$urlPost);
curl_setopt($chPost, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($chPost, CURLOPT_POSTFIELDS, $payload);
curl_setopt($chPost, CURLINFO_HEADER_OUT, true);
curl_setopt($chPost, CURLOPT_RETURNTRANSFER, true);
$resultPost = curl_exec($chPost);
$httpCodePost = curl_getinfo($chPost, CURLINFO_HTTP_CODE);
curl_close($chPost);
$jsonPost = json_decode($resultPost, true);
return $jsonPost;

Rendering view for DOMPDF in phalconPHP

I have been try to convert template to PDF with DOMPDF in phalconPHP with angularJS at the front. But I am getting 500 internal server error response from it. DOMPDF is included fine in the controller as I loaded static HTML in load_html() function, it worked fine. Below is the report action from ReportsController. Don't bother with the whole code and just skip to the DOMPDF related code at the end. And $patients is the array that contains all the data which the template is going to need.
ReportController's reportAction:
public function reportAction()
{
$patientsModel = new Patients();
$patients = array();
$patients['data'] = array();
$tmpfilters = $this->queryfilters;
unset($tmpfilters['limit']);
$tmpfilters2 = array();
$tmpfilters2['models'] = "PRM\\Models\\Patients";
if( isset( $tmpfilters['conditions'] ) )
{
$tmpCondition = preg_replace("/[^0-9]/", '', $tmpfilters['conditions']);
$tmpfilters2['conditions'] = "clinic = " . $tmpCondition . " AND status = 24";
}
else
{
$tmpfilters2['conditions'] = "status = 24";
}
$tmpActivePatients = new Patients();
$tmpActivePatients = $tmpActivePatients->find($tmpfilters2);
$patients['activeTotal'] = $tmpActivePatients->count();
$tmpfilters3 = array();
$tmpfilters3['models']['m'] = "PRM\\Models\\Activity";
$tmpfilters3['models']['s'] = "PRM\\Models\\Patients";
if( isset( $tmpfilters['conditions'] ) )
{
$tmpCondition2 = preg_replace("/[^0-9]/", '', $tmpfilters['conditions']);
$tmpfilters3['conditions'] = "m.clinic = " . $tmpCondition2 . " AND " . "s.clinic = " . $tmpCondition2 . " AND m.patient=s.id AND m.duration > 1";
}
else
{
$tmpfilters3['conditions'] = "m.patient = s.id AND m.duration > 1";
}
$tmpPatientDuration = new Query($tmpfilters3);
$tmpPatientDuration = $tmpPatientDuration->getQuery()->execute();
//$builder = $this->modelsManager->createBuilder();
$patients['billableTotal'] = $tmpPatientDuration->count();
//$builder->addFrom('PRM\\Models\\Activity', 'a')->innerJoin('PRM\\Models\\Patients', 'p.id=a.patient', 'p')->where('a.duration > 1 AND p.status = 24');
//$result = $builder->getQuery()->execute();
//$patients['billableTotal'] = $result->count();
foreach ($tmpPatientDuration as $patient) {
array_push($patients['data'], array(
'id' => $patient->id,
'firstname' => $patient->s->firstname,
'lastname' => $patient->s->lastname,
'duration' => $patient->m->duration,
'billingCode' => "CPT 99490"));
/*'icd1' => Ccm::findFirstById($patient->icd1)->icdcode,
//'icd2' => Ccm::findFirstById($patient->icd2)->icdcode,
//'clinic' => Clinics::findFirstById($patient->clinic)->name,
'duration' => Activity::sum([
"column" => "duration",
"conditions" => "patient = '{$patient->id}'",
]),
'response' => Activity::findFirst([
"conditions" => "patient = '{$patient->id}' and activity='Communication' ",
"order" => "id desc"
])->description,
'status' => Status::findFirstById($patient->status)->name));*/
}
$html = $this->view->getRender("reports", "report", $patients);
$dompdf = new domPdf();
$dompdf->load_html($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
//$this->response->setJsonContent($patients);
$this->response->setContentType('application/pdf');
$this->response->setContent($dompdf->stream());
$this->response->send();
}
Here is the angularJS controller's code:
$http.get('common/reports/report', {responseType: 'arraybuffer'}).success(
function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}).error(
function (data) {
angular.forEach(data, function (error) {
$scope.error[error.field] = error.message;
console.log(error.field);
});
$alert({title: 'Error!', content: data.flash.message, placement: 'top-right', type: data.flash.class , duration: 10, container: '.site-alert'});
}
);
error logs:
error log for the above problem

CakePHP push notifications are repeating?

I'm trying send push notifications with CakePHP. The notifications are send but the problem is that all notifications are repeating. I cant understand why this problem.
I have a table to add devices of GCM (Google Cloud Messaging). After save the Model I do a SELECT in this table to get all devide_id of GCM saved and send the push notifications. The field device_id is unique in table. After to select I do a foreach to get devices and send the notifications, but this always repeating and send a lot of push to the same device_id.
How could I solve it ?
Push Notification Class
<?php
class Pusher{
const GOOGLE_GCM_URL = 'https://android.googleapis.com/gcm/send';
private $apiKey;
private $proxy;
private $output;
public function __construct($apiKey, $proxy = null)
{
$this->apiKey = $apiKey;
$this->proxy = $proxy;
}
/**
* #param string|array $regIds
* #param string $data
* #throws \Exception
*/
public function notify($regIds, $data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::GOOGLE_GCM_URL);
if (!is_null($this->proxy)) {
curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->getPostFields($regIds, $data));
$result = curl_exec($ch);
if ($result === false) {
throw new \Exception(curl_error($ch));
}
curl_close($ch);
$this->output = $result;
}
/**
* #return array
*/
public function getOutputAsArray()
{
return json_decode($this->output, true);
}
/**
* #return object
*/
public function getOutputAsObject()
{
return json_decode($this->output);
}
private function getHeaders(){
return [
'Authorization: key=' . $this->apiKey,
'Content-Type: application/json'
];
}
private function getPostFields($regIds, $data){
$fields = [
'registration_ids' => is_string($regIds) ? [$regIds] : $regIds,
'data' => is_string($data) ? ['message' => $data] : $data,
];
return json_encode($fields, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
}
}
Controller
<?php
App::uses('AppController', 'Controller');
App::uses('Pusher', 'Plugin/Push');
class NoticiasController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->Noticia->create();
if($this->Noticia->save($this->request->data)){
$this->Session->setFlash(__("Save ok!"));
$this->sendPush();
return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__("Not save :("));
}
}
}
/***************** push notifications ****************/
private function sendPush(){
$apiKey = "AIzaSyCMZ6roIEpHsj5P8cgErgceerljerhaljh";
//msg de push
$message = array("title"=>"Title",
"message"=>"Post a news",
"tickerText"=>"Post a news",
"url"=>"News");
$this->loadModel('Device');
$devices = $this->Device->query("SELECT device_id, status FROM devices Device WHERE status = 1");
$pusher = new Pusher($apiKey);
foreach ($devices as $device){
$pusher->notify($device["Device"]["device_id"], $message);
}
}
}

PHP newbie CURL and array

UPDATED: I've simplified the code (tried to)
I'm trying to download a series of images as set in an array, but something is clearly not right:
function savePhoto($remoteImage,$fname) {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_NOBODY, true);
curl_setopt ($ch, CURLOPT_URL, $remoteImage);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
$fileContents = curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($retcode==200) {
$newImg = imagecreatefromstring($fileContents);
imagejpeg($newImg, ".{$fname}.jpg",100);
}
return $retcode;
}
$filesToGet = array('009');
$filesToPrint = array();
foreach ($filesToGet as $file) {
if(savePhoto('http://pimpin.dk/jpeg/'.$file.'.jpg',$file)==200) {
$size = getimagesize(".".$file.".jpg");
echo $size[0] . " * " . $size[1] . "<br />";
}
}
I get the following errors:
Warning: imagecreatefromstring()
[function.imagecreatefromstring]:
Empty string or invalid image in
C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php
on line 15
Warning: imagejpeg(): supplied
argument is not a valid Image resource
in
C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php
on line 16
Warning: getimagesize(.009.jpg)
[function.getimagesize]: failed to
open stream: No such file or directory
in
C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php
on line 26
*
try this instead:
function get_file1($file, $local_path, $newfilename)
{
$err_msg = '';
echo "<br>Attempting message download for $file<br>";
$out = fopen($newfilename, 'wb');
if ($out == FALSE){
print "File not opened<br>";
exit;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, $out);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $file);
curl_exec($ch);
echo "<br>Error is : ".curl_error ( $ch);
curl_close($ch);
//fclose($handle);
}//end function
// taken from: http://www.weberdev.com/get_example-4009.html
or file_get_contents
You should try file_get_contents in replacement of CURL (simpler but it does the job):
function savePhoto($remoteImage,$fname) {
$fileContents = file_get_contents($remoteImage);
try {
$newImg = imagecreatefromstring($fileContents);
imagejpeg($newImg, ".{$fname}.jpg",100);
} catch (Exception $e) {
//what to do if the url is invalid
}
}
I finally got it to work, with help from you all and a bit of snooping around :-)
I ended up using CURL:
function savePhoto($remoteImage,$fname) {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $remoteImage);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
$fileContents = curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($retcode == 200) {
$newImg = imagecreatefromstring($fileContents);
imagejpeg($newImg, $fname.".jpg",100);
}
return $retcode;
}
$website = "http://www.pimpin.dk/jpeg";
$filesToGet = array('009');
$filesToPrint = array();
foreach ($filesToGet as $file) {
if(savePhoto("$website/$file.jpg",$file)==200) {
$size = getimagesize($file.".jpg");
echo $size[0] . " * " . $size[1] . "<br />";
} else {
echo "File wasn't found";
}
}

How to parse the data from Google Alerts?

Firstly, How would you get Google Alerts information into a database other than to parse the text of the email message that Google sends you?
It seems that there is no Google Alerts API.
If you must parse text, how would you go about parsing out the relevant pieces of the email message?
When you create the alert, set the "Deliver To" to "Feed" and then you can consume the feed XML as you would any other feed. This is much easier to parse and digest into a database.
class googleAlerts{
public function createAlert($alert){
$USERNAME = 'XXXXXX#gmail.com';
$PASSWORD = 'YYYYYY';
$COOKIEFILE = 'cookies.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $COOKIEFILE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $COOKIEFILE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_URL,
'https://accounts.google.com/ServiceLogin?hl=en&service=alerts&continue=http://www.google.com/alerts/manage');
$data = curl_exec($ch);
$formFields = $this->getFormFields($data);
$formFields['Email'] = $USERNAME;
$formFields['Passwd'] = $PASSWORD;
unset($formFields['PersistentCookie']);
$post_string = '';
foreach($formFields as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/ServiceLoginAuth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
if (strpos($result, '<title>') === false) {
return false;
} else {
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts');
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/create');
curl_setopt($ch, CURLOPT_POST, 0);
$result = curl_exec($ch);
//var_dump($result);
$result = $this->getFormFieldsCreate($result);
$result['q'] = $alert;
$result['t'] = '7';
$result['f'] = '1';
$result['l'] = '0';
$result['e'] = 'feed';
unset($result['PersistentCookie']);
$post_string = '';
foreach($result as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/manage');
$result = curl_exec($ch);
if (preg_match_all('%'.$alert.'(?=</a>).*?<a href=[\'"]http://www.google.com/alerts/feeds/([^\'"]+)%i', $result, $matches)) {
return ('http://www.google.com/alerts/feeds/'.$matches[1][0]);
} else {
return false;
}
}
}
private function getFormFields($data)
{
if (preg_match('/(<form.*?id=.?gaia_loginform.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form');
}
}
private function getFormFieldsCreate($data)
{
if (preg_match('/(<form.*?name=.?.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form1');
}
}
private function getInputs($form)
{
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}
}
$alert = new googleAlerts;
echo $alert->createAlert('YOUR ALERT');
It will return link to rss feed of your newly created alert
I found a Google Alerts API here. It's pretty minimal and I haven't tested it.

Resources