I want to Show My data in Popup,Once User Selected Department Showing that
Staff's names related to user Selected Department using Ajax,Geeting
data's Correctly But Am showing that Staff's names in Eselect2 Widget
Multiple option in Yii,that Eselect2 Design Not coming Its showing normal
Select Dropdown user Choose multiple choice using ctrl Keys .
My Codings, in that Div staff I am showing that eselect2 widget data's.
Ajax Coding
<div id ="staffs></div>
function selectstaff(id)
{
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("user/users/ajaxselectstaff"); ?>',
data: 'id=' + id,
success: function (packages) {
$('#staffs').html(packages);
}
});
}
Controller Coding
public function actionAjaxselectstaff() {
$id = Yii::app()->request->getPost('id');
$model = Users::model()->getAllStaffDepartment($id);
$this->renderPartial('ajaxselect', array('model' => $model));
}
MOdel Coding,
public function getAllStaffDepartment($id, $type = '') {
$model = UserAccount::model()->findAll('department_code=:id', array(':id' => $id));
$userid = "";
$result = "";
if (isset($model)) {
foreach ($model as $data) {
$userid .= $data->user_id . ",";
}
}
$userid = trim($userid, ',');
if ($userid != "") {
$criteria = new CDbCriteria();
$criteria->condition = "user_role_id!=" . Yii::app()->mconstant->CONST_FIVE . " AND user_role_id!= " . Yii::app()->mconstant->CONST_SIX . " AND user_role_id!= " . Yii::app()->mconstant->CONST_NINE . " AND user_id IN (" . $userid . ")";
$result = Users::model()->findAll($criteria);
$data = CHtml::listData($result, 'user_id', 'real_name');
return $data;
} else {
return false;
}
}
Ajaxselect page:
<?php
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
if ($model) {
?>
<?php
$this->widget('ext.select2.ESelect2', array(
'name' => 'users',
'id' => 'users',
'data' => $model,
'htmlOptions' => array(
'multiple' => true,
'placeholder' => 'Select Users',
),
));
?>
<?php
} else {
echo "No Staff's Found";
}
?>
what's wrong in my code ? Am changes the page to render eselect2 widget design getting properly but render partial eselect2 design not getting,
There is small change in controller which is mention below.
public function actionAjaxselectstaff() {
$id = Yii::app()->request->getPost('id');
$model = Users::model()->getAllStaffDepartment($id);
$this->renderPartial('ajaxselect', array('model' => $model) ,false , true);
}
Please find description of third and forth paramerter of renderPartial in below link : http://www.yiiframework.com/doc/api/1.1/CController#renderPartial-detail
Related
It seems like Instagram has changed certain things, because I have tried several codes on my html website to show the amount of Instagram followers on a button, but nothing works.
I tried this:
<?php
$account='XXX';
$instagramsource=file_get_contents('https://instagram.com/' . $account);
preg_match_all('/"userInteractionCount":"(.*?)"/', $instagramsource, $count);
$followcount=$count[1][0];
echo "$account instagram account has $followcount followers";
?>
Also this
<?php
$otherPage = 'XXX';
$response = file_get_contents("https://www.instagram.com/$otherPage/?__a=1");
if ($response !== false) {
$data = json_decode($response, true);
if ($data !== null) {
$follows = $data['graphql']['user']['edge_follow']['count'];
$followedBy = $data['graphql']['user']['edge_followed_by']['count'];
echo $follows . ' and ' . $followedBy;
}
}
?>
And this ...
<?php
$url = "https://www.instagram.com/XXX";
$json = file_get_contents($url);
$obj = json_decode($json, true);
$content = $obj['query']['results']['script']['content'];
$content = str_replace("window._sharedData =", "", $content);
$content = str_replace(";", "", $content);
$content = trim($content);
$json = json_decode($content);
$instagram_follower_count = $json->entry_data->ProfilePage{0}->user->followed_by->count;
?>
And finally this:
<?php
$username = 'XXX';
$response = #file_get_contents( "https://www.instagram.com/$username/?__a=1" );
if ( $response !== false ) {
$data = json_decode( $response, true );
if ( $data !== null ) {
$follows = $data['graphql']['user']['edge_follow']['count'];
$followedBy = $data['graphql']['user']['edge_followed_by']['count'];
echo 'XXX follows:' . $follows . ' and is followed by: ' . $followedBy;
}
}
?>
None works.
Can anyone indicate what would work in 2021, please?
Thanks.
It's because the url https://www.instagram.com/$username/?__a=1 is redirecting to login page & giving u a html response
You can check it by echo $response
These posts will help you link1,link2
Instagram blocked access via __a=1 parameter since 2018-04-12. __a=1 must be replaced by JS and Ajax bypass. I've looked for an alternative solution. You can use javascript code inside php. For example:
async function instagramFollowers () {
const followers = []
try {
const userInfoSource = await Axios.get('https://www.instagram.com/123/')
const jsonObject = userInfoSource.data.match(/<script type="text\/javascript">window\._sharedData = (.*)<\/script>/)[1].slice(0, -1)
const userInfo = JSON.parse(jsonObject)
const mediaArray = userInfo.entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges.splice(0, 10)
for (let media of mediaArray) {
const node = media.node
followers.push(node.thumbnail_src)
}
} catch (e) {
console.error('Unable to retrieve Followers. Reason: ' + e.toString())
}
return followers
}
Other helpful links: how to write javascript code inside php
https://code.tutsplus.com/tutorials/how-to-use-ajax-in-php-and-jquery--cms-32494
I have a simple section in which I am displaying data from the database,
If the user clicks eg construction and selects eg Algeria, I am displaying [251, 211,712] if a user clicks eg Power and selects eg. Egypt I am displaying [406, 228,559] etc
Now I want if the user clicks the button All available industries and select eg. Algeria I want to display this [251+203+130, 211,712+179,877+154,946] in a simple way like this in SQL
SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value FROM `meed` WHERE Countries = 'Algeria'
Which give me this [611, 546535]
Here is my solution
HTML
<div id="interactive-layers">
<div buttonid="43" class="video-btns">
<span class="label">Construction</span></div>
<div buttonid="44" class="video-btns">
<span class="label">Power</span></div>
<div buttonid="45" class="video-btns">
<span class="label">Oil</span></div>
<div buttonid="103" class="video-btns">
<span class="label">All available industries</span>
</div>
</div>
Here is js ajax
$("#interactive-layers").on("click", ".video-btns", function(){
if( $(e.target).find("span.label").html()=="Confirm" ) {
var selectedCountries = [];
$('.video-btns .selected').each(function () {
selectedCountries.push( $(this).parent().find("span.label").html() ) ;
});
if( selectedCountries.length>0 ) {
if(selectedCountries.indexOf("All available countries")>-1) {
selectedCountries = [];
}
} else {
return;
}
var ajaxurl = "";
if(selectedCountries.length>0) {
ajaxurl = "data.php";
} else {
ajaxurl = "dataall.php";
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
countries: selectedCountries.join(","),
sector: selectedSector
},
success: function(result){
console.log(result);
result = JSON.parse(result);
$(".video-btns").each(function () {
var getBtn = $(this).attr('buttonid');
if (getBtn == 106) {
var totalProjects = $("<span class='totalprojects'>"+ result[0] + "</span>");
$(this).append(totalProjects)
}else if(getBtn ==107){
var resultBudget = result[1]
var totalBudgets = $("<span class='totalbudget'>"+ '$m' +" " + resultBudget +"</span>");
$(this).append( totalBudgets)
}
});
return;
}
});
}
});
UPDATE Here is Updated data.php
<?php
$selectedSectorByUser = $_POST['sector'];
$countries = explode(",", $_POST['countries']);
echo '$countries';
$conn = mysqli_connect("localhost", "root", "", "meedadb");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = array();
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result))
{
if($row['Sector']==$selectedSectorByUser && in_array($row['Countries'],$countries ) ) {
$totalProjects+= $row['SumofNoOfProjects'];
$totalBudget+= $row['SumofTotalBudgetValue'];
}elseif($selectedSectorByUser =="All available industries"){
$result = mysqli_query($conn,
"SELECT sum(SumofNoOfProjects) as 'SumofNoOfProjects, sum(SumofTotalBudgetValue) as SumofTotalBudgetValue
FROM `meed`
WHERE Countries = '$countries'");
while( $row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
echo json_encode([ $row['SumofNoOfProjects,'], $row['SumofTotalBudgetValue '] ] );
exit;
}
exit;
}
}
echo json_encode([ $totalProjects, $totalBudget ] );
exit();
?>
Now when the user clicks All available industries btn and selects a country I get the following error
b>Fatal error: Uncaught Error: Cannot use object of type mysqli_result as array in C:\custom-xammp\htdocs\editor\data.php:23
What do I need to change to get what I want? any help or suggestion will be appreciated,
you should fecth a row (at least)
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($conn,
"SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value
FROM `meed`
WHERE Countries = '$countries'");
while( $row=mysqli_fetch_array($result,MYSQLI_ASSOC);) {
echo json_encode([ $row['sum_projects'], $row['sum_value'] ] );
exit;
}
for the multiple countries
Asuming you $_POST['countries'] contains "'Egypt','Algerie'"
then you could use a query as
"SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value
FROM `meed`
WHERE Countries IN (" . $_POST['countries'] . ");"
this is my first time on this site so I'll cut to chase.
I've been working on a fixed assets control web system using PHP, AJAX, jquery and MySQL as database (the project structure was made by following the tutorial from this website: https://www.itechempires.com/2016/07/pdo-crud-operations-using-php-bootstrap/ ), where such items are registered along with the categories to which each asset belongs, the transactions made by the users within the company and the reports generated by each transaction.
Currently I'm stuck with the dropdowns since I tried anything I could to make them work but without the results I've been looking for, which is:
in a modal there's a form where an asset is going to be added with its related information, two of those details are categories and subcategories which are handled by dependent dropdowns, the dropdown regarding to subcategories will be displayed once a category is selected.
The code snippets will be up for review which will be focused on the ones related to the dropdowns:
Tables
grupo (group or category)
id_grp (group id,autoincremented, not visible by the user)
codigo_grp (code)
nombre_grp (name)
subgeupo (subgroup or subcategory)
id_sgrp (subgroup id, autoincremented, not visible by the user)
codigo_sgrp (code)
nombre_sgrp (name)
vidaUtil_sgrp (useful life)
id_grp (group id, foreign key)
libAF.php: Contains all queries for crud operations
/*
* Get group's id and name
*
* #return $id_grp, $nombre_grp
* */
public function populateSelGrp()
{
$query = $this->db->prepare("SELECT id_grp, nombre_grp FROM grupo");
$query->execute();
$data = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return $data;
}
/*
* Get sub-group's id and name
*
* #return $id_grp, $nombre_grp
* */
public function populateSelSgrp($id_grp)
{
$query = $this->db->prepare("SELECT * FROM subgrupo WHERE id_grp = :id_grp");
$query->bindParam("id_grp", $id_grp, PDO::PARAM_STR);
$query->execute();
$data = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return $data;
}
populateSelGrp.php: loads the categories on to the parent dropdown
<?php
require 'libAF.php';
$data = "";
$object = new CRUD();
$grupos = $object->populateSelGrp();
$data .= '<select id="select_grp" class="form-control" onchange="populateSelSgrp()">';
$data .= '<option value="0" disabled selected>Escoja grupo</option>';
if (count($grupos) > 0) {
foreach ($grupos as $grupo) {
$data .= '<option id="selected_grp" value="' . $grupo['id_grp'] . '"> ' . $grupo['nombre_grp'] . '</option>';
}
}
else
{
$data .= '<option>No hay opciones disponibles</option>';
}
$data .= '</select>';
echo $data;
?>
populateSelSgrp.php: loads the subcategories on to the child dropdown
<?php
require 'libAF.php';
if (isset($_POST['id_grp']) && isset($_POST['id_grp']) != "") {
$id_grp = $_POST['id_grp'];
$data = "";
$object = new CRUD();
$subgrupos = $object->populateSelSgrp($id_grp);
$data .= '<label for="select_sgrp">Sub-grupo</label>';
$data .= '<select id="select_sgrp" class="form-control">';
$data .= '<option value="0" disabled selected>Escoja sub-grupo</option>';
if (count($subgrupos) > 0) {
foreach ($subgrupos as $subgrupo) {
$data .= '<option value="' . $subgrupo['id_sgrp'] . '"> ' . $subgrupo['nombre_sgrp'] . '</option>';
}
}
else
{
$data .= '<option>No hay opciones disponibles</option>';
}
$data .= '</select>';
echo $data;
}
?>
scptAF.js: Contains the scripts needed to make the inputs work
function populateSelGrp(){
$.get("ajax/activoFijo/populateSelGrp.php", {
},
function (data, status) {
//load options to dropdown list
$(".option_grp").html(data);
}
);
}
function populateSelSgrp(id_grp){
$.ajax({
url: "ajax/activoFijo/populateSelSgrp.php",
method: "POST",
data:{id_grp: id_grp},
success:function(data){
$(".option_sgrp").html(data);
}
})
}
activos.php (assets): visible page where the user adds, removes or updates an asset.
<div class="form-group">
<label for="select_grp">Grupo</label>
<div class="option_grp"></div>
</div>
<div class="form-group">
<div class="option_sgrp"></div>
</div>
I finally found a solution for this mess, was a little code I had to add to the javaScript file to send the id to the second dropdown. Although I finally fixed my problem, I'd like to see other suggestions on how to tackle this problem.
Here's my snippet
scptAF.js
function populateSelGrp() {
$.get("ajax/activoFijo/populateSelGrp.php", {
},
function (data, status) {
//load options to dropdown list
$(".option_grp").html(data);
}
);
}
function changeGrpId(){
var id_grp = document.getElementById("select_grp").value;
populateSelSgrp(id_grp);
}
function populateSelSgrp(id_grp) {
$.ajax({
url: "ajax/activoFijo/populateSelSgrp.php",
method: "POST",
data:{id_grp: id_grp},
success:function(data){
$(".option_sgrp").html(data);
}
})
}
I'am trying to display same data using datatables server side processing at Codeigniter.I should use 'where' clause and i'am using Emran ul hadi script class.(Visit https://emranulhadi.wordpress.com/2014/06/05/join-and-extra-condition-support-at-datatables-library-ssp-class/#comment-196).
My controller script :
$sql_details = array(
'user' => 'root',
'pass' => '',
'db' => 'kreatx',
'host' => 'localhost'
);
$index = $this->uri->segment(3);
$table = 'user';
$columns = array(
array('db' => 'Name', 'dt' => 0),
array('db' => 'Lastname', 'dt' => 1),
array('db' => 'Email', 'dt' => 2),
array('db' => 'Username', 'dt' => 3),
array('db' => 'Password', 'dt' => 4)
);
$primaryKey = 'ID';
$this->load->model('employees_model');
$department = $this->employees_model->get_department($index);
require( 'SSP.php' );
$where = 'Department = '.$index.'';
echo json_encode(
SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns,
null ,$where )
);
My view script :
$('#employees').DataTable({
"responsive":true,
"processing":true,
"serverSide":true,
"searching":true,
"ordering":true,
"order":[],
"ajax":{
url:"<?php echo base_url() .
'employees/get_employees/'.$index.''; ?>",
type:"POST"
},
"columnDefs":[
{
"targets":[4],
"orderable":false,
},
],
});
Table is displaying correctly,with no errors.But search and order does'nt work.
If i try to search it just say prrocessing and show the same table.
Same problem with ordering.
Any sugesstion please ?
Thanks !
On your script you set "serverside" parameter to "true"
That means all the filtering and sorting needs to be in your php script. Every time you change the order or try to apply a filter, the dataTables javascript will send an ajax call to the php page you have listed under the ajax parameter. The ajax call will include everything you need inside of get or post variables that you can parse.
You need to write the code in php to parse the URL parameters and dynamically create a sql query that filters your database results.
I haven't done this in Codeignitor before but this is a quick example of what I would try in Laravel (note, you need to hard code your own database columns or if you're advanced then you can loop the code into an array of your database column names)
public function MyExampleJson(Request $request)
{
$len = $_GET['length'];
$start = $_GET['start'];
$select = "SELECT *,1,2 ";
$presql = " FROM entities a ";
$whereused = false;
if($_GET['search']['value']) {
$presql .= " WHERE (id LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column01 LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column02 LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column03 LIKE '%". $_GET['search']['value']."%' ";
$presql .= " OR column04 LIKE '%". $_GET['search']['value']."%' ";
$presql .= ") ";
$whereused = true;
}
$orderby = "";
$columns = array('column01','column02','column03','column04');
$order = $columns[$request->input('order.0.column')];
$dir = $request->input('order.0.dir');
$columnsearcharray = $request->columns;
foreach ($columnsearcharray as $key => $value)
{
if ($value['search']['value']) {
if ($whereused) {
$presql .= " AND ";
} else {
$presql .= " WHERE ";
$whereused = true;
}
$presql .= $columns[$key] . " LIKE '%" . $value['search']['value'] . "%' ";
}
}
$orderby = "Order By " . $order . " " . $dir;
$sql = $select.$presql.$orderby." LIMIT ".$start.",".$len;
$qcount = DB::select("SELECT COUNT(a.id) c".$presql);
$count = $qcount[0]->c;
$results = DB::select($sql);
$ret = [];
foreach ($results as $row) {
$r = [];
foreach ($row as $value) {
$r[] = $value;
}
$ret[] = $r;
}
$ret['data'] = $ret;
$ret['recordsTotal'] = $count;
$ret['iTotalDisplayRecords'] = $count;
$ret['recordsFiltered'] = count($ret);
$ret['draw'] = $_GET['draw'];
echo json_encode($ret);
}
I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. Ofcourse Ajax updates this list everytime the textbox gets edited.
Index.PHP calls all the other files, classes and HTML. But when the textbox gets updated, Ajax sends a POST variable to index.PHP because this is where the Search.PHP file with the class name SearchEngine gets called. But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice.
Index.php
<?php
require_once("cgi_bin/connection.php");
require_once("Database_Handler.Class.php");
require_once("HTML_Page.Class.php");
require_once("search.php");
$hostname_conn = "localhost";
$database_conn = "ajax";
$username_conn = "root";
$password_conn = "";
$db = new DatabaseHandler();
$conn = $db->openConnection($hostname_conn, $username_conn, $password_conn, $database_conn);
$IndexPage = new page();
echo $IndexPage->render();
$SearchEngine = new SearchEngine($conn);
?>
Please ignore the poor and unsecure database connection. I am currently transforming all my code to PDO and refining it but that is for later.
Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
And as final the Javascript
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "index.php", //Referring to index.php because this is where the class SearchEngine is called
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
note: HTML is being returned from the "page" class called inside Index.php
How do i not let everything get called twice?
Thank you,
EDIT: A new file was suggested where i direct the ajax url to AutoComplete.php
AutoComplete.PHP
Please explain what should be in the file and why. I am clueless.
Basically, just add a parameter to your Ajax call to tell the index.php its being called by Ajax, and then wrap an if-statement around the two lines that print out your actual index page:
if(!isset($_REQUEST['calledByAjax']))
{
$IndexPage = new page();
echo $IndexPage->render();
}
and in your Ajax call:
data: { query: query_value, calledByAjax: 'true' },
Or make another php page, like ajaxsearch.php that's the same as your index.php but lacking those two lines, and call that in your Ajax call.
First thing (this is a sample, not tested yet)
autocomplete.php
<?php
$search_string = $_POST['query'];
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
}
echo($output);
?>
autocomplete.js
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "autocomplete.php", //Here change the script for a separated file
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
} else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
search(); // call the function without setTimeout
}
});
});
Have luck :)