Ajax response not displaying anything in view file (Yii) - php

I have a file ( _gen.php) that is in my view that sends selected data to the controller file for verification:
$('#validate').on('click',function(){
var data = []; // data container
// collect all the checked checkboxes and their associated attributes
$("table#subsection_table input[type='checkbox']:checked").each(function(){
data.push({
section : $(this).data('sectionid'),
subsection : $(this).val(),
year : $(this).data('year')
})
});
// JSON it so that it can be passed via Ajax call to a php page
var data = JSON.stringify(data);
$.ajax({
url : "<?php echo Yii::app()->createAbsoluteUrl("scheduler/ScheduleValidation"); ?>",
type: "POST",
data : "myData=" + data,
success : function(data)
{
$("#ajax-results").html(data);
$("#ajax-results").dialog({ width: 500, height: 500})
},
error: function()
{
alert("there was an error")
}
})
console.log(JSON.stringify(data));
$('#dialog').html(data).dialog({ width: 500, heigh: 500});
});
Now #ajax-result is the id of one of my div tag after my button ( last thing displayed on the page).
As for the controller function, I do know it handles the data fine and the sql call correctly ( I made sure of it). However when I call renderPartial it will call my _ajax.php file correctly but it will only displayed it in an alert box, not to the #ajax-result tag. The controller function:
public function actionScheduleValidation()
{
print_r("in ajax");
$post_data = $_POST['myData'];
$decodedData = json_decode($post_data, true);
//$course = [[[]]];
$course=[];
$counter = 0;
//Save the years associated to sections chosen
foreach ($decodedData as $key) {
$tutOrLab = null;
$lec = null;
$currentYear = null;
foreach ($key as $id => $number) {
if ($id == 'year') {
$currentYear = $number;
} elseif ($id == 'subsection') {
$tutOrLab = Yii::app()->db->createCommand()
->select('courseID,kind,days,start_time,end_time,semester')
->from($id)
->where('id=' . $number)
->queryRow();
} else
$lec = Yii::app()->db->createCommand()
->select('courseID,kind,days,start_time,end_time,semester')
->from($id)
->where('id=' . $number)
->queryRow();
}
print_r(gettype($lec['start_time']));
$lecture = new Lecture($lec['courseID'],$lec['kind'],$lec['days'],$lec['start_time'],$lec['end_time'],$lec['semester'],$currentYear);
print_r(gettype($lecture->getStartTime()));
// WILL ACTUALLY DISPLAY SOMETHING
$tutorial = new TutorialAndLab($tutOrLab['courseID'],$tutOrLab['kind'],$tutOrLab['days'],$tutOrLab['start_time'],$tutOrLab['end_time'],$tutOrLab['semester'],$currentYear);
$course[$counter] = new CourseObj($lecture,$tutorial);
$counter++;
}
$courseYear1Fall = [];
$courseYear1Winter = [];
$courseYear2Fall = [];
$courseYear2Winter = [];
$courseYear3Fall = [];
$courseYear3Winter = [];
$courseYear4Fall = [];
$courseYear4Winter = [];
if($course != null) {
for ($i = 0; $i < count($course); $i++) {
if ($course[$i]->getLecture()->getYear() == '1') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear1Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W') {
array_push($courseYear1Winter, $course[$i]);
}
} elseif ($course[$i]->getLecture()->getYear() == '2') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear2Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W')
array_push($courseYear2Winter, $course[$i]);
} elseif ($course[$i]->getLecture()->getYear() == '3') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear3Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W') {
array_push($courseYear3Winter, $course[$i]);
}
} elseif ($course[$i]->getLecture()->getYear() == '4') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear4Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W') {
array_push($courseYear4Winter, $course[$i]);
}
}
}
$counter2=0;
$errorArr = [];
if($courseYear1Fall != null){
$fallErr = verification($courseYear1Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
elseif($courseYear1Winter != null) {
$winterErr = verification($courseYear1Winter);
$errorArr[$counter2] = $winterErr;
$counter2++;
}
if($courseYear2Fall != null) {
$fallErr = verification($courseYear2Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
if($courseYear2Winter != null) {
$winterErr = verification($courseYear3Fall);
$errorArr[$counter2] = $winterErr;
$counter2++;
}
if($courseYear3Winter != null) {
$fallErr = verification($courseYear3Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
if($courseYear3Fall != null) {
$winterErr = verification($courseYear3Winter);
$errorArr[$counter2] = $winterErr;
$counter2++;
}
if($courseYear4Fall != null) {
$fallErr = verification($courseYear4Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
if($courseYear4Winter != null) {
$winterErr = verification($courseYear4Winter);
$errorArr[$counter2] = $winterErr;
}
$this->renderPartial('_ajax', array(
'data' => $errorArr,
)
);
}
Any idea on how to append it to my original (_gen.php) html code?

Your ajax call is missing semi-colon.
And probably as a good practise you should not be naming both request and response variable "data".

Related

Can you help me to correct this "net::ERR_TOO_MANY_REDIRECTS" Chrome error?

I have a problem with ajax POST when my website is integrated in iframe. Only some users have the error in Chrome. I put a screenshot of the console error (send by user).
Screenshot
The concerned javascript is in /js/open.min.js :
/* (c) 2019 Lockee.fr */
function openLock(){
if($("#inputcode").val() != ""){
$.ajax({
type: 'POST',
async: false,
cache: false,
url: homeURL + 'ajax-open.php',
dataType: "json",
data: {id : $("#inputid").val(), code : $("#inputcode").val(), top : $("#inputtop").val()},
timeout: 3000,
success: function(data){
console.log(data);
if(data.open == 0){
$("#wrongcode").fadeIn(0).delay(1500).fadeOut(0);
} else {
if(data.redirect == 1){
if(data.top == 1){
top.location.href = data.content;
} else {
location.href = data.content;
}
} else {
$("#contentlock").html(data.content);
$("#isclose").hide();
$("#isopen").show();
$("#report").show();
}
}
}
});
}
}
function closeLock(){
lock.clearCode();
$("#contentlock").html("");
$("#isopen").hide();
$("#report").hide();
$("#isclose").show();
}
The PHP code :
<?php
include("functions.php");
if((!empty($_POST["id"]))&&(!empty($_POST["code"]))){
$id = addslashes($_POST['id']);
$code = htmlspecialchars($_POST['code']);
$infos = lockInfo($id);
if(($infos['action'] == "L")&&($_POST['top'] == 1)){
$top = 1;
$redirect = 1;
$content = $infos["content"];
} else if($infos['action'] == "L"){
$redirect = 1;
$top = 0;
$content = $infos["content"];
} else {
$redirect = 0;
$top = 0;
$content = displayContent($infos["action"], $infos["content"], $infos["linked"], false);
}
$open = 1;
if($infos['code'] == $code){
$open = 1;
} else {
$open = 0;
}
} else {
$open = 0;
}
if($open == 0){
$content = "";
}
$file = ["open" => $open, "content" => $content, "redirect" => $redirect, "top" => $top];
header('Content-Type: application/json');
echo json_encode($file);
?>
This is an example which is not working for some users :
The code to open integrated lock is "123"
Thank's for your help !

Value not saving outside foreach loop

I update my code from PHP 5 to PHP 7 and i got problem with foreach loop. I loocked wor answers here, but none is working. Or i dont understand where i have problem
function getStructure($pid = 0, $expand = array(), $alevel = 0)
{
$struct = array();
if ( $alevel > $this->levelCount) $this->levelCount = (int)$alevel;
$str = $this->dbStructure->getStructure($pid);
foreach ($str as &$row)
{
if ($row["type"] == STRUCT_PAGE)
{
$row["editLink"] = "editPage";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_MODULE)
{
$row["editLink"] = "editModule";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_LINK)
{
$row["editLink"] = "editLink";
$row["target"] = "_blank";
}
elseif ($row["type"] == STRUCT_CATALOG)
{
$row["editLink"] = "editCatalog";
$row["target"] = "_self";
}
$row["childrens"] = $this->getStructure((int)$row["id"], $expand, $alevel+1);
if ($row["type"] == STRUCT_CATALOG and isset($row["childrens"][0]["shortcut"]))
{
$row["shortcut"] = $row["childrens"][0]["shortcut"];
$row["target"] = $row["childrens"][0]["type"] == STRUCT_LINK ? "_blank" : "_self";
}
$struct[] = $row;
}
unset($row);
return $struct;
}
All the time $struct is NULL and I need to be multidimensional array
This code by itself is good. Has no problems, only ampersand is not needet. The problem was in different place. Sorry for spam

How to correctly write a foreach for $clientList in TS3AntiVPN application?

I download a TS3AntiVPN but it shoes an error. I use a Linux Server running Debian 9 Plesk installed.
PHP Warning: Invalid argument supplied for foreach() in
/var/www/vhosts/suspectgaming.de/tsweb.suspectgaming.de/antivpn/bot.php
on line 29
How do I solve this problem?
<?php
require("ts3admin.class.php");
$ignore_groups = array('1',); // now supports one input and array input
$msg_kick = "VPN";
$login_query = "serveradmin";
$pass_query = "";
$adres_ip = "94.249.254.216";
$query_port = "10011";
$port_ts = "9987";
$nom_bot = "AntiVPN";
$ts = new ts3Admin($adres_ip, $query_port);
if(!$ts->getElement('success', $ts->connect())) {
die("Anti-Proxy");
}
$ts->login($login_query, $pass_query);
$ts->selectServer($port_ts);
$ts->setName($nom_bot);
while(true) {
sleep(1);
$clientList = $ts->clientList("-ip -groups");
foreach($clientList['data'] as $val) {
$groups = explode(",", $val['client_servergroups'] );
if(is_array($ignore_groups)){
foreach($ignore_groups as $ig){
if(in_array($ig, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
}else{
if(in_array($ignore_groups, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
$file = file_get_contents('https://api.xdefcon.com/proxy/check/?ip='.$val['connection_client_ip'].'');
$file = json_decode($file, true);
if($file['message'] == "Proxy detected.") {
$ts->clientKick($val['clid'], "server", $msg_kick);
}
}
}
?>
You might be missing data in your first array. You may add an if statement to check if there is data in your $clientList['data'] var:
if (is_array($clientList['data'])) {
}
Or you might also check if sizeof(); of your array is larger than a number, you may desire.
if (is_array($clientList['data']) && sizeof($clientList['data']) > 0) {
}
Code
require "ts3admin.class.php";
$ignore_groups = array('1'); // now supports one input and array input
$msg_kick = "VPN";
$login_query = "serveradmin";
$pass_query = "";
$adres_ip = "94.249.254.216";
$query_port = "10011";
$port_ts = "9987";
$nom_bot = "AntiVPN";
$ts = new ts3Admin($adres_ip, $query_port);
if (!$ts->getElement('success', $ts->connect())) {
die("Anti-Proxy");
}
$ts->login($login_query, $pass_query);
$ts->selectServer($port_ts);
$ts->setName($nom_bot);
while (true) {
sleep(1);
$clientList = $ts->clientList("-ip -groups");
if (is_array($clientList['data']) && sizeof($clientList['data']) > 0) {
foreach ($clientList['data'] as $val) {
$groups = explode(",", $val['client_servergroups']);
if (is_array($ignore_groups)) {
foreach ($ignore_groups as $ig) {
if (in_array($ig, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
} else {
if (in_array($ignore_groups, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
$file = file_get_contents('https://api.xdefcon.com/proxy/check/?ip=' . $val['connection_client_ip'] . '');
$file = json_decode($file, true);
if ($file['message'] == "Proxy detected.") {
$ts->clientKick($val['clid'], "server", $msg_kick);
}
}
} else {
echo "There might be no data in Client List";
}
}

I am getting array index in query string when use remote in jquery.How can I get its value in laravel controller?

I have send a get request
jQuery.validator.addClassRules({
termName:{
required: true,
maxlength:50,
unique:true,
/*termValidate : true,*/
remote: {
url: "/term/unique",
type: "get",
data: {
memberId: function () {
return $("input[name='member_id']").val();
},
},
dataFilter: function (data) {
var json = JSON.parse(data);
if (json.id!=0) {
return "\"" + "{{Lang::get('messages.membership_name_already_taken')}}" + "\"";
} else {
return 'true';
}
}
}
}
in controller
public function checkLimit()
{
$membership = Tenure::all()->where('name', Input::get('termName'))->first();
if (Input::get('memberId')!=" ") {
$id = Input::get('memberId');
} else {
$id = 0;
}
if($membership == null && $id == 0){
$membership = ['id' => '0'];
} else {
if ($membership->id == $id) {
$membership = ['id' => '0'];
}
}
return Response::json($membership);
}
i have used Input::get('termName') to get termName.but when i checked my querystring its like
http://localhost:8088/term/unique?term_name[0]=vfvfvfvffvff&memberId=
how can i get termname in controller?
Use this method
public function checkLimit(Request $request)
{
$membership = Tenure::all()->where('name', $request->term_name->first());
if ($request->memberId!="") {
$id = $request->memberId;
} else {
$id = 0;
}
if($membership == null && $id == 0){
$membership = ['id' => '0'];
} else {
if ($membership->id == $id) {
$membership = ['id' => '0'];
}
}
return Response::json($membership);
}

MethodNotAllowedHttpException [AJAX]!

I have some problems with routes.
Code: MethodNotAllowedHttpException in RouteCollection.php line 219.
I use ajax and laravel 5.1. I try use google, but I do not understand, I try method "path", and in ajax change "type" to "method". I try GET, but no work.
My ajax:
$.ajax({
type: 'POST',
url: '/placeBet',
dataType: 'json',
data: {
ammount: ammount,
color: color
},
headers: {
'X-CSRF-TOKEN': $('#_token').val()
},
success: function (data) {
if (data['color'] == 'red') {
var currentPlaced = parseInt($('.user_red').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_red').html(currentPlaced);
}
if (data['placedMuch']) {
alertify.error('Max 4 bets in round!');
}
if (data['color'] == 'purple') {
var currentPlaced = parseInt($('.user_black').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_black').html(currentPlaced);
}
if (data['color'] == 'gold') {
var currentPlaced = parseInt($('.user_gold').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_gold').html(currentPlaced);
}
if (data['color'] == 'green') {
var currentPlaced = parseInt($('.user_green').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_green').html(currentPlaced);
}
if (data['baaad'] == true) {
alertify.error('Niu niu!');
return;
}
if (data['improvements'] == true) {
alertify.error('We are working on improvements.');
return;
}
if (data['toLow'] == true) {
alertify.error('Minimum bet is 200 diamonds!');
return;
}
if (data['can_bet'] == false) {
alertify.error('You have withdraw request pending, you cannot bet!');
return;
}
if (data['placed'] != false && data['coins'] != false) {
var coins = data['coins'];
var htmlo = '<div class="chat_message"><div class="top"><div class="right_info">Info Bot</div></div><div class="message">You spent ' + ammount + ' diamonds on ' + data['color'] + '.</div></div>';
$('#chatmessages').append(htmlo);
$('.recents_box').mCustomScrollbar("scrollTo", 'bottom');
$({countNum: $('#currentBallance').html()}).animate({countNum: coins}, {
duration: 1000,
easing: 'linear',
step: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
},
complete: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
}
});
} else if (data['placed'] != false && data['coins'] == '0') {
var coins = data['coins'];
var htmlo = '<div class="chat_message"><div class="top"><div class="right_info">Info Bot</div></div><div class="message">You spent all your diamonds on ' + data['color'] + '.</div></div>';
$('#chatmessages').append(htmlo);
('.recents_box').mCustomScrollbar("scrollTo", 'bottom');
$({countNum: $('#currentBallance').html()}).animate({countNum: coins}, {
duration: 1000,
easing: 'linear',
step: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
},
complete: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
}
});
// swal('Yea', 'You placed a bet to ' + color + '. Your current coins are : ' + coins + '!', 'success');
// $('#betammount').val(0);
} else {
if (data['logged'] == false) {
alertify.error('You need to be log in to use this option!');
} else if (data['coins'] == false) {
alertify.error('You are not that rich!');
// $('#betammount').val(0);
} else if (data['coins'] == '0') {
alertify.error('You are empty!');
//$('#betammount').val(0);
}
}
}
});
My routes:
Route::post('/placeBet', ['as' => 'placeBet', 'uses' => 'RouletteController#placeBet']);
My RoulleteController:
public function placeBet(Request $request)
{
$info = [];
if (Auth::check()) {
$lastID = DB::select("SELECT * FROM roulette_history ORDER BY id DESC LIMIT 1");
$roundID = $lastID[0]->id;
$steamID = Auth::user()->steamId64;
$ammount = $request->All()['ammount'];
$getCountPlaced = \App\placedBets::where('gameID', $roundID)->where('userID64', Auth::user()->steamId64)->count();
if($getCountPlaced > 3) {
$info['placedMuch'] = true;
$info = json_encode($info);
return $info;
}
if($ammount < 1 || !is_numeric($ammount)) {
$info['baaad'] = true;
$info = json_encode($info);
return $info;
}
if ($ammount < 200) {
$info['toLow'] = true;
$info = json_encode($info);
return $info;
}
if(Auth::user()->global_banned > 0) {
$info['baaad'] = true;
$info = json_encode($info);
return $info;
}
$color = $request->All()['color'];
if($color == 'black') {
$color = 'purple';
}
$user_info = \App\User::where('steamId64', Auth::user()->steamId64)->first();
$active_ofer = \App\ofers::where('userID', Auth::user()->steamId64)->count();
$info['active_ofer'] = $active_ofer;
$user_coins = $user_info->coins;
if ($user_coins < $ammount) {
$info['coins'] = false;
$info['placed'] = false;
} else {
$user_coins = $user_coins - $ammount;
$siteProfit = \App\profit::first();
$siteProfitTotal = $siteProfit->siteProfit;
$siteProfitTotal = intval($siteProfitTotal) + intval($ammount);
$updateProfit = DB::update("UPDATE siteProfit SET siteProfit='$siteProfitTotal'");
$user_update = \App\User::where('steamId64', Auth::user()->steamId64)->update(['coins' => $user_coins]);
$info['coins'] = $user_coins;
$active_bet = DB::select("SELECT * FROM roulette_history ORDER BY id DESC LIMIT 1");
$game_id = $active_bet[0]->id;
$placed = DB::insert('insert into placed_bets (color, userID64, ammount, gameID, avatar,url,nick,isStreamer,streamLink) values (?, ?, ?, ?,?,?,?,?,?)', [$color, $steamID, $ammount, $game_id, $user_info->avatar, $user_info->url, $user_info->nick,$user_info->isStreamer,$user_info->steamLink]);
$info['placed'] = true;
$info['ammount'] = $ammount;
$info['color'] = $color;
$info['count'] = $getCountPlaced;
}
$info['logged'] = true;
} else {
$info['coins'] = 0;
$info['logged'] = false;
$info['placed'] = false;
}
$info = json_encode($info);
return $info;
}
If u need source, i can get for us!
In your ajax call, change
$.ajax({
type: 'POST',
to
$.ajax({
method: 'POST',

Categories