connection between android app and cakephp - php

Hi I'm making a web service in cakephp for an android app. I am getting the request and the respose is being send but the response is not visible on the client's end. My code is as shown below. Can there be some other method to send the response.
public function AndroidApp() {
if (isset($_POST["myHttpData"])) {
$coupon = trim($_POST["myHttpData"]);
$couponId = $this->Code->find('all', array(
'conditions' => array(
'Code.coupon_code' => $coupon,
'Code.status' => 'Used'
),
'fields' => array('Code.id')));
$studentAssessmentId = $this->StudentAssessment->find('all', array(
'conditions' => array(
'StudentAssessment.code_id' => $couponId[0]['Code']['id'],
'StudentAssessment.status' => 'Complete'
),
'fields' => array('StudentAssessment.id')));
$scores = $this->AssessmentScore->find('all', array(
'conditions' => array(
'AssessmentScore.student_assessment_id' => $studentAssessmentId[0]['StudentAssessment']['id']
),
'fields' => array('AssessmentScore.score')));
$json = array();
$assessment_data = array();
//debug($scores);
$i = 0;
foreach ($scores as $score) {
$assessment_data[$i] = array("score" => $score['AssessmentScore']['score']);
$i+=1;
}
header('Content-type: application/json');
$json['success'] = $assessment_data;
$android = json_encode($json);
} else {
$json['error'] = "Sorry, no score is available for this coupon code!";
$android = json_encode($json);
}
echo $android;

code smell, non-cakephp standards
First of all, as mentioned in comments by others, you're not using the CakePHP request/response objects. Because of this, you're overly complicating things. See the documentation here;
http://book.cakephp.org/2.0/en/controllers/request-response.html
http://book.cakephp.org/2.0/en/controllers/request-response.html#dealing-with-content-types
And
http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
The $scores loop to reformat the query results is probably redundant if you replace the find('all') with find('list'), using 'score' as display field. See the documentation here http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list
bugs
There also seems to be some bugs in your code;
the content-type header is only sent if $_POST["myHttpData"] is present.
you're only checking if $_POST["myHttpData"] is present, not if it actually contains any data (empty)
you're not checking if the various queries return a result. This will cause errors in your code if a query did not return anything! For example, you assume that $couponId[0]['Code']['id'] is present (but it won't be if the coupon-code was not found)
possible answer
Apart from these issues, the most probable cause for your problem is that you did not disable 'autoRender'. Therefore CakePHP will also render the view after you've output your JSON, causing a malformed JSON response.
public function AndroidApp() {
$this->autoRender = false;
// rest of your code here
}

Related

Unable to use templates in php

I am working with an existing website,(I am new to this site),I have to find and use the view/transaction_detail page. How can I do this? How can I find the exact path of the file
Here is my code
public function transaction_wallet()
{
//echo "Om Success3";
$customer_id = $this->session->userdata('customer_id');
$customer = $this->site->getRowById('customer_information', 'customer_id', $customer_id);
if($customer->sales_active != 1){
$this->session->set_flashdata('danger_msg', 'Sorry, You have not active !');
redirect('customer/customer_dashboard');
}
$getWallet = $this->site->getRowsByCondition('wallet_transaction', array('customer_id'=>$customer_id), array('id','desc'), 1);
$wallet_balance = !empty($getWallet) ? $getWallet[0]->balance : 0;
$company_info = $this->site->getRowsByCondition('company_information');
$data = array(
'title' => 'Transaction Wallets',
'customer' => objectToArray($customer),
'customer_id' => $customer_id,
'wallet_balance' => $wallet_balance,
'company_info' => $company_info
);
$content = $this->parser->parse('website/customer/transaction_wallet', $data, true);
$this->template->full_customer_html_view($content);
}
If I understand your question correctly, you want to find the file in your project-structure, of which you know the http-path.
A easy way is to go to the page, view the page source and look for an specific codepart.
Also, you can look for a word on the page itself which has nothing to do with a framework syntax.
For example you find a header "Tuesday is moneyday" or a class, "class="moneytable".
Go to your project and simply use the search tool of your IDE to find "Tuesday is moneyday" or "moneytable".

Array becoming multi-dimensional in AJAX request

