Issue with a JSON Query - php

I Use a json onclick script for triggering a php function.
I call the php function with:
$('#dtable').on('click', '[name=option3]', function () {
var select = $(this);
var id = select.attr('id');
$.post('index.php/stop/'+id+'', function(json) {
if (json && json.status) {
$("#failure").show().delay(2500).fadeOut(1500);
} else {
$("#success").show().delay(2500).fadeOut(1500);
}
}
);
} );
If the item is trigger he calls a slim property in my index.php
$admin->slim->post('/stop/:action', function($action) use ($admin) {
$admin->slim->contentType('application/json');
echo json_encode($admin->cont->Stop($action));
After this he triggert the function
function Stop($action) {
$port = $action;
$connection = #fsockopen($this->cfg->base_host, $port, $errno, $errstr, 1);
if (!$connection) {
return false;
} else {
$pid = $this->db->query("SELECT pid FROM testdb WHERE port='" . $port . "'", SQL_ALL, SQL_ASSOC);
if ($pid == "") {
return false;
} else {
......
}
}
}
}
}
the only thing is that the answer from json is always success
but there is no return from true or false from the function
Does someone knows what i doing wrong or can someone give me some advice.
Added more information about the function

Use alert(json); before if (json && json.status) to see what you get. I'm sure json is not what you expect. It seems json == false (because function Stop() return false) and there is no json.status - or maybe rest of your Stop function return something more.

Related

Laravel exists() function keeps returning false when it does exist

i'm not sure what im doing wrong but every time i click the like button it turns up false
Im using laravel 5.5
it clearly works it when i pass in the post id, whenever i click it.
http://127.0.0.1:8000/post/144/islikedbyme
my console log shows no errors, the like button works but the isLikedByMe function keeps rendering
false
in the network log and i don't know why. It works look at the datebase
PostController.php
public function isLikedByMe($id)
{
$post = Post::find($id);
if (Like::whereUserId(auth()->user()->id)->wherePostId($post)->exists()){
return 'true';
}
return 'false';
}
Route
Route::get('post/{id}/islikedbyme', 'PostController#isLikedByMe');
Route::post('post/like/{post}', 'PostController#like');
Main.js
$scope.like = function(post) {
$http.post('/post/like/'+ post.id).then(function(result) {
$scope.getLike(post);
});
};
$scope.getLike = function(post){
$http.get('/post/'+ post.id +'/islikedbyme').then(function(result) {
if (result == 'true') {
$scope.like_btn_text = "Like";
} else {
$scope.like_btn_text = "Unlike";
}
});
}
Because it's removed, if you want even the removed ones do it like this :
public function isLikedByMe($id)
{
$post = Post::find($id);
if (Like::withTrashed()
->whereUserId(auth()->user()->id)
->wherePostId($post->id)->exists()){
return 'true';
}
return 'false';
}
Or even better if you don't want the post insatance you can do it like this :
public function isLikedByMe($id)
{
if (Like::withTrashed()
->whereUserId(auth()->user()->id)
->wherePostId($id)->exists()){
return 'true';
}
return 'false';
}
Try something like below :
public function isLikedByMe($id) {
$post = Post::find($id);
$is_like = Like::where(['user_id' => auth()->user()->id, 'post_id' => $post->post_id])->exists();
if ($is_like) {
return 'true';
}
return 'false';
}

PHP create override function only for certain parts of the original function

