I have been struggling for a few days to discover an option to display only the episodes corresponding to a season when I click on that season.
This is my code...
<div id='seasons' class='visible'>
<div class='wrap'>
<div class='tit'>ALEGEȚI UN SEZON</div>
<div class='list bslider undraggable deployed' data-bslider-margin='20' data-bslider-left-margin='0' data-bslider-right-margin='20' data-bslider-item-class='item' data-bslider-nav='false' id='seasonsList' data-single-width='60' data-max-width='201' data-stage-width='1160'><div class='bslider-outer'><div class='bslider-stage' style='width: 1160px; padding-left: 0px;'>
<?php
$tmdb = get_post_meta($post->ID,'ids',true);
$ctrl = get_post_meta($post->ID,'clgnrt',true);
$query_seasons = DDbmoviesHelpers::GetAllSeasons($tmdb);
if($query_seasons && is_array($query_seasons) && $ctrl == true){
$numb = 0;
foreach($query_seasons as $season){
$senumb = get_post_meta($season,'temporada', true);
?>
<div class="bslider-item" style="padding-right: 20px;"><div class="item" data-season-id="<?php echo $senumb; ?>" id="sezonul-<?php echo $senumb; ?>"><?php echo $senumb; ?></div></div>
<?php
$numb++;
}
}
?>
</div></div></div>
</div></div>
<div class='clearfix'></div>
<div id='episodes' class="active">
<div class='wrap'>
<?php
// Main data
$tmdb = get_post_meta($post->ID,'ids',true);
$ctrl = get_post_meta($post->ID,'clgnrt',true);
/*=====================================================*/
$query_seasons = DDbmoviesHelpers::GetAllSeasons($tmdb);
/*=====================================================*/
// Start Query
if($query_seasons && is_array($query_seasons) && $ctrl == true){
$numb = 0;
foreach($query_seasons as $k => $season){
$senumb = get_post_meta($season,'temporada', true);
$aidate = get_post_meta($season,'air_date', true);
$rating = get_post_meta($season,'_starstruck_avg', true);
/*=====================================================*/
$query_episodes = DDbmoviesHelpers::GetAllEpisodes($tmdb,$senumb);
/*=====================================================*/
$mnseo = $numb == 0 ? ' se-o' : false;
$dsply = $numb == 0 ? ' style="display:block"' : false;
$title = $senumb == '0' ? __d('Specials') : sprintf( __d('Season %s %s'), $senumb, '<i>'.doo_date_compose($aidate, false).'</i>');
$nseas = $senumb == '0' ? '<i class="icon-star"></i>' : $senumb;
// Continue View HTML
if($query_episodes && is_array($query_episodes)){
?>
<div class='list bslider' data-bslider-margin='20' data-bslider-left-margin='0' data-bslider-right-margin='20' data-bslider-item-class='item' data-bslider-nav='false' id='episodesList-<?php echo $senumb; ?>' data-single-width='220' data-max-width='761' data-stage-width='2000'><div class='bslider-outer'><div class='bslider-stage' style='width: 2000px; padding-left: 0px;'>
<?php
foreach($query_episodes as $episode){
// Post Data
$image = dbmovies_get_poster($episode,'dt_episode_a','dt_backdrop','w154');
$name = get_post_meta($episode,'episode_name', true);
$episo = get_post_meta($episode,'episodio', true);
$edate = get_post_meta($episode,'air_date', true);
$edate = doo_date_compose($edate, false);
$plink = get_permalink($episode);
$title = !empty($name) ? $name : __('Episode').' '.$episo;
?>
<div class='bslider-item' style='padding-right: 20px;'>
<div class='item slider-item' slide-number='<?php echo $episo; ?>' data-episode-id='<?php echo $episo; ?>'>
<div class='poster'>
<div class='img' style='background-image:url(<?php echo $image ?>);'></div>
<div class='title'><?php echo $episo; ?>. <?php echo $title; ?></div>
</div>
</div>
</div>
<?php
}
?>
</div></div></div> </br></br>
<?php
} else{
?>
<div class='title'><?php echo __d('There are still no episodes this season') ?></div>
<?php
}
$numb++;
}
}
?>
</div>
</div>
<div class="clearfix"></div>
I want when I click on a Season to trigger the list of episodes below.
I don't have any js for this, my script show all seasons and episodes perfectly but is all displayed.
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>
I have a multi-page form for customizing some sort of product. The radio buttons are dynamically generated based on the values from the database. What I want to happen is prevent the form from shifting to the next page if the required radio button groups doesn't have a selected value. I have tried JQuery validation plugin:
$('#customize-form').validate({ // initialize plugin
ignore:":not(:visible)",
rules: {
shape: { required:true },
size: { required:true },
tier: { required:true },
flavors: { required:true },
}
});
Now this part here shows the next page. Works perfectly except the fact that valid() seems to always return true and it goes to the next page.
// Next button click action
btnnext.click(function(){
if(current < widget.length){
// Check validation
if($("#customize-form").valid())
{
widget.show();
widget.not(':eq('+(current++)+')').hide();
}
}
hideButtons(current); //hides buttons which are not needed such as the submit button if it's not the end of the form
})
Here is how I generate the radio buttons dynamically:
<div id=step1 class='options step'>
<section class=section-title>Shape</section>
<?php
include('connect_db.php');
$query = $dbc->prepare("SELECT * FROM product_shape_t");
$query->execute();
$result = $query->get_result();
$total = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
echo '<ul class="radios">';
echo '<li>';
echo '<input type="radio" name="shape" id="'.$row['ShapeName'].'">';
echo '<label for="'.$row['ShapeName'].'">'.$row['ShapeName'].'</label>';
echo '</li>';
echo '</ul>';
}
?>
</div>
Here is the full html:
<html>
<head>
</head>
<body>
<form method=POST id=customize-form action ="">
<div id=step1 class='options step'>
<?php
include('connect_db.php');
$query = $dbc->prepare("SELECT MAX(CustomizedProductID) as 'Max ID' FROM customized_products_t");
$query->execute();
$result = $query->get_result();
$total = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
$custom_id = $row['Max ID'] + 1;
echo "<label class=custom_id style='display:none'>".$custom_id."</label>";
}
?>
<section class=section-title>Shape</section>
<?php
include('connect_db.php');
$query = $dbc->prepare("SELECT * FROM product_shape_t");
$query->execute();
$result = $query->get_result();
$total = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
echo '<ul class="radios">';
echo '<li>';
echo '<input type="radio" name="shape" id="'.$row['ShapeName'].'">';
echo '<label for="'.$row['ShapeName'].'">'.$row['ShapeName'].'</label>';
echo '</li>';
echo '</ul>';
}
?>
<section class=section-title>Size</section>
<?php
include('connect_db.php');
$query = $dbc->prepare("SELECT * FROM product_size_t");
$query->execute();
$result = $query->get_result();
$total = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
echo '<ul class="radios">';
echo '<li>';
echo '<input type="radio" name="size" id="'.$row['SizeName'].'">';
echo '<label for="'.$row['SizeName'].'">'.$row['SizeName'].'</label><br />';
echo '<label for="'.$row['SizeDesc'].'">'.$row['SizeDesc'].'</label>';
echo '</li>';
echo '</ul>';
}
?>
<section class=section-title>Tier</section>
<?php
include('connect_db.php');
$query = $dbc->prepare("SELECT * FROM product_tier_t");
$query->execute();
$result = $query->get_result();
$total = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
echo '<ul class="radios">';
echo '<li>';
echo '<input type="radio" name="tier" id="'.$row['TierName'].'">';
echo '<label for="'.$row['TierName'].'">'.$row['TierName'].'</label><br />';
echo '</li>';
echo '</ul>';
}
?>
</div>
<div id=step2 class='options step'>
<section class=section-title>Flavor</section>
<?php
include('connect_db.php');
$query = $dbc->prepare("SELECT * FROM product_flavor_t");
$query->execute();
$result = $query->get_result();
$total = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
echo '<ul class="radios">';
echo '<li>';
echo '<input type="checkbox" name="flavors" id="'.$row['FlavorName'].'">';
echo '<label for="'.$row['FlavorName'].'">'.$row['FlavorName'].'</label><br />';
echo '</li>';
echo '</ul>';
}
?>
<section class=section-title>Sides (Optional)</section>
<?php
include('connect_db.php');
$query = $dbc->prepare("SELECT g.IngredientID, g.IngredientsName FROM ingredients_t g JOIN inventory_t i ON g.IngredientID = i.IngredientsID JOIN ingredient_type_t t ON t.IngTypeID = i.IngredientTypeID WHERE t.IngTypeName='sides'");
$query->execute();
$result = $query->get_result();
$total = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
echo '<ul class="radios">';
echo '<li>';
echo '<input type="checkbox" name="ingredients" id="'.$row['IngredientsName'].'">';
echo '<label for="'.$row['IngredientsName'].'">'.$row['IngredientsName'].'</label><br />';
echo '</li>';
echo '</ul>';
}
?>
<section class=section-title>Template (Optional)</section>
<?php include('get_templates.php');?>
</div>
<div id=step3 class='options step'>
<section class=section-title>Image (Optional)</section>
<div class=image-display><img src="" width="100" style="display:none;" /></div>
<?php
echo '<form method=post enctype=multipart/form-data>
<section style="margin-bottom:10px">
<label class="paragraph-font2 full-width">Attach an image:</label>
</section>
<section style="margin-bottom:15px">
<input class="paragraph-font2 full-width" type=file name=uploaded_img id=uploaded_img accept="image/*">
</form>';
?>
</div>
<div id=step4 class='options step'>
<section class=section-title>Writings (Optional)</section>
<?php
echo '<form method=post>
<section class=add-notes>
<textarea id=writings class="lightfields-base lighttxtarea-regular" maxlength="250" placeholder="Do we have to write something on the cake?"></textarea>
</section>
</form>';
?>
<div class=separator-div></div>
<section class=section-title>Additional notes (Optional)</section>
<?php
echo '<form method=post>
<section class=add-notes>
<textarea id=additional class="lightfields-base lighttxtarea-medium" maxlength="999"></textarea>
</section>
</form>';
?>
</div>
<div id=step5 class='options step'>
<section class=section-title>Check your cake</section>
<div id=final_image class=final-image-display><img src="" width="100" style="display:none;" /></div>
<div class=details>
<label><span class=desc>Shape: </span><span id=shape></span></label>
<label><span class=desc>Size: </span><span id=size></span></label>
<label><span class=desc>Flavor: </span><span id=flavor></span></label>
<label><span class=desc>Sides/Mix-ins: </span><span id=sides></span></label>
<label><span class=desc>Writings: </span><span id=write></span></label>
<label><span class=desc>Additional notes: </span><span id=add_notes></span></label>
</div>
</div>
<div class=button-separator>
<label>
<button class='btn btn-info action next'>Next <span class='glyphicon glyphicon-arrow-right'></span></button>
</label>
<label>
<button class='btn btn-info action submit'>Add to cart <span class='glyphicon glyphicon-arrow-right'></span></button>
</label>
<label>
<button class='btn btn-info action back'><span class='glyphicon glyphicon-arrow-left'></span> Back</button>
</label>
</div>
</form>
</body>
</html>
<script>
$(document).ready(function(){
var current = 1;
widget = $(".step");
btnnext = $(".next");
btnback = $(".back");
btnsubmit = $(".submit");
// Init buttons and UI
widget.not(':eq(0)').hide();
hideButtons(current);
$('#customize-form').validate({ // initialize plugin
ignore:":not(:visible)",
rules: {
shape: { required:true },
size: { required:true },
tier: { required:true },
flavors: { required:true },
}
});
// Next button click action
btnnext.click(function(){
if(current < widget.length){
// Check validation
if($("#customize-form").valid())
{
widget.show();
widget.not(':eq('+(current++)+')').hide();
$('#step'+(current-1)).removeClass('active');
$('#step'+(current-1)).addClass('complete');
$('#step'+current).removeClass('disabled');
$('#step'+current).addClass('active');
//This part gets the values chosen to be displayed on page 5
/*if(current == 5)
{
var shape = $('input[type=radio][name=shape]:checked').attr('id');
var size = $('input[type=radio][name=size]:checked').attr('id');
var tier = $('input[type=radio][name=tier]:checked').attr('id');
var flavors = [];
$("input[name=flavors]:checked").each(function()
{
flavors.push($(this).attr('id'));
});
var sides = [];
$("input[name=ingredients]:checked").each(function()
{
sides.push($(this).attr('id'));
});
var writings = $(this).find('#writings').val();
var additional = $(this).find('#additional').val();
document.getElementById("shape").innerHTML=shape;
document.getElementById("size").innerHTML=size;
var flav;
for (var i=0; i<flavors.length; i++) {
flav += flavors[i];
}
document.getElementById("flavor").innerHTML=flavors;
document.getElementById("sides").innerHTML=sides;
document.getElementById("write").innerHTML=writings;
document.getElementById("add_notes").innerHTML=additional;
}*/
}
}
hideButtons(current);
})
// Back button click action
btnback.click(function(){
if(current > 1){
current = current - 2;
if(current < widget.length){
widget.show();
widget.not(':eq('+(current++)+')').hide();
//This part adjusts the steps bar
/*$('#step'+current).removeClass('complete');
$('#step'+current).addClass('active');
$('#step'+(current+1)).removeClass('active');
$('#step'+(current+1)).addClass('disabled');*/
}
}
hideButtons(current);
})
btnsubmit.click(function(){
if($("#customize-form").valid())
{
var id = $(this).find('.custom_id').text();
var quantity = 1;
window.location.href = "add_custom_to_cart.php?id=" + id + "&quantity=" + quantity;
return false;
}
})
$('#uploaded_img').change( function(event) {
$(".image-display img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
var image_name = $(this).attr('src',URL.createObjectURL(event.target.files[0]));
document.getElementById('final_image').src = image_name;
});
$('.select-template').on('click', function(e){
var temp_id = $('.temp_id').text();
$.ajax({
type: 'POST',
url: 'add_selected_temp.php',
data: {
template: temp_id
}
});
});
$().maxlength();
});
// Hide buttons according to the current step
hideButtons = function(current){
var limit = parseInt(widget.length);
$(".action").hide();
if(current < limit) btnnext.show();
if(current > 1) btnback.show();
if (current == limit) {
btnnext.hide();
btnsubmit.show();
}
}
</script>
Am I doing something wrong or should I use an alternative solution? Thank you.
I have solved the problem by making a custom validation. There seems to be a problem with my markup that's why JQuery validation plugin won't apply. Here is my custom validation.
btnnext.click(function(){
if(current < widget.length){
// Check validation
var empty = true;
if(current == 1)
{
if($("input[name='shape']:checked").val() &&
$("input[name='tier']:checked").val() &&
$("input[name='tier']:checked").val())
{
empty = false;
}
}
if(current == 2)
{
if($("input[name='flavors']:checked").val())
{
empty = false;
}
}
if(current == 3)
{
if(document.getElementById("uploaded_img").files.length != 0)
{
empty = false;
}
}
if(current == 4)
{
if($("#writings").val())
{
empty = false;
}
}
if(current == 5)
{
empty = false;
}
if(!empty)
{
widget.show();
widget.not(':eq('+(current++)+')').hide();
//only gets values to be display on page 5 please ignore
/*if(current == 5)
{
var shape = $('input[type=radio][name=shape]:checked').attr('id');
var size = $('input[type=radio][name=size]:checked').attr('id');
var tier = $('input[type=radio][name=tier]:checked').attr('id');
var flavors = [];
$("input[name=flavors]:checked").each(function()
{
flavors.push($(this).attr('id'));
});
var sides = [];
$("input[name=ingredients]:checked").each(function()
{
sides.push($(this).attr('id'));
});
var writings = $("#writings").val()
var additional =$("#additional").val();
document.getElementById("shape").innerHTML=shape;
document.getElementById("size").innerHTML=size;
var flav;
for (var i=0; i<flavors.length; i++) {
flav += flavors[i];
}
document.getElementById("flavor").innerHTML=flavors;
document.getElementById("sides").innerHTML=sides;
document.getElementById("write").innerHTML=writings;
document.getElementById("add_notes").innerHTML=additional;
}*/
}
}
hideButtons(current);
})
I want to give credit to OffirPe'er for all the help and heads up about possible markup conflict.
I am trying to create an AJAX filter using jQuery and PHP. When my user selects an ingredient from the dropdown I look to see in my database if a recipe exists with that ingredient and if the user created the recipe. This query works perfectly and allows me to loop through and create HTML for each recipe. I want to update the HTML via AJAX. At the moment I have this for my AJAX:
$(document).ready(function() {
$('#filterButton').click(function(e) {
e.preventDefault();
// When the filter button is clicked, grab the ingredient ID and the cuisine ID
var mainIngred = $('#sel1').val();
var cuisine = $('#cuisine').val();
var userID = $('#userIDHidden').val();
var data = {
"ingredID" : mainIngred,
"tagID" : cuisine,
"userID" : userID
}
var filterajaxurl = '/recipe-project/filter-ajax.php';
$.ajax({
url: filterajaxurl,
type: "POST",
data: data,
success:function(data) {
$("#cookbook-recipe").html(data);
}
});
});
});
This is the PHP script I call, when it's called I want to replace the default data in the div with the ID cookbook-recipe with the HTML below after the PHP has looped through and got each recipe.
include_once('classes/class-database-functions.php');
$db_functions = new Database_Functions();
$ajax_recipes = $db_functions->ajax_filter_search(23,6);
$recipes_array = array();
foreach ($ajax_recipes as $ajax_recipe) {
$search_recipes = $db_functions->get_single_recipe($ajax_recipe);
$rows = mysqli_fetch_array($search_recipes, MYSQL_ASSOC);
array_push($recipes_array,$rows);
} ?>
<?php
if (isset($recipes_array) ) {
foreach ( $recipes_array as $single_recipe ) { ?>
<div class="col-md-4 portfolio-item">
<a href="single-recipe.php?id=<?php echo $single_recipe['recipe_id'];?>">
<?php if ( $single_recipe['recipe_image'] == '' ) { ?>
<img class="img-responsive" src="http://placehold.it/300x200" alt="">
<?php } else { ?>
<img class="img-responsive" src="<?php echo $single_recipe['recipe_image']; ?>" alt="">
<?php } ?>
</a>
<h4>
<a href="#">
<?php echo $single_recipe['recipe_name']; ?>
</a>
</h4>
</div>
<?php } } else { ?>
<div class="col-md-4 portfolio-item">
<h4>Please Add Some Recipes</h4>
</div>
<?php } ?>
Below is my default HTML
<button id="filterButton" class="btn btn-lg active" role="button">Filter Recipes</button>
<div id="cookbook-recipes" class="col-md-9">
<?php
if (isset($recipes_array) ) {
foreach ( $recipes_array as $single_recipe ) { ?>
<div class="col-md-4 portfolio-item">
<a href="single-recipe.php?id=<?php echo $single_recipe['recipe_id'];?>">
<?php if ( $single_recipe['recipe_image'] == '' ) { ?>
<img class="img-responsive" src="http://placehold.it/300x200" alt="">
<?php } else { ?>
<img class="img-responsive" src="<?php echo $single_recipe['recipe_image']; ?>" alt="">
<?php } ?>
</a>
<h4>
<a href="#">
<?php echo $single_recipe['recipe_name']; ?>
</a>
</h4>
</div>
<?php } } else { ?>
<div class="col-md-4 portfolio-item">
<h4>Please Add Some Recipes</h4>
</div>
<?php } ?>
</div>
However the HTML doesn't get replaced when I click the button and I get no console errors, can anyone see why?
It may help you.
Setting all HTML in a variable and finally echoing it:
$html_reponse = "";
<?php
if (isset($recipes_array) ) {
foreach ( $recipes_array as $single_recipe ) {
$html_reponse .= "<div class='col-md-4 portfolio-item'>";
$html_reponse .= "<a href='single-recipe.php?id=".$single_recipe['recipe_id']."'>";
if ( $single_recipe['recipe_image'] == '' ) {
$html_reponse .= "<img class='img-responsive' src='http://placehold.it/300x200' alt=''>";
} else {
$html_reponse .= "<img class='img-responsive' src='".$single_recipe['recipe_image']."' alt=''>";
}
$html_reponse .= "</a>";
$html_reponse .= "<h4>";
$html_reponse .= "<a href='#'>".$single_recipe['recipe_name']."</a>";
$html_reponse .= "</h4>";
$html_reponse .= "</div>";
}
}else{
$html_reponse .= "<div class='col-md-4 portfolio-item'>";
$html_reponse .= "<h4>Please Add Some Recipes</h4>";
$html_reponse .= "</div>";
}
echo $html_reponse;exit;
In your JS:
success:function(data) {
// remove this alert after your testing.
// It is just to placed that we successfully got the reponse
alert("We got Response");
// Just showing response in Browser console 'press F12 shortcut to open console in your browser'
console.log(data);
// removing existing HTML from the container and then entering new one!
$("#cookbook-recipe").empty().html(data);
}
If it still doesn't work, you might have some problem in getting response. Make sure that it comes to your Ajax success callback event.
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.