So I am creating a function in WordPress which counts and sets a user session and storing its values in the user's local storage. I was able to make it work perfectly by using cookies and when the site is hosted locally, for some reason, it is not working when I uploaded it on the staging site. So I am trying implement this function using another approach and decided to use local storage instead.
There's a problem with the Array values that the function is generating and I have spent almost the entire day trying to debug the problem. It is generating multi-dimensional instead of a single one.
Here's my function code:
function monitor_post_views() {
$page_id = 'page' . $_POST['page_id'];
$timestamp = time();
// 30 minutes timeout
$timeout = 1800;
// Serves as my guide for debugging, will not include in the final code
$message = '';
if ( ! empty($_POST['page_id_array']) ) {
//Checks if values from local storage exist
//Gets the stored Array coming from AJAX call
$page_id_array[] = json_decode(stripslashes($_POST['page_id_array']), true);
if ( in_array_r($page_id_array, $page_id) ) {
//Check if current page is found in array
$message = 'FOUND IN ARRAY CHECKING !!!!';
$temp= [];
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array_temp;
//Pushes the generated array inside the $page_id_array
array_push($page_id_array, $temp);
print_r(json_encode($page_id_array));
foreach ( $page_id_array as $page ) {
//If page is in array, check if the session is expired, if not, do nothing, if expired, update and then run the view function
}
} else {
// ID Not found in Array, Insert a new entry
$message = 'ID NOT FOUND IN ARRAY, CREATING ENTRY !!!';
$temp = [];
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array_temp;
//Pushes the generated array inside the $page_id_array
array_push($page_id_array, $temp);
print_r(json_encode($page_id_array));
//Set post view function here base on $_POST['page_id']
}
} else {
//Not found in local storage, need to create one
$message = 'CREATING A NEW ENTRY !!!!';
$temp = [];
$page_id_array = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array;
print_r(json_encode($temp));
//Set post view function here base on $_POST['page_id']
}
wp_die();
}
add_action('wp_ajax_monitor_post_views', 'monitor_post_views');
add_action('wp_ajax_nopriv_monitor_post_views', 'monitor_post_views');
Here's a screenshot of what this function generates
Array
Here's a sample JSON
[[{"id":"page1202","expiration":1551125579,"message":"FOUND IN ARRAY CHECKING !!!!"},{"id":"page1206","expiration":1551125613,"message":"ID NOT FOUND IN ARRAY !!!! INSERTING ENTRY !!!"}],{"id":"page1296","expiration":1551125624,"message":"ID NOT FOUND IN ARRAY !!!! INSERTING ENTRY !!!"}]
I was trying to generate a one dimensional but ended up with this.
Any thoughts? Thanks in advance
The problem is you are creating arrays too many times:
Change $page_id_array and $page_id_array_temp to
$page_id_array=new \stdClass();//no need to declare as an array
replace
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
with
$page_id_array->id=$page_id;
$page_id_array->expiration=$timestamp;
$page_id_array->message=$message;
also change
$temp = [];
you can use it directly
//no need to declare $temp as an array
$temp=$page_id_array;

How do I put a SimplePie Enclosure Link into an Array

I am attempting to parse an RSS feed which uses media enclosures. I am using SimplePie and I have been able to parse it, and make all the needed elements appear on the page.
But I am writing a plugin for a CMS and I need to put those elements into an array. All are working fine, except the $item->get_enclosure().
I should say, that in the array, what is returned is a string of gibberish. I need it to return the url to the file.
Here is the relevant code:
// Get Enclosure
$enclosures = array();
$item_enclosures = $item->get_enclosures();
if ( ! empty($item_enclosures))
{
foreach ($item_enclosures as $enclosure)
{
if ($enclosure = $item->get_enclosure())
{
$enclosure->get_link();
} else {
$enclosure->get_title();
}
}
}
$items[] = array(
'item_title' => $item->get_title(),
'item_link' => $item->get_permalink(),
'item_date' => $item->get_date('U'),
'item_content' => $item->get_content(),
'item_img' => $item->get_enclosure(),
'item_description' => $item->get_description(),
'item_categories' => $categories,
'item_authors' => $authors
);
}
return $items;
Does anyone know how to make the 'item_img' return a link to the file, rather than what seems to be some kind of encoded string of characters.
From http://simplepie.org/wiki/reference/simplepie_enclosure/get_link
$link = $item->get_enclosure()->get_link();
would seem to do what you want.