Hi there and welcome to my first official problem! I'm trying to override a function, but only certain parts. The function i want to override, is different in several versions of the open source CMS system. The specific parts which i need to change in order for this to work, are the same in all of those versions.
The override has to work with all of those different versions of the CMS system.
I can't use PECL (apd) package or any other external PHP package for this. And as far i know and could find in the PHP manual, there is no function for this.
So, for example:
We have the different CMS system versions: 1, 2 and 3.
And we would have a original function like this one (THIS IS JUST AN EXAMPLE AND NOT THE ACTUAL FUNCTION I NEED CHANGED), which can only be used for version 3. Certain parts are the same in all versions, and some parts are different:
public function createAccessToken($body = false)
{
if (!$body) { //this is different
$body = 'grant_type=client_credentials'; //this is different
}
$this->action = 'POST'; //this is different
$this->endpoint = 'v1/oauth2/token'; //this is different
$response = $this->makeCall($body, "application/json", true); //this is different
if (!isset($response->access_token)) { //this is THE SAME
return false; //this is THE SAME
}
$this->token = $response->access_token; //this is different
return true; //this is different
}
And this is what i would like to change for all of those versions:
public function createAccessToken($body = false)
{
if (!$body) {
$body = 'grant_type=client_credentials';
}
$this->action = 'POST';
$this->endpoint = 'v1/oauth2/token';
$response = $this->makeCall($body, "application/json", true);
if (isset($response->access_token)) { //IT'S CHANGED! THE -> ! IS GONE
return false;
}
$this->token = $response->access_token;
return true;
}
But the function above (which has changed), will only work with version 3 of the CMS system.
Therefore, is there any way i can only override the specific part i need to change and "get" the code which doesn't have to change some other way so the function would still be executed? So again:
public function createAccessToken($body = false)
{
//some way to get the code above the part i need to change, untill i get to the part which needs to be changed. So the override "takes over" from here.
if (isset($response->access_token)) { //IT'S CHANGED! THE -> ! IS GONE
return false;
}
//some way to get the rest of the code and have the function continue agian
}
Hope you can help me out on this.
You could create your own middle layer. This is assuming you have access to some variable that defines your current VERSION.
public function createAccessToken($body = false) {
if (VERSION == 1 || VERSION == 2) { createAccessTokenOld($body); }
else { createAccessTokenNew($body); }
}
public function createAccessTokenOld($body = false)
{
if (!$body) {
$body = 'grant_type=client_credentials';
}
$this->action = 'POST';
$this->endpoint = 'v1/oauth2/token';
$response = $this->makeCall($body, "application/json", true);
if (!isset($response->access_token)) { //IT'S CHANGED! THE -> ! IS GONE
return false;
}
$this->token = $response->access_token;
return true;
}
public function createAccessTokenNew($body = false)
{
if (!$body) {
$body = 'grant_type=client_credentials';
}
$this->action = 'POST';
$this->endpoint = 'v1/oauth2/token';
$response = $this->makeCall($body, "application/json", true);
if (isset($response->access_token)) { //IT'S CHANGED! THE -> ! IS GONE
return false;
}
$this->token = $response->access_token;
return true;
}
You could also do it with a bit more code reuse:
public function createAccessToken($body = false) {
if (VERSION == 1 || VERSION == 2) { createAccessToken($body, true); }
else { createAccessToken($body, false); }
}
public function createAccessToken($body = false, $isOld = false)
{
if (!$body) {
$body = 'grant_type=client_credentials';
}
$this->action = 'POST';
$this->endpoint = 'v1/oauth2/token';
$response = $this->makeCall($body, "application/json", true);
if ($isOld) { if (!isset($response->access_token)) { return false; } }
else { if (isset($response->access_token)) { return false; } }
$this->token = $response->access_token;
return true;
}

How to implement method pointers in PHP

