Email send successfully , success or error messages not print, here is my code please check [ Controller]
if ($this->email->send()){
$str = "success";
echo json_encode(array('st' => 0, 'msg' => $str ));
} else {
$str = "error";
echo json_encode(array('st' => 0, 'msg' => $str ));
}
Ajax Script
$('#forgot_form').submit(function(){
$.post($('#forgot_form').attr('action'),$('#forgot_form').serialize(),function(json){
if ( json.md == 0){
$('#msg-container').html(json.msg);
} else {
('#msg-container').html(json.msg);
}
},'json');
return false;
});
It's not a ajax script error. Just check your modal your return value is not accepting the false condition, and only returning the true value.
use this..
$this->output
->set_content_type('application/json')
->set_output(json_encode( (
array('st'
=> 0, 'msg' => $str ));
Related
I'm working on a functionality where only a user with the ID number 3 can bet if the match is 1 minute away from starting, it's a success, but now those matches that has the status "Open" is not allowed to place bets. here is the code:
public function *addMatchBet*(Request $request){
$rules = [
'matchid' => 'required|integer|exists:matches,id',
'teamid' => 'required|integer|exists:teams,id',
'bet_amount' => 'required|integer|min:100'
];
$validation = \**Validator**::make($request->all(), $rules);
if ($validation->passes()) {
$user = \**Auth**::user();
$match = \App\**Match**::find($request->matchid);
$team = \App\**Team**::find($request->teamid);
if(!in_array($team->id, [$match->team_a, $match->team_b])) {
return [
'success' => false,
'errors' => [
'bet' => ['Match teams have been updated! Please refresh
page and try again.']
]
];
}
if($match && $match->status == 'open') {
$betCount = $user->bets
->where('match_id', $request->matchid)
->count();
if($match->isClosing(0)) {
return [
'success' => false,
'errors' => [
'bet' => ['Could no longer bet. This match is now
starting!']
]
];
}
}
}
}
Any ideas anyone? TYIA
I've found a solution, this was the code:
if($match && $match->isClosing(0)) {
if($user->id == 3){
$betCount = $user->bets
->where('match_id', $request->matchid)
->count();
}
else{
return [
'success' => false,
'errors' => [
'bet' => ['Could no longer bet. This match is now starting!']
]
];
}
}
I try validation Alnum in my Phalcon model. But I get not the correct validation when I enter symbols in Cyrillic (utf8)
$validation->add(
'title',
new \Phalcon\Validation\Validator\Alnum([
"message" => 'Поле Город содержит недопустимые символы',
])
);
Phalcon's validation service is using the PHP built in ctype_alnum function (as seen here), which does not support multibyte strings.
Quick snippets for testing:
$validation = new \Phalcon\Validation();
$validation->add(
'name',
new \Phalcon\Validation\Validator\Alnum(
[
'message' => 'Validation failed',
]
)
);
$words = [
'test1234',
't__est1234',
'тест123',
];
echo '<h2>Phalcon Validation</h2>';
foreach ($words as $word) {
$messages = $validation->validate(['name' => $word]);
if (count($messages)) {
echo '[N] '. $word, '<br>';
} else {
echo '[Y] '. $word, '<br>';
}
}
echo '<h2>PHP `ctype_alnum`</h2>';
foreach ($words as $word) {
if (ctype_alnum($word)) {
echo '[Y] '. $word, '<br>';
} else {
echo '[N] '. $word, '<br>';
}
}
Results:
Phalcon Validation
[Y] test1234
[N] t__est1234
[N] тест123
PHP `ctype_alnum`
[Y] test1234
[N] t__est1234
[N] тест123
I'm afraid you have to use preg_match to solve your problem. Quick sample:
preg_match("/^[a-zA-Z\p{Cyrillic}0-9\s\-]+$/u", $string);
Source: Using Arabic characters with ctype_alnum or How to use ctype_alpha with UTF-8
And finally, here is info on how to create your own validator: https://docs.phalconphp.com/en/latest/validation#validators
Update: #Vladimir Kompaniec solution from comments!
$validator->add('city', new Callback([
'callback' => function () {
if (empty($this->subway)) {
return true;
}
return (0 != preg_match("/[\w\d\s\-А-Яа-я]+/u", $this->subway));
},
'message' => 'Поле метро содержит недопустимые символы',
'cancelOnFail' => true,
]));
as title says I wonder if there is an way to get the getQueryLog function to show line of the query.
var_dump(DB::getQueryLog())
You can't do it with getQueryLog(), but you can listen to queries, generate a backtrace and finally extract line number:
// routes.php
Event::listen('illuminate.query', function($query,$binding,$time,$connections){
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
foreach ($backtrace as $trace) {
if(array_key_exists('file',$trace) && array_key_exists('line',$trace)){
if( strpos($trace['file'],base_path().'/app') !== false ){
var_dump(array(
'query' => $query
,'binding' => $binding
,'time' => $time
,'connection' => $connections
,'file' => $trace['file']
,'line' => $trace['line']
));
break;
}
}
}
});
I'm using the HybridAuth library.
I'd like to be able to post message to my authenticated users twitter profile with images.
The setUserStatus method works well to automatically send a tweet.
I wrote the following method :
function setUserStatus( $status, $image )
{
//$parameters = array( 'status' => $status, 'media[]' => "#{$image}" );
$parameters = array( 'status' => $status, 'media[]' => file_get_contents($image) );
$response = $this->api->post( 'statuses/update_with_media.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
The message I get from twitter is :
Ooophs, we got an error: Update user status failed! Twitter returned an error. 403 Forbidden: The request is understood, but it has been refused.
How Can I get more precise info about error ?
Does anybody allready success in sending a picture attached to a tweet ?
Thanks !
Hugo
Thanks #Heena for making myself wake up on this question, I MADE IT ;)
function setUserStatus( $status )
{
if(is_array($status))
{
$message = $status["message"];
$image_path = $status["image_path"];
}
else
{
$message = $status;
$image_path = null;
}
$media_id = null;
# https://dev.twitter.com/rest/reference/get/help/configuration
$twitter_photo_size_limit = 3145728;
if($image_path!==null)
{
if(file_exists($image_path))
{
if(filesize($image_path) < $twitter_photo_size_limit)
{
# Backup base_url
$original_base_url = $this->api->api_base_url;
# Need to change base_url for uploading media
$this->api->api_base_url = "https://upload.twitter.com/1.1/";
# Call Twitter API media/upload.json
$parameters = array('media' => base64_encode(file_get_contents($image_path)) );
$response = $this->api->post( 'media/upload.json', $parameters );
error_log("Twitter upload response : ".print_r($response, true));
# Restore base_url
$this->api->api_base_url = $original_base_url;
# Retrieve media_id from response
if(isset($response->media_id))
{
$media_id = $response->media_id;
error_log("Twitter media_id : ".$media_id);
}
}
else
{
error_log("Twitter does not accept files larger than ".$twitter_photo_size_limit.". Check ".$image_path);
}
}
else
{
error_log("Can't send file ".$image_path." to Twitter cause does not exist ... ");
}
}
if($media_id!==null)
{
$parameters = array( 'status' => $message, 'media_ids' => $media_id );
}
else
{
$parameters = array( 'status' => $message);
}
$response = $this->api->post( 'statuses/update.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
To make it work you have to do like this :
$config = "/path_to_hybridauth_config.php";
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Twitter" );
$twitter_status = array(
"message" => "Hi there! this is just a random update to test some stuff",
"image_path" => "/path_to_your_image.jpg"
);
$res = $adapter->setUserStatus( $twitter_status );
Enjoy !
I did not understand it for hybridauth then I used this library
https://github.com/J7mbo/twitter-api-php/archive/master.zip
Then I was successful using code below: (appears elsewhere in stack)
<?php
require_once('TwitterAPIExchange.php');
$settings= array(
'oauth_access_token' => '';
'oauth_access_secret' => '';
'consumer_key' => '';
'consumer_secret' => '';
// paste your keys above properly
)
$url_media = "https://api.twitter.com/1.1/statuses/update_with_media.json";
$requestMethod = "POST";
$tweetmsg = $_POST['post_description']; //POST data from upload form
$twimg = $_FILES['pictureFile']['tmp_name']; // POST data of file upload
$postfields = array(
'status' => $tweetmsg,
'media[]' => '#' . $twimg
);
try {
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url_media, $requestMethod)
->setPostfields($postfields)
->performRequest();
echo "You just tweeted with an image";
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>
Hie guys i need help with my code I don't know how to do it. I have a form where a student selects an exam body, if the exam body selected is zimsec marks should be empty and if the exam body is cambridge marks should not be empty and should take a range depending on grade. validMarks is the function I am using to validate marks and it stopped working when i allowed marks to be empty so as to accomodate Zimsec.
My add.ctp
echo "<td>";
echo $this->Form->label('Mark(%): ');
echo "</td><td>";
echo $this->Form->input("ApplicantOlevelQualification.mark.$s",array('label'=>''));
echo "</td></tr>";
echo $this->Form->label('Exam Body<font color=red>*</font>');
$exambody=array(
'ZIMSEC'=>'ZIMSEC',
'CAMBRIDGE'=>'CAMBRIDGE'
);
echo $this->Form->select('exam_body_code',$exambody,array('empty'=>'Please Select','selected'=>false,'label'=>'Exam Body<font color="red">*</font>'));
My Controller
$exam_body_code = $this->data['ApplicantOlevelQualification']['exam_body_code'];
'mark' => $this->data['ApplicantOlevelQualification']['mark'][$i],
My model
'exam_body_code' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'mark' => array(
//'numeric' => array(
//'rule' => array('numeric'),
'rule' => array('validMarks'),
'message' => 'Wrong mark for this grade, please try again.',
'allowEmpty' => true,
// ),
),
public function validMarks($check) {
$grade=($this->data['ApplicantOlevelQualification']['grade']);
$mark=($this->data['ApplicantOlevelQualification']['mark']);
//var_dump($mark);
if($grade== 'A' && $mark>74) {
// $this->validationError( 'grade', 'Grade A must be greater than or equal to 75%' );
//Access $this->data and $check to compare your marks and grade;
return true;
} elseif( ($grade)== 'B' && ($mark>64)) {
return true;
} elseif( ($grade)== 'C' && ($mark)>50) {
return true;
} elseif( ($grade)== 'D' && ($mark)>40) {
return true;
} elseif( ($grade)== 'E' && ($mark)>30) {
return true;
} elseif( ($grade)== 'U' && ($mark)>0) {
return true;
} else {
return false;
}
//Access $this->data and $check to compare your marks and grade..
}
if the exam body selected is zimsec marks should be empty and if the exam body is cambridge marks should not be empty and should take a range...
In that case you should split validation into 2 functions:
function emptyIfZimsec($data) {
return $this->data['ApplicantOlevelQualification']['exam_body_code'] != 'ZIMSEC'
|| empty($this->data['ApplicantOlevelQualification']['mark']);
}
function validMarks($data) {
if ($this->data['ApplicantOlevelQualification']['exam_body_code'] != 'CAMBRIDGE')
return true;
...
emptyIfZimsec will result in a validation error if the code is ZIMSEC and mark is not empty. and validMarks will check CAMBRIDGE marks (and skip if ZIMSEC)
This way you can also output separate validation error messages for each case.
Hope this helps.