array_key_exists() expects parameter 2 to be array, string when using pushWoosh Class

I am having some trouble implementing the pushwoosh class http://astutech.github.io/PushWooshPHPLibrary/index.html. I have everything set up but i am getting an error with the array from the class.
This is the code i provied to the class:
<?php
require '../core/init.php';
//get values from the clientside
$sendID = $_POST['sendID'];
$memID = $_POST['memID'];
//get sender name
$qry = $users->userdata($memID);
$sendName = $qry['name'];
//get receiving token
$qry2 = $users->getTokenForPush($sendID);
$deviceToken = $qry2['token'];
//i have testet that $deviceToken actually returns the $deviceToken so thats not the problem
//this is the array that the php class requires.
$pushArray = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$push->createMessage($pushArray, 'now', null);
?>
And this is the actually code for the createMessage() method
public function createMessage(array $pushes, $sendDate = 'now', $link = null,
$ios_badges = 1)
{
// Get the config settings
$config = $this->config;
// Store the message data
$data = array(
'application' => $config['application'],
'username' => $config['username'],
'password' => $config['password']
);
// Loop through each push and add them to the notifications array
foreach ($pushes as $push) {
$pushData = array(
'send_date' => $sendDate,
'content' => $push['content'],
'ios_badges' => $ios_badges
);
// If a list of devices is specified, add that to the push data
if (array_key_exists('devices', $push)) {
$pushData['devices'] = $push['devices'];
}
// If a link is specified, add that to the push data
if ($link) {
$pushData['link'] = $link;
}
$data['notifications'][] = $pushData;
}
// Send the message
$response = $this->pwCall('createMessage', $data);
// Return a value
return $response;
}
}
Is there a bright mind out there that can tell me whats wrong?
If I understand, your are trying to if your are currently reading the devices sub-array. You should try this:
foreach ($pushes as $key => $push) {
...
// If a list of devices is specified, add that to the push data
if ($key == 'devices') {
$pushData['devices'] = $push['devices'];
}
You iterate over $pushes, which is array('content' => ..., 'devices' => ...). You will first have $key = content, the $key = 'devices'.
It looks like the createMessage function expects an array of messages, but you are passing in one message directly. Try this instead:
$push->createMessage(array($pushArray), 'now', null);
The class is expecting an array of arrays; you are just providing an array.
You could do something like this
//this is the array that the php class requires.
$pushArrayData = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$pushArray[] = $pushArrayData
Will you ever want to handle multiple messages? It makes a difference in how I would do it.

How to tweet an image using PHP from my website?

I am trying to tweet an image using php. I have read the documentation and followed a some tutorials. I don't have any problem when sending a message; however, it does not work with images. I can not find where my mistake is, can anyone help?? I would deeply appreciate it.
<?php
$comments = $_POST['comment'];
if (isset($_POST['Twitter']))
{
require_once('twitter/codebird-php/src/codebird.php');
\Codebird\Codebird::setConsumerKey("xxxxxx","xxxxxx");
$cb = \Codebird\Codebird::getInstance();
$cb->setToken("xxxxxx", "xxxxxxxxxx");
$params = array(
'status' => $comments,
'media[]' => "/images/image1.jpg"
);
$reply = $cb->statuses_update($params);
echo "You have posted your message succesfully";
}
else{
echo "You havent posted anythingh";
}
?>
You need to supply Twitter the fully qualified URI to your image.
You have the following code:
$params = array(
'status' => $comments,
'media[]' => "/images/image1.jpg"
);
Unfortunately, that's not a complete URL to an image, it's a relative URL. Instead, you need to provide something along the lines of this:
$params = array(
'status' => $comments,
'media[]' => "http://www.example.com/images/image1.jpg"
);
In addition, according to the Twitter API v1 documentation, you need to use statuses/update_with_media instead of statuses/update.
If you are using Twitter API v1, Twitter also recommends using v1.1 instead.

Categories