I have a function A which loads the data from db if the user has liked the image. I have another function B which loads the count for the total number of likes for the image. Both these functions return response using JSON.
If I call them individually, everything works fine, but if I call function B in function A, I get no JSON response and nothing happens although firebug does show two JSON arrays being outputted.
What is wrong with the code?
Function A:
public function loadLikes() {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $imageid, ':author' => $author);
$query->execute($params);
//calling function B
$this->countLikes($imageid);
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
if ($row['like'] == '1') {
$response = json_encode(array('like' => true));
echo $response;
return TRUE;
}
elseif ($row['like'] == '2') {
$response = json_encode(array('unlike' => true));
echo $response;
return TRUE;
}
else {
$error = "Invalid";
$response = json_encode(array('like' => false, 'text' => $error));
echo $response;
return FALSE;
}
}
}
else {
$response = json_encode(array('unlike' => true));
echo $response;
return FALSE;
}
}
catch(PDOException $ex)
{
echo json_encode(array('like' => false, 'text' => $ex));
return FALSE;
}
}
Function B:
public function countLikes($i) {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $i);
$query->execute($params);
if ($query->rowCount() > 0) {
$count = $query->fetchColumn();
$response = json_encode(array('count' => $count));
echo $response;
return TRUE;
}
}
catch(PDOException $ex)
{
return FALSE;
}
}
jQuery:
$.ajax({
type: "POST",
url: url,
data: postData,
dataType: "json",
success: function(data){
$(".count-like").show(600).text(data.count);
if(data.like) {
$("a#alike").attr('class', 'starred');
}
else if (data.unlike) {
$("a#alike").attr('class', 'unlike');
}
else {
alert(data.text);
}
}
});
If you invoke both functions, then each will output a JSON array. This will result in a HTTP response with following content:
{"like":1}{"count":2}
Both arrays would be valid separately. But if concatenated like this, it's no longer valid JSON.
Instead of outputting the json serialization with echo you should collect it in a temporary variable, merge the two arrays, and then output the combined array with a single:
echo json_encode(array_merge($countArray, $likeArray));
Example adaptions of your code
Function B should become:
public function countLikes($i) {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $i);
$query->execute($params);
if ($query->rowCount() > 0) {
$count = $query->fetchColumn();
/* JUST RETURN HERE */
return (array('count' => $count));
}
}
catch(PDOException $ex)
{
/* INSTEAD OF FALSE use an empty array,
which is interpreted as false in boolean context*/
return array();
}
}
Then when you call the function:
//calling function B
$countArray = $this->countLikes($imageid);
This will always be an array. Which you then can use in the output code:
$response = json_encode(array('like' => true) + $countArray);
(It's still inadvisable to have an echo right there. But too much code, too little context to propose a nicer rewrite. And if it works, ..)
Related
After registering a new user, I receive a selector and token for account verification.
I want to be able to know whether or not a confirmation mail was sent, but I'm having troubles returning the value from the callback. Here's what I have:
try {
$callback = function ($selector, $token) {
$msg = "some message";
if(mail($_POST['email'],"Please verify your account",$msg))
{
return "success";
}
else
{
return "mail_not_sent";
}
};
$auth->registerWithUniqueUsername($_POST['email'], $_POST['password'], $_POST['username'], $callback);
$output['result']=$callback; //this is the array where I want to store the result in ("success" of "mail_not_sent").
}
catch ($e) {
}
It doesn't look like Auth::registerWithUniqueUsername() gives you access to the result of the callback, so if I had to do this, I would do something like this:
$callback_result = '';
$callback = function ($selector, $token) use (&$callback_result) {
/* Other code here */
$callback_result = 'whatever';
/* Other code here */
};
$auth->registerWithUniqueUsername(/* Other args here */, $callback);
$output['result'] = $callback_result;
This is a bit odd way but:
try {
$mailFlag = null;
$callback = function ($selector, $token) use (&$mailFlag) {
$msg = "some message";
if(mail($_POST['email'],"Please verify your account",$msg))
{
$mailFlag = "success";
}
else
{
$mailFlag = "mail_not_sent";
}
};
$auth->registerWithUniqueUsername($_POST['email'], $_POST['password'], $_POST['username'], $callback);
$output['result'] = $mailFlag; //this is the array where I want to store the result in ("success" of "mail_not_sent").
}
catch ($e) {
}
This is the output I get from ajax request to php pdo:
[{"sys_id":"1","task":"qwe","task_date":"11\/30\/2017 8:49 PM","task_person":"qwe","task_status":"0"},{"sys_id":"2","task":"asd","task_date":"11\/30\/2017 9:54 PM","task_person":"asd","task_status":"0"}]null
As shown there is an excess null value which I cant figure out where it is coming from my code is:
function selecttask(action) {
$.ajax({
type: 'POST',
url: '../include/demo.php',
dataType: "json",
data: {
action: action
},
success: function(data) {
}
}).done(function(data) {
});
}
selecttask("selectall");
My demo.php is:
<?php
include_once("crud.php");
//include_once("../config/config.php");
//$con = new connect_pdo();
$crud = new Crud();
$action = $_POST['action'];
$data = $_POST['data'];
switch (strtolower($action)):
case("selectall"):
$table = "list_tbl";
$selectall = $crud->selectall($table);
echo json_encode($selectall, JSON_UNESCAPED_UNICODE);
break;
case("add"):
$table = "list_tbl";
$insert = $crud->insert($table,$data);
echo json_encode($insert, JSON_UNESCAPED_UNICODE);
break;
endswitch;
?>
Then crud is:
<?php
include_once("../config/config.php");
class Crud extends connect_pdo {
public $_con;
function __construct() {
parent::__construct();
$this->_con = $this->dbh();
}
public function selectall($table_name) {
$queryselectall = "Select * from {$table_name}";
$selectall = $this->_con->prepare($queryselectall);
if ($selectall->execute()) {
if ($selectall->rowCount() > 0) {
$result = $selectall->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
}else{
echo array('error'=> TRUE, 'message'=> 'No result found.');
}
}
}
public function insert($table_name, $res) {
parse_str($res, $data);
$limit = count($data);
$ctr = 0;
$columns = "";
$values = "";
foreach ($data as $key => $value) {
$ctr++;
$columns.= "{$key}";
$values .= ":{$key}";
if ($ctr < $limit) {
$columns.= ",";
$values .= ",";
}
}
$query = "INSERT INTO {$table_name} ({$columns})VALUES({$values})";
try {
$create = $this->_con->prepare($query);
foreach ($data as $key => $value) {
$keys = ":{$key}";
$create->bindValue($keys, $value, PDO::PARAM_STR);
}
if ($create->execute()) {
$lastinserted_id = $this->_con->lastInsertId();
echo array('error' => FALSE, 'message' => 'Data added successfully.', 'lastinserted_id' => $lastinserted_id, 'query' => $query);
} else {
echo array('error' => TRUE, 'message' => 'Execution failed, please contact system support!');
}
} catch (Exception $ex) {
echo array('error' => TRUE, 'message' => $ex);
}
}
}
?>
From the above code I cant determine where the null is coming from.
Did I miss something that is why null is coming as result of ajax request
Probably a better architecture for your Crud class to handle DB interactions by running the queries and returning the results as an array (or throwing an exception if anything exceptional happens). Then your demo.php script can just get the array from the Crud class method and handle the output (json encoding, response output).
i was doing long polling , but it can see in my network chrome my long polling in status pending that means is waiting for new data and changes the database , but when I try to insert one item to my database then , but when I try to insert one value show keep that long polling in real time i cant see real time updatings .. how can I fix it?
pusher controller codeigiter
public function pusher() {
header('Content-Type: application/json');
$user_id = $this->session->log['id'];
set_time_limit(0);
while (true) {
$firstCall = false;
if (isset($_GET['timestamp'])) {
$last_ajax_call = $_GET['timestamp'];
} else {
$last_ajax_call = time();
$firstCall = true;
}
clearstatcache();
$notificationsCount = $this->notification->checkForNotifications($last_ajax_call, $user_id);
$newData = (int) $notificationsCount > 0 ? true : false;
$notifications = [];
if ($newData) {
$dataSet = $this->notification->getNotifications($user_id, $last_ajax_call);
foreach($dataSet as $data) {
$notifications[] = $data;
$finalNotificationTime = $data['timestamp'];
}
$result = array('notifications' => $notifications, 'timestamp' => $finalNotificationTime);
$json = json_encode($result);
echo $json;
break;
} else {
if ($firstCall) {
$dataSet = $this->notification->getUnreadNotifications($user_id);
foreach($dataSet as $data) {
$notifications[] = $data;
}
$result = array('notifications' => $notifications, 'timestamp' => $last_ajax_call);
$json = json_encode($result);
echo $json;
break;
}
sleep(1);
session_write_close();
continue;
}
}
exit();
}
ajax
function check_notifications(timestamp) {
var queryString = {
'timestamp': timestamp
};
$.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
data: queryString,
success: function (data) {
// put result data into "obj"
for (var i in data.notifications) {
notify(data.notifications[i].message, data.notifications[i].type, data.notifications[i].timestamp);
}
check_notifications(data.timestamp);
}
});
}
check_notifications();
I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
I have created a javascript file that contains js to trigger an event onchange of a drop down list. The JS is below:
// /public/js/custom.js
jQuery(function($) {
$("#parent").change(function(event){
event.preventDefault();
var parentID = $('#parent').val();
var id = $('#id').val();
$.post("/menu/GetMenuChildren", {pID: parentID, thisID: id },
function(data){
if(data.response === true){
var $el = $("#Position");
$el.empty(); // remove old options
$.each(data.newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
} else {
// print error message
alert("something went wrong in Post");
}
}, 'json');
alert("After Post");
});
});
In my Controller.php I have an function GetMenuChildrenAction as shown below:
public function GetMenuChildrenAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isPost())
{
$post_data = $request->getPost();
$parent_id = $post_data['pID'];
$id = $post_data['thisID'];
//$this->form->get('Position')->SetOptionValues(
$newOptions = $this->getMenuTable()->GetPositionsByID($parent_id, $id);
if(isset($newOptions))
{
$response->setContent(\Zend\Json\Json::encode(array('response' => true, 'newOptions' => $newOptions)));
}
else
{
$response->setContent(\Zend\Json\Json::encode(array('response' => false)));
}
}
return $response;
}
In the MenuTable.php there is a Method GetPositionsByID as shown below:
public function GetPositionsByID($parentID, $id)
{
if($parentID == 0)
{
$menu = $this->getMenu($this->id);
$parentID = $menu->parent_id;
}
if(isset($parentID))
{
$sql = "Select ID,Label from Menu Where parent_ID = " . $parentID . " and id > 1 and id <> " . $id . " Order by Position,Label";
try
{
$statement = $this->adapter->query($sql);
}
catch(Exception $e) {
console.log('Caught exception: ', $e->getMessage(), "\n");
}
$res = $statement->execute();
$rows = array();
$i = 0;
foreach ($res as $row) {
$i = $i + 1;
$rows[$i] = array (
$i => $row['Label']
);
}
return $rows;
}
return array();
}
It all seems to be hooked up correctly, when I debug the code, I get the this line:
$statement = $this->adapter->query($sql);
and then nothing happens. If I replace all the code in the GetPositionsByID method, and simply return an array like the following:
return array('1' => 'one', '2' => 'two');
it works great, however i want to get the data from the DB. Does anyone know why the execute would fail on this line?
$statement = $this->adapter->query($sql);
Thanks in advance
The issue was that the adapter was null.