Using AJAX to Call PHP method within PHP file - javascript

Right now I have a dynamic form of sorts that allows a user to pick a category, type, and a subtype. This information will then be used in a PHP function (hopefully). All of this is within a PHP file.
I am hoping to use AJAX to call a function within that PHP file. I've seen ways to call a PHP file with AJAX from within an HTML document, but not from within a PHP document.
This is the relevant portion of my configs.php:
<?php
use FW\Config;
require_once 'setup.php';
function build($category, $type, $subtype){
//WANT TO GET HERE
}
function getTypes($dir) {
return array_diff(scandir($dir), array('..', '.'));
}
function getSubTypes($dir, $type) {
return array_diff(scandir("$dir//$type"), array('..', '.'));
}
function getVersions($dir, $type, $subType) {
return array_diff(scandir("$dir//$type//$subType"), array('..', '.'));
}
function getFileContents($dir, $type, $subtype, $file){
$path = "$dir/$type/$subtype/$file.txt";
$openFile = fopen($path, "r");
$content = fread($openFile, filesize($path));
fclose($openFile);
return split("/", $content)[0];
}
$project_dir = Config::$appConfig['project_file_dir']['scriptPath'];
$workflow_dir = Config::$appConfig['workflow_file_dir']['scriptPath'];
$project_types = getTypes($project_dir);
$project_subtypes = array();
$project_versions = array();
$workflow_types = getTypes($workflow_dir);
$workflow_subtypes = array();
$workflow_versions = array();
foreach ($project_types as $type) {
$project_subtypes[$type] = getSubTypes($project_dir, $type);
//#todo remove once folder structure is all setup
if ($type !== 'CD') continue;
foreach ($project_subtypes[$type] as $subType) {
$project_versions[$subType] = getVersions($project_dir, $type, $subType);
}
}
foreach ($workflow_types as $type) {
$workflow_subtypes[$type] = getSubTypes($workflow_dir, $type);
foreach ($workflow_subtypes[$type] as $subType) {
$workflow_versions[$subType] = getVersions($workflow_dir, $type, $subType);
}
}
function makeInfoSection($type, $subType, $versions, $dir) {
// list versions
$html .= '<h4>Available Versions</h4>';
$html .= '<ul class="list-group">';
foreach ($versions as $v) {
if (strpos($v, '.txt')) continue;
$html .= '<li class="list-group-item">';
$html .= '<span class="badge"><a href="#" style="color:orange">';
$html .= '<span class="glyphicon glyphicon-arrow-up" aria-hidden="true"';
$html .= 'onclick="build()">'; //#todo add onclick to trigger build()
$html .= '</span></a></span>';
$html .= $v;
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
function makeSection($parent, $prefix, $type, $subTypes) {
$headingID = 'heading-'.$type;
$bodyID = 'collapse-'.$prefix.$type;
$html = '<div class="panel panel-default" style="margin-bottom:10px;">';
$html .= '<div class="panel-heading" role="tab" id="'.$headingID.'">';
$html .= '<h4 class="panel-title">';
$html .= '<a role="button" data-toggle="collapse" data-parent="'.$parent;
$html .= '" href="#'.$bodyID.'" aria-expanded="true"';
$html .= 'aria-controls="'.$bodyID.'">'.$type;
$html .= '</a></h4></div>';
$html .= '<div id="'.$bodyID.'" class="panel-collapse collapse in" ';
$html .= 'role="tabpanel" aria-labelledby="'.$headingID.'">';
$html .= '<div class="list-group">';
foreach ($subTypes as $subType) {
$target = "tab-".$prefix.$type."-".$subType;
$html .= '<a href="#'.$target.'" class="list-group-item" ';
$html .= 'aria-controls="'.$target.'" role="tab" data-toggle="tab"';
$html .= '>'.$subType.'</a>';
}
$html .= '</div></div></div>';
return $html;
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<style>
.list-group-item.active, .list-group-item.active:hover {
background-color: white;
color: black;
}
</style>
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Configuration Management</h1>
</div>
<div class="row">
<div class="col-md-5 col-md-push-1 col-sm-6">
<ul class="nav nav-tabs" role="tablist" id="config-tabs">
<li role="presentation" class="active">
<a href="#project_list" aria-controls="project_list" role="tab" data-toggle="tab">
<h4>Project</h4>
</a>
</li>
<li role="presentation">
<a href="#workflow_list" aria-controls="workflow_list" role="tab" data-toggle="workflow_list">
<h4>Workflow</h4>
</a>
</li>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane active panel-group" id="project_list" role="tablist" aria-multiselectable="true">
<?php
foreach ($project_types as $type) {
echo makeSection( '#project_list', 'project-',$type, $project_subtypes[$type]);
}
?>
</div>
<div role="tabpanel" class="tab-pane panel-group" id="workflow_list" role="tablist" aria-multiselectable="true">
<?php
foreach ($workflow_types as $type) {
echo makeSection( '#workflow_list', 'workflow-',$type, $workflow_subtypes[$type]);
}
?>
</div>
</div>
</div>
<div class="col-md-5 col-md-push-1 col-sm-6">
<div id="tabs" class="tab-content" style="padding:0em 0em 0em 1em">
<?php
foreach ($project_types as $type) {
// #TODO remove once folder structure is all setup
if ($type !== 'CD') continue;
foreach ($project_subtypes[$type] as $subType) {
$html = "<div role ='tabpanel' class='tab-pane'";
$html .= "id='tab-project-".$type."-".$subType."'>";
$html .= makeInfoSection($type, $subType, $project_versions[$subType], $project_dir);
$html .= "</div>";
echo $html;
}
}
foreach ($workflow_types as $type) {
foreach ($workflow_subtypes[$type] as $subType) {
$html = "<div role ='tabpanel' class='tab-pane'";
$html .= "id='tab-workflow-".$type."-".$subType."'>";
$html .= makeInfoSection($type, $subType, $workflow_versions[$subType], $workflow_dir);
$html .= "</div>";
echo $html;
}
}
?>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="12345" crossorigin="anonymous"></script>
<script type="text/javascript">
function build (url, params, cb) {
url += "/buildWithParameters";
$.ajax({
type: 'POST',
url: url,
data: params,
success: cb
});
};
$('.collapse').collapse();
$('.list-group a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
$('#config-tabs a').click(function (e) {
e.preventDefault();
$(this).tab('show');
})
</script>
</body>
</html>
In the code above, I want to call the PHP function build. I have a JavaScript function build() which is called at the appropriate time and should have the AJAX to make the call. How would I go about this? And how would I pass the params?

Why not just have a separate file for the AJAX routine to call?
Anyway, to answer your question:
AJAX will send a data string to your PHP file, either via GET or POST. Standardize on one -- many folks prefer post.
As you know, the AJAX code block looks something like this (you will need to send the information required by your function):
var var_value = $('#my_element').val();
var cat = $('#category_element').val();
var typ = $('#type_element').val();
var sub = $('#subtype_element').val();
$.ajax({
type: 'post',
url: 'your_file.php',
data: 'var_name=' +var_value+ '&cat=' +cat+ '&typ=' +typ+ '&sub=' +sub,
success: function(d){
if (d.length) alert(d); //for testing - alerts anything your function ECHOs
}
});//end ajax
In your PHP file, just trap that var:
<?php
//Your existing PHP file contents go here. At bottom add:
if ( isset($_POST('var_name') ){
$category = $_POST('cat');
$type = $_POST('typ');
$subtype = $_POST('sub');
build($category, $type, $subtype);
}
See this post for some useful AJAX tips and simple examples

place below code after the php tag starts.
// check if ajax call
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
// call your php function here and return some data
$data = someFunction();
echo json_encode($data); // return data back in json format, can return in other format as well.
exit(); // do use exit here otherwise it will return the whole file code
}

Try this:
<?php
use FW\Config;
require_once 'setup.php';
//Check the get variable for the function being called.
if(isset($_GET['func']) AND function_exists($_GET['func'])){
$func=$_GET['func'];
$func();
//This is an ajax call, we really should exit here so we can let $func handle the ajax output;
exit;
}
function build($category, $type, $subtype){
//WANT TO GET HERE
}
function getTypes($dir) {
return array_diff(scandir($dir), array('..', '.'));
}
function getSubTypes($dir, $type) {
return array_diff(scandir("$dir//$type"), array('..', '.'));
}
function getVersions($dir, $type, $subType) {
return array_diff(scandir("$dir//$type//$subType"), array('..', '.'));
}
function getFileContents($dir, $type, $subtype, $file){
$path = "$dir/$type/$subtype/$file.txt";
$openFile = fopen($path, "r");
$content = fread($openFile, filesize($path));
fclose($openFile);
return split("/", $content)[0];
}
$project_dir = Config::$appConfig['project_file_dir']['scriptPath'];
$workflow_dir = Config::$appConfig['workflow_file_dir']['scriptPath'];
$project_types = getTypes($project_dir);
$project_subtypes = array();
$project_versions = array();
$workflow_types = getTypes($workflow_dir);
$workflow_subtypes = array();
$workflow_versions = array();
foreach ($project_types as $type) {
$project_subtypes[$type] = getSubTypes($project_dir, $type);
//#todo remove once folder structure is all setup
if ($type !== 'CD') continue;
foreach ($project_subtypes[$type] as $subType) {
$project_versions[$subType] = getVersions($project_dir, $type, $subType);
}
}
foreach ($workflow_types as $type) {
$workflow_subtypes[$type] = getSubTypes($workflow_dir, $type);
foreach ($workflow_subtypes[$type] as $subType) {
$workflow_versions[$subType] = getVersions($workflow_dir, $type, $subType);
}
}
function makeInfoSection($type, $subType, $versions, $dir) {
// list versions
$html .= '<h4>Available Versions</h4>';
$html .= '<ul class="list-group">';
foreach ($versions as $v) {
if (strpos($v, '.txt')) continue;
$html .= '<li class="list-group-item">';
$html .= '<span class="badge"><a href="#" style="color:orange">';
$html .= '<span class="glyphicon glyphicon-arrow-up" aria-hidden="true"';
$html .= 'onclick="build()">'; //#todo add onclick to trigger build()
$html .= '</span></a></span>';
$html .= $v;
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
function makeSection($parent, $prefix, $type, $subTypes) {
$headingID = 'heading-'.$type;
$bodyID = 'collapse-'.$prefix.$type;
$html = '<div class="panel panel-default" style="margin-bottom:10px;">';
$html .= '<div class="panel-heading" role="tab" id="'.$headingID.'">';
$html .= '<h4 class="panel-title">';
$html .= '<a role="button" data-toggle="collapse" data-parent="'.$parent;
$html .= '" href="#'.$bodyID.'" aria-expanded="true"';
$html .= 'aria-controls="'.$bodyID.'">'.$type;
$html .= '</a></h4></div>';
$html .= '<div id="'.$bodyID.'" class="panel-collapse collapse in" ';
$html .= 'role="tabpanel" aria-labelledby="'.$headingID.'">';
$html .= '<div class="list-group">';
foreach ($subTypes as $subType) {
$target = "tab-".$prefix.$type."-".$subType;
$html .= '<a href="#'.$target.'" class="list-group-item" ';
$html .= 'aria-controls="'.$target.'" role="tab" data-toggle="tab"';
$html .= '>'.$subType.'</a>';
}
$html .= '</div></div></div>';
return $html;
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<style>
.list-group-item.active, .list-group-item.active:hover {
background-color: white;
color: black;
}
</style>
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Configuration Management</h1>
</div>
<div class="row">
<div class="col-md-5 col-md-push-1 col-sm-6">
<ul class="nav nav-tabs" role="tablist" id="config-tabs">
<li role="presentation" class="active">
<a href="#project_list" aria-controls="project_list" role="tab" data-toggle="tab">
<h4>Project</h4>
</a>
</li>
<li role="presentation">
<a href="#workflow_list" aria-controls="workflow_list" role="tab" data-toggle="workflow_list">
<h4>Workflow</h4>
</a>
</li>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane active panel-group" id="project_list" role="tablist" aria-multiselectable="true">
<?php
foreach ($project_types as $type) {
echo makeSection( '#project_list', 'project-',$type, $project_subtypes[$type]);
}
?>
</div>
<div role="tabpanel" class="tab-pane panel-group" id="workflow_list" role="tablist" aria-multiselectable="true">
<?php
foreach ($workflow_types as $type) {
echo makeSection( '#workflow_list', 'workflow-',$type, $workflow_subtypes[$type]);
}
?>
</div>
</div>
</div>
<div class="col-md-5 col-md-push-1 col-sm-6">
<div id="tabs" class="tab-content" style="padding:0em 0em 0em 1em">
<?php
foreach ($project_types as $type) {
// #TODO remove once folder structure is all setup
if ($type !== 'CD') continue;
foreach ($project_subtypes[$type] as $subType) {
$html = "<div role ='tabpanel' class='tab-pane'";
$html .= "id='tab-project-".$type."-".$subType."'>";
$html .= makeInfoSection($type, $subType, $project_versions[$subType], $project_dir);
$html .= "</div>";
echo $html;
}
}
foreach ($workflow_types as $type) {
foreach ($workflow_subtypes[$type] as $subType) {
$html = "<div role ='tabpanel' class='tab-pane'";
$html .= "id='tab-workflow-".$type."-".$subType."'>";
$html .= makeInfoSection($type, $subType, $workflow_versions[$subType], $workflow_dir);
$html .= "</div>";
echo $html;
}
}
?>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="12345" crossorigin="anonymous"></script>
<script type="text/javascript">
function build (url, params, cb) {
url += "/buildWithParameters";
//Added so we set the $_GET['func']
url += "?func=build";
$.ajax({
type: 'POST',
url: url,
data: params,
success: cb
});
};
$('.collapse').collapse();
$('.list-group a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
$('#config-tabs a').click(function (e) {
e.preventDefault();
$(this).tab('show');
})
</script>
</body>
</html>
I only altered 2 sections of your code.
Just below the require setup.php and right inside your Javascript build function.
If you need to pass parameters to it, Your current call to build is empty, you're calling build(), but build wants 3 arguments.
So, with url being empty(or undefined in this case), you may find that the url is not going to the correct location. Params is empty as well as cb. So all of those may need to be checked inside your function with
if(typeof VARIABLE == "undefined" ) VARIABLE="SOMETHING"; //populate, you can also call a function here to get data.

Related

retreive image on clicking image name through ajax in codeignitor from database

i am making gallery in codeignitor. i have retrived list of image names from database on view page. now i want to get image on clicking name through ajax. i am not that much good with code. kindly help me with fetch gallery function. any help is much appreciated. thanks in advance.
this is my code for fetchng image names:
<?php
//$i=1;
foreach($data as $row)
{
?>
<img class="img-circle img-bordered-sm" src='<?php echo base_url();?>assets/uploads/<?php echo $row->imagefiles;?>' height='30px' width='30px'>
<span class="username">
<a id="view_gallery" class="view_gallery" href="javascript:void(0);" id="<?php echo $row->id;?>"><?php echo $row->name; ?></a>
</span>
<hr>
<?php }
?>
and this is my script, i need further help with code :
<script type="text/javascript">
$( ".view_gallery" ).click(function() {
id = $(this).attr('id');
/* alert(userid);*/
$.ajax({
url : '<?php echo base_url('fetch_gallery_data') ;?>',
method : 'post',
data : {id : id},
success : function(res){
$('.disp_gallery').html(res);
}
})
});
</script>
here is my fetch gallery function in controller ,
public function fetch_gallery_data()
{
$id = $this->input->post('id');
$where = $id;
$result = $this->App_model->gallery_model('gallery','id',$where);
$data = '';
if(count($result) > 0)
{
foreach ($result as $key => $value)
{
$files = json_decode($value->imagefile);
if($value->id > 0)
{
$data .= "<div class='col-md-3' style='border:1px solid gray; margin:20px; padding:20px; ' id='".$id."''>";
$data .= "<a >";
$data .= "<img src='".base_url()."assets\uploads/seo-business-quotes-6.jpg' height='150' width='150'><br>";
$data .= "</div>";
}
else
{
foreach ($files as $key => $value)
{
$data .= "<div class='col-md-3' style='border:1px solid gray; margin:20px; padding:20px; '>";
$data .= "<img src=".base_url()."assets\uploads/".$value." height='150' width='150'><br>";
$data .= "</div>";
}
}
}
}
else
{
$data .= 'No Records.';
}
echo $data;
}
Change the slashes you mentioned in the controller then try
$data .= "<img src='".base_url()."assets/uploads/seo-business-quotes-6.jpg' height='150' width='150'><br>";
Here also change slash and single quotes
$data .= "<img src='".base_url()."assets/uploads/".$value."' height='150' width='150'><br>";

tree view display data using jquery javascript in yii2

I have display data like treeview using javascript, jquery in yii2.
I have done my code like this:
$this->registerJs(
'
function videoShow(id){
var url = "' . Url::to(['test/get-videos-from-category']) . '?id="+id;
$.ajax({
type: "GET",
url: url,
beforeSend: function() {
blockBody();
},
success:function(data){
var hidden = $(data).find(".hidden")[0];
var parent_id = $(hidden).find(".category_parent_id").text();
var category_id = $(hidden).find(".category_uuid").text();
$("span").one("click", function() {
$(".category_video #myTab5").hide();
$(this).parent().children().css("display","inline");
$(this).addClass("caret-down");
$(this).parent().parent().children().children().not($(this)).removeClass("caret-down");
$(this).parent().children().css("display","inline").not($(this));
$(this).parent().children().addClass("active");
});
var category = $(".hidden").children(".category_name").text();
var category_uuid = $(".hidden").children(".category_uuid").text();
var category_parent_id = $(".hidden").children(".category_parent_id").text();
if(category == "") {
$(".datatable-search-div").css("display","inline");
unblockBody();
$("#myTabContent5").css("display","inline");
$(".showVideo").html(data);
} else {
if(".hidden") {
var hidden = $(data).find(".hidden")[0];
var hidden_category = $(hidden).find(".category_name").text();
var hidden_parent_id = $(hidden).find(".category_parent_id").text();
var hidden_category_uuid = $(hidden).find(".category_uuid").text();
category = hidden_category;
category_uuid = hidden_category_uuid;
category_parent_id = hidden_parent_id;
var html = "<a href=\'"+category_uuid+"\' id=\'video_search\' data-uuid=\'"+category_uuid+"\' data-parentid=\'"+category_parent_id+"\' data-name=\'"+category+"\' data-toggle=\'tab\' class=\'caret\' onclick=videoShow(\'"+category_parent_id+"\'); style=\'margin-left: 20px;\'>"+category+"</a>";
html += "<ul class=\'category_nested\' id=\'"+category_uuid+"\' role=\'tablist\'>";
html += "<li class=\'category_sub_child\'>";
html += "</li>";
html += "</ul>";
unblockBody();
$("#myTabContent5").css("display","inline");
$(".showVideo").html(data);
}
var html = [];
$(".hidden").each(function(cat) {
$("#video_search").addClass("caret-down");
$(".category_child").parent().addClass("caret-down");
var category = $(this).children(".category_name").text();
;
var category_uuid = $(this).children(".category_uuid").text();
var category_parent_id = $(this).children(".category_parent_id").text();
var category_uuid_array = [];
var category_array = [];
var category_parent_id_array = [];
category_uuid_array.push(category_uuid);
category_array.push(category);
category_parent_id_array.push(category_parent_id);
var html_new = "<li class=\'category_child\' data-id=\'"+category_uuid+"\'>";
html_new += "<a href=\'"+category_uuid+"\' id=\'video_search\' data-uuid=\'"+category_uuid+"\' data-parentid=\'"+category_parent_id+"\' data-name=\'"+category+"\' data-toggle=\'tab\' class=\'caret\' onclick=videoShow(\'"+category_uuid+"\'); style=\'margin-left: 20px;\'>"+category+"</a>";
html_new += "<ul class=\'category_nested\' id=\'"+category_uuid+"\' role=\'tablist\'>";
html_new += "<li class=\'category_sub_child\'>";
html_new += "</li>";
html_new += "</ul>";
html.push(html_new);
});
$(".category_child").click(function(){
console.log("category_child clicked");
$(this).children(".category_nested").children().html(html);
});
if($(".nested").length) {
console.log("nested");
$(".nested").children().html(html);
}
unblockBody();
$("#myTabContent5").css("display","inline");
$(".showVideo").html(data);
}
},
error:function(e){
unblockBody();
showErrorMessage(e.responseText);
}
});
}
', View::POS_END
);
?>
And html code like this:
<html>
<body>
<div class="content-body">
<div class="row ">
<div class="col-lg-12 col-md-12 col-12 ">
<ul id="myUL" class="datatable-search-div" style="display: none;">
<?php
if (!empty($model)) {
foreach ($model as $key => $value) { ?>
<li class="category_video">
<span class="caret">
<a href="<?= $value['uuid']; ?>" id="video_search" data-uuid="<?= $value['uuid']; ?>" data-parentid="<?= $value['parent_id']; ?>" data-name="<?= $value['name']; ?>" data-toggle="tab" onclick="videoShow('<?= $value['uuid']; ?>');">
<?= $value['name']; ?>
</a>
</span>
<ul class="nested" data-id="<?= $value['uuid']; ?>" id="myTab5" role="tablist" style="display:none;">
<li class="category_child" data-id="<?= $value['uuid']; ?>">
<ul class="category_nested" id="<?= $value['uuid']; ?>" role="tablist">
<li class="category_sub_child">
</li>
</ul>
</li>
</ul>
</li>
<?php
}
}
?>
</ul>
</div>
</div>
</div>
<div class="tab-content float-left vertical col-xl-12 col-lg-12 col-md-3 col-3 left-aligned" id="myTabContent5" style="display:none;">
<?php
if (!empty($model)) { ?>
<div id="<?= $value['uuid']; ?>" class="tab-pane showVideo fade active show">
</div>
<?php
}
?>
</div>
</body>
</html>
[![enter image description here][1]][1]
In this code category_child class element then that data display in that not children class.
In this code, I have tried to Cat-1.1.1 in after Cat-1.1 category.
But not display like that. Cat-1.1.1 display after Category1 and Cat-1.1 remove.
This is an image I have to explain in the last step:
Please help if anyone have an idea for that.
This is answer for my question:
public function getCategoryTreeHtml($level = null, $prefix = '') {
$rows = InstrumentCategory::find()->where(['parent_id' => $level])->asArray()->all();
$category = '';
if (count($rows) > 0) {
foreach ($rows as $row) {
$sub_count = InstrumentCategory::find()->where(['parent_id' => $row['uuid']])->count();
if($sub_count > 0){
$category .= '<li style="padding: 5px;"><span class="caret"><a href="'.$row['uuid'].'" id="video_search" data-uuid="'.$row['uuid'].'" data-parentid="'.$row['parent_id'].'" data-name="'.$row['name'].'" data-toggle="tab" onclick=videoShow("'.$row['uuid'].'");>' . $row['name'] . "</a></span>";
$category .= '<ul class="nested">';
$category .= self::getCategoryTreeHtml($row['uuid'], $prefix . '-');
$category .= '</ul>';
$category .= '</li>';
}else{
$category .= '<li><a href="'.$row['uuid'].'" id="video_search" data-uuid="'.$row['uuid'].'" data-parentid="'.$row['parent_id'].'" data-name="'.$row['name'].'" data-toggle="tab" onclick=videoShow("'.$row['uuid'].'")>' . $row['name'] . "</a></li>";
// Append subcategories
//$category .= $this->getCategoryTree($row->id, $prefix . '-');
}
}
}
return $category;
}

Add new dynamic boostrap card does not work

I will insert new boostrap card inside my page. My problem, I have not success to include a new card inside my content.
When i click on insert, the card is not displayed
Below the code
display a new boostrap card if record exist
<div class="row">
<button type="button" class="btn btn-primary" aria-label="Insert" id="insert">
<span aria-hidden="true">Insert</span>
</button>
</div>
<div class="row">
<ul class="row list-unstyled" id="list">
<?php
$i = 0;
while ($QoptionValue->fetch()) {
.....
?>
<li class="col-md-4" id="element'<?php echo $i; ?>">
<div class="card">
<h4 class="card-header">Card title <a class="close" href="#">×</a></h4>
<div class="card-body">
<div class="card-text">
<div><?php ..... ?></div>
</div>
</div>
</li>
<?php
$i++;
}
?>
</ul>
</div>
Display a new card or first card inside the content
<?php
$card = '<li class="col-md-4" id="element0">';
$card .= '<div class="card">';
$card .= '<h4 class="card-header">Card title <a class="close" href="#">Remove</a></h4>';
$card .= '<div class="card-body">';
$card .= '<div class="card-text">';
$card .= '<div>';
for ($l=0, $n=count($languages); $l<$n; $l++) {
$card .= Language->getImage($languages[$l]['code']) . ' ' . HTML::inputField('option_value[' . $i . '][option_value_description][name][' . $l . ']', $options_name) . '<br />';
$card .= HTML::hiddenField('option_value[' . $i . '][option_value_description][language_id][' . $l . ']', $options_name);
}
$card .= '</div>';
$card .= '<div>';
$card .= HTML::inputField('option_value[' . $i . '][sort_order]', $QoptionValue->value('sort_order'), 'id="sort_order[' . $i . ']"');
$card .= '</div>';
$card .= '<div>';
$card .= '</div>';
$card .= '</div>';
$card .= '</li>';
?>
<script>
$('#insert').click(function(){
$( "ul#list" ).append( "<?php echo $card; ?>" );
});
</script>
<script type="text/javascript">
$('.close').click(function(){
var $target = $(this).parents('li');
$target.hide('slow', function(){ $target.remove(); });
})
</script>
console error
it seems on this line has a problem :
$( "ul#list" ).append(""<li class=\"col-md-4\" id=\"element0\"><div class=\"row\"><div class=\"col-md-12\"><div class=\"card\"><h4 class=\"card-header\"><a class=\"close\" href=\"#\">Supprimer<\/a><\/h4><div class=\"card-body\">Nom de la valeur<div><img src=\"http:\/\/localhost\/test_option\/shop\/sources\/third_party\/flag-icon-css\/flags\/4x3\/gb.svg\" alt=\"Anglais\" title=\"Anglais\" width=\"16\" height=\"12\" \/> <input type=\"text\" name=\"option_value[0][option_value_description][name][0]\" class=\"form-control\" \/><br \/><input type=\"hidden\" name=\"option_value[0][option_value_description][language_id][0]\" \/><img src=\"http:\/\/localhost\/test_option\/shop\/sources\/third_party\/flag-icon-css\/flags\/4x3\/fr.svg\" alt=\"Francais\" title=\"Francais\" width=\"16\" height=\"12\" \/> <input type=\"text\" name=\"option_value[0][option_value_description][name][1]\" class=\"form-control\" \/><br \/><input type=\"hidden\" name=\"option_value[0][option_value_description][language_id][1]\" \/><\/div><div class=\"row\"><span class=\"col-md-4\">Ordre de tri<\/span><\/div><\/div><\/div><\/div><\/div><\/li>"");
Uncaught SyntaxError: missing ) after argument list
It's good practice to pass any PHP variable to javascript using json_encode(). Using json_encode() you'll always get a properly formatted JavaScript object with the quotes escaped.
<script>
$('#insert').click(function(){
$( "ul#list" ).append(<?php echo json_encode($card); ?>);
});
</script>

How pull innerHTML of element created by javascript function

Question:
I have a div element with id of "tableholder" which is purely to hold the output on a javascript function that pulls data via ajax from a PHP file.
Within the tableholder element, is a list.js table that works if we simply include he php file instead of calling it via ajax and setting it via innerHTML = "".
How do I use the contents of innerHTML of the tableholder div when it has been created dynamically?
Code so far:
PHP File called:
<?php
// Connection details for the database being called.
include 'connection.php';
// Putting the query to the database in a variable called "$assets".
$assets = "SELECT * FROM assetregister.getassets";
$assetPull = $conn->query($assets);
$output = "";
// Pulling all of the details from the database and displaying them on the page within the inidividual divs.
if ($assetPull->num_rows > 0) {
$output .= "<div id='users'>";
$output .= "<input class='search form-control mt-2' placeholder='Search...' />";
$output .= "<div class='m-2'>";
$output .= "<button class='sort btn' data-sort='model'>Sort By Model</button>";
$output .= "<button class='sort btn ml-2' data-sort='domain'>Sort By Domain</button>";
$output .= "<button class='sort btn ml-2' data-sort='location'>Sort By Location</button>";
$output .= "</div>";
$output .= "<table class='table table.hover list'>";
$output .= "<thead>";
$output .= "<th style='text-align: center;'>Model</th>";
$output .= "<th style='text-align: center;'>Serial Number</th>";
$output .= "<th style='text-align: center;'>Asset Number</th>";
$output .= "<th style='text-align: center;'>Domain</th>";
$output .= "<th style='text-align: center;'>Location</th>";
$output .= "<th style='text-align: center;'>Type</th>";
$output .= "</thead>";
while ($row = $assetPull->fetch_assoc()) {
$output .= "<tbody class='list' style='text-align: center;'>";
$output .= "<td class='model'>" . $row['modelName'] . "</td>";
$output .= "<td class='serialNumber'>" . $row['serialNumber'] . "</td>";
$output .= "<td class='assetNumber'>" . $row['assetNumber'] . "</td>";
$output .= "<td class='domain'>" . $row['domain'] . "</td>";
$output .= "<td class='location'>" . $row['locationName'] . "</td>";
$output .= "<td class='type'>" . $row['type'] . "</td>";
}
$output .= "</tbody>";
$output .= "</table>";
$output .= "</div>";
// If there is no rows in the table that is being called then they will display 0 Results... See below.
} else {
$output .= "0 results";
}
echo $output;
$conn->close();
?>
This works:
<div class="container-fluid">
<div class="container">
<div class="row">
<main class="col-12" style="margin-top: 80px;">
<button class="btn btn-primary" onclick="assetSubmit()" style="width: 100%;">Add An Asset</button>
<?php include 'scripts/getAsset.php'; ?>
</main>
</div>
</div>
</div>
<script>
populatetable('tableholder');
window.onload = function () {
var options = {
valueNames: ['model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList = new List('users', options);
};
</script>
This outputs the table and all of the list.js functions work fine as expected.
This Doesn't Work:
<div class="container-fluid">
<div class="container">
<div class="row">
<main class="col-12" style="margin-top: 80px;">
<button class="btn btn-primary" onclick="assetSubmit()" style="width: 100%;">Add An Asset</button>
<!-- Pulling in the results of the assets (most recent assets) -->
<div id="tableholder"></div>
<!-- end -->
</main>
</div>
</div>
</div>
<!-- PHP include for the footer -->
<?php include 'assets/layout/footer.php'; ?>
<!-- end -->
<script>
populatetable('tableholder');
window.onload = function (){
var options = {
valueNames: [ 'model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList = new List('users', options);
};
function populatetable(name){
$.ajax({
url: "scripts/getAssets.php",
success: function(data){
document.getElementById(name).innerHTML = data;
}
})
}
</script>
What I can assume:
From the various console.log lines and php echos I have put in to test the code, it would appear that the issue it that the javascript command for initiating the list.js table isn't able to find the "user" table that is created by the document.getElementById(name).innerHTML = data; in the populatetable() function. I know this because the folllowing shows blank:
console.log(document.getElementById(tableholder).innerHTML);
What am I doing wrong, or is it not possible to pull the innerHTML data of a dynamically created element?
The problem is that by the time you're calling List(), the ajax call hasn't finished yet, since it's asynchronous.
Try this instead:
var options = {
valueNames: ['model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList;
$(document).ready(function() {
populatetable('#tableholder');
});
function populatetable(id) {
$.ajax({
url: "scripts/getAssets.php",
success: function(data) {
$(id).html(data);
userList = new List('users', options);
}
});
}
Here I'm using jQuery everywhere it's useful, and I'm calling List() only after the data is actually inserted.
Also note, that like I mentioned in my comment, you need to move the <tbody> line outside the loop.

remove() function not deleting the item within ul list

I have created a javascript function on drop down select it adds element and calculate the total amount of the added product now what I want do here is to make a function to delete that product added from the dropdown list but when I click on delete button it us only deleting the selected button and not deleting the row which I want it to be deleted by clicking on the button. You can review on this fiddle and will understood what is going on with it https://jsfiddle.net/h1k6mohs/ and also my script is not working may be is because it is not calling to that function below is my php script file
Controller
Home.php
public function addpart() {
$part = $this->input->post('parts');
$part_modify = explode(")", $part);
$part_id = $part_modify[0];
$old_price = $this->input->post('old_price');
$old_minutes = $this->input->post('old_minutes');
$data = $this->get_data->data_cart($part_id, $old_price, $old_minutes);
echo $data;
}
public function removepart() {
$part_id = $this->input->post('partid');
$old_price = $this->input->post('old_price');
$old_minutes = $this->input->post('old_minutes');
$data = $this->get_data->delete_part($part_id, $old_price, $old_minutes);
echo $data;
}
Model
Get_data.php
public function data_cart($part_id, $old_price, $old_minutes) {
$get_data = $this->db->get_where('rapair_parts', array('id' => $part_id));
$total_minutes = $get_data->row()->repair_time + $old_minutes;
$total_price = $get_data->row()->part_price + $old_price;
$html = '<div class="col-xs-12">';
$html .= '<div class="col-xs-6">Repair time</div>';
$html .= '<div class="col-xs-6">'.$total_minutes.' mins</div></div>';
$html .= '<input type="hidden" id="minutes_parts" value="'.$total_minutes.'" />';
$html .= '<div class="col-xs-12">';
$html .= '<div class="col-xs-6">Discount</div>';
$html .= '<div class="col-xs-6">'."£".'0.00</div></div>';
$html .= '<div class="col-xs-12">';
$html .= '<div class="col-xs-6">Total</div>';
$html .= '<div class="col-xs-6">£'.$total_price.'</div></div>';
$html .= '<input type="hidden" id="price_parts" value="'.$total_price.'" />';
return $html;
}
public function delete_part($part_id, $old_price, $old_minutes) {
$get_data = $this->db->get_where('rapair_parts', array('id' => $part_id));
$total_minutes = $get_data->row()->repair_time - $old_minutes;
$total_price = $get_data->row()->part_price - $old_price;
$html = '<div class="col-xs-12">';
$html .= '<div class="col-xs-6">Repair time</div>';
$html .= '<div class="col-xs-6">'.$total_minutes.' mins</div></div>';
$html .= '<input type="hidden" id="minutes_parts" value="'.$total_minutes.'" />';
$html .= '<div class="col-xs-12">';
$html .= '<div class="col-xs-6">Discount</div>';
$html .= '<div class="col-xs-6">'."£".'0.00</div></div>';
$html .= '<div class="col-xs-12">';
$html .= '<div class="col-xs-6">Total</div>';
$html .= '<div class="col-xs-6">£'.$total_price.'</div></div>';
$html .= '<input type="hidden" id="price_parts" value="'.$total_price.'" />';
return $html;
}
Please help me out with this bug please
Elements in Chrome have a .remove() method which allows for self-removal of an element instead of having to do it from the parent.
So "remove" is a reserved keyword, that's the issue and the reason it removes the element and not executing your function. You need to choose another name for your function.
I gone through your code, as per code you are using remove() which is inbuilt in JQuery, so you can directly apply to the HTML, kindly follow the below code.
<div id="js-part">
<li id="parts3" style="display: list-item;" onclick="remove();">
<div class="col-md-9"><i class="fa fa-check-circle"></i> Wifi Antenna</div>
<div class="col-d-3"><a>Remove</a></div>
</li>
<li id="parts1" style="display: list-item;" onclick="remove();">
<div class="col-md-9"><i class="fa fa-check-circle"></i> Glass Screen</div>
<div class="col-d-3"><a >Remove</a></div>
</li>
<li id="parts4" style="display: list-item;" onclick="remove();">
<div class="col-md-9"><i class="fa fa-check-circle"></i> Rear Camera</div>
<div class="col-d-3"><a>Remove</a></div>
</li>
<li id="parts5" style="display: list-item;" onclick="remove();">
<div class="col-md-9"><i class="fa fa-check-circle"></i> Front Camera</div>
<div class="col-d-3"><a>Remove</a></div>
</li>
</div>
<div id="total">
<div class="col-xs-12">
<div class="col-xs-6">Repair time</div>
<div class="col-xs-6">170 mins</div>
<input type="hidden" id="minutes_parts" value="170">
</div>
<div class="col-xs-12">
<div class="col-xs-6">Discount</div>
<div class="col-xs-6">£0.00</div>
</div>
<div class="col-xs-12">
<div class="col-xs-6">Total</div>
<div class="col-xs-6">£362</div>
<input type="hidden" id="price_parts" value="362">
</div>
</div>
So, i am directly remove the div on clicking each li elements.

Categories

Resources