Is there a way to implement method pointers in PHP?
I keep getting the following error:
Fatal error: Call to undefined function create_jpeg() in /Users/sky/Documents/images.php on line 175
This is line 175:
if ($this->ImageType_f[$pImageType]($pPath) != 0)
class CImage extends CImageProperties
{
private $Image;
private $ImagePath;
private $ImageType;
private function create_jpeg($pFilename)
{
if (($this->Image = imagecreatefromjepeg($pFilename)) == false)
{
echo "TEST CREATION JPEG\n";
echo "Error: ".$pFilename.". Creation from (JPEG) failed\n";
return (-1);
}
return (0);
}
private function create_gif($pFilename)
{
if (($this->Image = imagecreatefromgif($pFilename)) == false)
{
echo "Error: ".$pFilename.". Creation from (GIF) failed\n";
return (-1);
}
return (0);
}
private function create_png($pFilename)
{
if (($this->Image = imagecreatefrompng($pFilename)) == false)
{
echo "Error: ".$pFilename.". Creation from (PNG) failed\n";
return (-1);
}
return (0);
}
function __construct($pPath = NULL)
{
echo "Went through here\n";
$this->Image = NULL;
$this->ImagePath = $pPath;
$this->ImageType_f['JPEG'] = 'create_jpeg';
$this->ImageType_f['GIF'] = 'create_gif';
$this->ImageType_f['PNG'] = 'create_png';
}
function __destruct()
{
if ($this->Image != NULL)
{
if (imagedestroy($this->Image) != true)
echo "Failed to destroy image...";
}
}
public function InitImage($pPath = NULL, $pImageType = NULL)
{
echo "pPath: ".$pPath."\n";
echo "pImgType: ".$pImageType."\n";
if (isset($pImageType) != false)
{
if ($this->ImageType_f[$pImageType]($pPath) != 0)
return (-1);
return (0);
}
echo "Could not create image\n";
return (0);
}
}
Just call the method you need with $this->$method_name() where $method_name is a variable containing the method you need.
Also it is possible using call_user_func or call_user_func_array
What is callable is described here: http://php.net/manual/ru/language.types.callable.php
So assuming $this->ImageType_f['jpeg']' must be callable: array($this, 'create_jpeg').
Alltogether: call_user_func($this->ImageType_f[$pImageType], $pPath) is the way to do it.
Or if $this->ImageType_f['jpeg'] = 'create_jpeg':
$this->{$this->ImageType_f['jpeg']]($pPath);
Some documentation on functions I mentioned here:
http://us2.php.net/call_user_func
http://us2.php.net/call_user_func_array
Your problem is is line:
if ($this->ImageType_f[$pImageType]($pPath) != 0)
-since $this->ImageType_f[$pImageType] will result in some string value, your call will be equal to call of global function, which does not exists. You should do:
if ($this->{$this->ImageType_f[$pImageType]}($pPath) != 0)
-but that looks tricky, so may be another good idea is to use call_user_func_array():
if (call_user_func_array([$this, $this->ImageType_f[$pImageType]], [$pPath]) != 0)
I think you need to use this function call_user_func
In your case call will looks like
call_user_func(array((get_class($this), ImageType_f[$pImageType]), array($pPath));

jaxl return to function that it's called from

I have library for xmpp transactions used jaxl libraries:
class xmpp{
public function register_user($username, $password){
require_once 'JAXL/jaxl.php';
$this->client = new JAXL(array(
'jid' => 'localhost',
'log_level' => JAXL_ERROR
));
$this->username = $username;
$this->password = $password;
$this->client->require_xep(array(
'0077' // InBand Registration
));
$thisClassObject =& $this;
$this->client->add_cb('on_stream_features', function($stanza) use(&$thisClassObject) {
$thisClassObject->client->xeps['0077']->get_form('localhost');
return array($thisClassObject, 'wait_for_register_form');
});
$this->client->start();
return;
}
public function wait_for_register_response($event, $args) {
if($event == 'end_stream') {
return;
}
else if($event == 'stanza_cb') {
$stanza = $args[0];
if($stanza->name == 'iq') {
if($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$this->client->end_stream();
return 'logged_out';
}
else if($stanza->attrs['type'] == 'error') {
$error = $stanza->exists('error');
echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL;
echo "error text: ".$error->exists('text')->text.PHP_EOL;
echo "shutting down...".PHP_EOL;
$this->client->end_stream();
return "logged_out";
}
}
}
}
public function wait_for_register_form($event, $args) {
$stanza = $args[0];
$query = $stanza->exists('query', NS_INBAND_REGISTER);
if($query) {
$form = array();
$instructions = $query->exists('instructions');
if($instructions) {
echo $instructions->text.PHP_EOL;
}
$this->client->xeps['0077']->set_form($stanza->attrs['from'], array('username' => $this->username, 'password' => $this->password));
return array($this, "wait_for_register_response");
}
else {
$this->client->end_stream();
return "logged_out";
}
}
}
these code are same as register_user.php, but implemented in a class;
i use this class in my code in this way:
$xmppObj = new xmpp();
$xmppObj('user','password');
/*
some more code after this
/*
when it execute , create user successfully but it's print a message ('registration successful ...') and application exited and it doesn't execute "some code after this" after the class function, in the other word it doesn't follow the code...
What can I do for solve this problem, a person can help me that familiar with JAXL library.
Looks like you are pretty much using the same code as found inside examples/register_user.php. Once user registration is successful, script closes XMPPStream as evident from this section of the code:
if($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$this->client->end_stream();
return 'logged_out';
}
You MUST instead call $client->send_end_stream(); and not $client->end_stream();. This will make sure underlying XMPPStream makes proper FSM state transition. Also add a callback for on_disconnect event, inside this callback you can again try to connect back with newly registered XMPP account and it should just work fine.
Note: Kindly checkout latest code from the repository. I made some updates which will allow core JAXLLoop to be re-initialized. If you are interested in details, here is the commit log.

returning values from one method to another

I don't know why this don't work at all. I maybe wrong with my understanding that is why.
here is the situation.
MVC pattern
form validation stuffs
Here are the codes
public function userExist($data)
{
$string = "SELECT student_number FROM users WHERE student_number = :user";
$sth = $this->db->prepare($string);
$sth->execute(array(
':user' => $data['user']
));
return $sth->rowCount() == 0 ? true : false;
}
public function validate($data) {
$this->userExist($data);
}
What i want is to return a string, that says "user exists", if the userExist method is false ... But this code doesn't work:
if($sth->rowCount() == 0) {
return true;
} else {
return "User Already Exists";
}
This is, how i call them in the controller:
if ($this->model->validate($data) == true) {
$this->model->create($data);
header('Location: '.URL.'users');
} else {
echo $this->model->validate($data);
die();
}
What do you think is the best solution?
First of all, you need to return the value of validate:
public function validate($data) {
$this->userExist($data);
}
But there are some other problems here. You don't need to call $this->model->validate($data) twice in your controller. You could do something like:
$result = false;
$result = $this->model->validate($data);
if ( true === $result {
$this->model->create($data);
header('Location: '.URL.'users');
} else {
die($result);
}

Categories