PHP, MySQL & jQuery: Display select options dynamically - php

having a bit of a problem here understanding how I can make the following action happen on my web page:
Right so at the moment I have two select elements on my page, one of the select elements looks like this:
<select class="form-control select-box">
<option value="make-any">Make (Any)</option>
<?php while($make = $makeFilter->fetch(PDO::FETCH_ASSOC))
{
echo '
<option value="'.$make["Make"].'">'.$make["Make"].'</option>
';
} ?>
</select>
As you can see this code is looping the 'Make' column of my SQL table, in the separate file that contains the queries I have made it so the query is using DISTINCT so it doesn't loop the same 'Makes' as the chances are there will be identical 'Makes' in the column.
I then have this block of code that displays another query into the front end:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '
<div class="makes ' . $row["Make"] . '">
<div class="listing-container">
<h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3>
<h3 class="price-listing">£'.number_format($row['Price']).'</h3>
</div>
<div class="listing-container-spec">
<img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/>
<div class="ul-listing-container">
<ul class="overwrite-btstrp-ul">
<li class="diesel-svg list-svg">'.$row["FuelType"].'</li>
<li class="saloon-svg list-svg">'.$row["Bodytype"].'</li>
<li class="gear-svg list-svg">'.$row["Transmission"].'</li>
<li class="color-svg list-svg">'.$row["Colour"].'</li>
</ul>
</div>
<ul class="overwrite-btstrp-ul other-specs-ul h4-style">
<li>Mileage: '.number_format($row["Mileage"]).'</li>
<li>Engine size: '.$row["EngineSize"].'cc</li>
</ul>
<button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked
</button>
<button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details
</button>
<button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive
</button>
<h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4>
</div>
</div>
';
} ?>
As you can see that block is looping various columns of my SQL table to display pretty much the whole table. PLEASE NOTE that the div with the class of 'makes' also includes the column 'Make' in the div.
I then use this jQuery to filter what results are brought to the screen:
<script>
$(document).ready(function(){
$('.form-control').change(function(){
var make = $(this).val();
if(make != 'make-any'){
$('.makes').hide();
$('.'+make).show();
} else {
$('.makes').show();
}
});
});</script>
As you can see it simply hides divs that don't have the class of the select value that has been selected.
So all of that is great however I get the feeling it just isn't enough for my users, I now want the users to be able to use a second select element to select a 'Model' of the 'Make'.
Now I know I could easily do this with the same technique I did at first but then users would be able to select 'BMW' and then select a model that wasn't associated with the 'Make' and no results would be returned.
I'd like my select element that contains the 'Models' to first of all be disabled until a user has selected a 'Make' then when a user has selected the 'Make' I'd like the second select element to show only the 'Models' that are associated with that 'Make'.
Here is an example of the columns in my SQL table:
Make, Model, Colour, FuelType, Year, Mileage, Bodytype, Doors, Variant, EngineSize, Price, Transmission, PictureRefs, ServiceHistory, PreviousOwners, Options, FourWheelDrive
I am now unsure how I can make this happen, it's really baffled me.
If someone could show me a detailed example and explain what each part does that would be great as I am a little stuck, thanks.

There are two options:
you could preload the data and save it as an object in JS and display when needed.
Or you could use ajax-calls to load the data when you need it(most websites do that nowadays)
use
$('makeselect').on('change', function() {
$.get("getmodels.php?make="+$("makeselect").val(),function(data){
var models=json.parse(data);
//iterate through the object and create the option tags
});
});
and give the select an id.
on php you should send the data encoded with json. json_encode(...)

Related

AngularJS ng-repeat for one row in PDO fetch

I am newer to Angular and seem to be having difficulty finding out why I'm getting blank fields. I'm using the 1.7.7 version of angular-min and angular-route.
The data is being pulled from a table called "news" and I am only needing the ID and ARTICLE columns. The ARTICLE column is stored from a CKEditor textarea.
My route looks like:
var app = angular.module("HabbfinityApp", ["ngRoute"]);
app.config(['$routeProvider','$locationProvider',
function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when("/", {
templateUrl : "home.php"
}).when("/home", {
redirectTo : "/"
}).when("/news", {
templateUrl : "news.php"
}).when("/newsinfo/:id", {
templateUrl : "newsinfo.php",
controller: "newsList"
}).otherwise({
redirectTo : "/"
});
}]);
app.controller("newsList", function($scope, $http, $routeParams){
var id = $routeParams.id;
$http.get("newsitem.php?id=" + id)
.then(function(resp){
$scope.item = resp;
});
});
app.filter('unsafe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
});
My newsitem.php looks like:
<?php
require('config2.php');
$id = $_GET["id"];
$newsQuery = $dbh->prepare("SELECT id, article FROM news WHERE id=:id LIMIT 1");
$newsQuery->execute(array(":id"=>$id));
$newsQueryData = $newsQuery->fetch(PDO::FETCH_ASSOC);
echo json_encode($newsQueryData);
?>
My newsinfo.php looks like:
<div class="row">
<div class="col-md-12">
<div class="panel-default panel-custom">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-lg fa-newspaper-o" aria-hidden="true"></i> News</h3>
</div>
<div class="panel-body">
<div ng-controller="newsList">
<div ng-repeat="x in item">
<img src="assets/images/news.png" alt="News" class="img-center img-responsive">
<br>
Tweet
<br>
<br>
<p ng-bind-html="x.article | unsafe"></p>
</div>
</div>
</div>
</div>
</div>
</div>
ISSUE
After the first image, twitter button and actual article, everything gets repeated another five times, so I end up with six images and six tweet buttons where the ID of the repeated five is blank.
Here's a var_dump using htmlentities so you can see exactly what those columns are pulling in.
string(899) "{"id":"610","article":"<p style=\"text-align:center\"><strong><span style=\"font-size:26px\">All of us at habbfinity would like wish our<\/span><\/strong><\/p>\r\n\r\n<p style=\"text-align:center\"><strong><span style=\"font-size:26px\">Builder<\/span><\/strong><\/p>\r\n\r\n<p style=\"text-align:center\"><strong><span style=\"color:#2980b9\"><span style=\"font-size:48px\">Sarah<\/span><\/span><\/strong><\/p>\r\n\r\n<p style=\"text-align:center\"><img alt=\"Image result for happy birthday gif\" src=\"http:\/\/bestanimations.com\/Holidays\/Birthday\/flowers\/happy-birthday-vintage-roses-gold-gif.gif\" \/><\/p>\r\n"}"
I've tried doing:
<div ng-repeat="x in item | limitTo: 1">
That doesn't work.
TEMP FIX
After reading through some of the posts on here, I managed a temporary fix.
I added the following to the newsList controller:
$scope.id = $routeParams.id;
I then changed newsinfo.php by moving the image and twitter button outside of ng-repeat and changed {{x.id}} in the twitter link to {{id}}.
QUESTION
How can I fix this to allow everything to be within the ng-repeat without having to use the temporary fix?
Or is what was done for the temporary fix the better way of doing it anyway?
EDITED ANSWER / QUESTION
Thanks to the suggestion below, I was able to get this resolved.
However, I have one more question.
Is there a way to do this on one page? For example, news.php is just a list of news posts and newsinfo.php is the single news post. Am I able to do something to get it all on news.php and keep the route to only /news, which would show the list if the route isn't news/# or show the specific item if the route is news/#?

How to check another table's columns and get their values to the other table

i am struggling over this problem
Shortly, i have payments page. Admin selects the user and course, then he should select course_type,which gets value from courses table's three columns(cost_group, cost_minigroup, cost_individual,one of them). If course_type is selected, the cost of course must be
inserted into payments table(inside course_cost column). So what i have done
Tables:
payments{ id,student_id, course_id, course_cost}
courses { id, name,cost_group,cost_minigroup,cost_individual }
My CourseController.php
> public function get($id){
> $course = Course::findOrFail($id);
> return response()->json($course);
> }
Here is my form.blade.php
<div class="ui selection dropdown">
<input type="hidden" name="course_">
<i class="dropdown icon"></i>
<div class="default text">Course type</div>
<div class="menu">
<div class="item" data-value="course_group">Group</div>
<div class="item" data-value="course_minigroup">Mini Group</div>
<div class="item" data-value="individual">Individual</div>
</div>
</div>
My PaymentsController
public function store(){
$payment = new Payment;
$payment->student_id = Input::get('student_id');
$payment->course_id = Input::get('course_id');
$payment->course_cost = Input::get('course_cost');
$payment->save();
return redirect('payment');
}
So here is problem how to get this course_cost value out of three columns of courses table. If you know how to solve or any method or advice would be great. Thank you in advance guys.
You should better get the values by js.and in your field(drop-down) there should be this code instead
<div class="menu">
<div class="item" data-value="{{$data['course_group']}}">Your call1</div>
<div class="item" data-value="{{$data['course_minigroup']}}">Your call2</div>
<div class="item" data-value="{{$data['course_individual']}}">Your call3</div>
</div>
And then You should insert some controller code
$payment->course_cost = Input::get('course_val');
And try this on your .js file
$('.course_val').click(function({
$('#course_val').val($(this).attr('data-value'));
alert('Your alert')
}))
On your blade, I see that you named the input as course_ not so sure since the HTML snippet is incomplete, but it may be the cause of your problem.
Better try to check what are you getting before storing it to anything, try to run dd(Input::all()) first as a start for debugging.
As for getting the value of the course cost, there is a lot of approach, one is ajax the updating the fields.

How to pass data from dropdown menu to PHP in CodeIgniter with Bootstrap

I am building an application with Codeigniter and Bootstrap.
What I want to do is to have a dropdown menu which can change a status in sql, and then in background via AJAX call PHP script to do that and display a confirmation message - with bootstrap alert. Everything should be done without page refresh.
The problem is that I can't find a solution to pass the variable from drop down to PHP without page refresh via POST.
I am trying to do something like this:
<!-- AJAX which hide the DIV -->
<script>
$(document).ready(function(){
$("#message").hide();
$('#status li').click(function () {
$("#message").show();
$("#success-alert").load('<?php echo base_url() ?>/changestatus/150/', {my_var : $("#my_var").val()});
$("#message").fadeTo(2000, 500).slideUp(500, function(){
$("#message").hide();
});
});
});
</script>
In the above code, I would like to have a link like: /changestatus/150/2
where 150 is a sample lead id, and 2 is a new status choosen from dropdown.
<!-- Alert DIV, which is hidden on load -->
<div id="message">
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>OK! </strong>
The changes has been done :-)
</div>
</div>
<!-- Dropdown menu -->
<div class="btn-group" id="myDropdown">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Menu
<span class="caret"></span>
</a>
<ul class="dropdown-menu" id="status">
<li>Chg status to 1</li>
<li>Chg status to 2</li>
<li>Chg status to 3</li>
</ul>
</div>
In the above drop down, I do not know where to put the ID numbers 1,2,3.
and how to send it as my_var to AJAX when user clicks option
..and function in my controller
<?
public function changestatus($lead_id)
{
//read a new status from segment in link...
$new_status = $this->uri->segment(4),
//...or from POST
if(isset($_POST['my_var']))
{
$new_status = $_POST['my_var'];
}
// then will be some call to model which mades changes to DB
echo '...done';
}
?>
I've spent a whole day trying to do without success, please help if you can :)
You can make an extra attribute to all your li and assign them values. Get those data attributes in your jQuery code and pass it to the ajax request page.
<ul class="dropdown-menu" id="status">
<li data="1">Chg status to 1</li>
<li data="2">Chg status to 2</li>
<li data="3">Chg status to 3</li>
</ul>
Change jQuery code as below:
$('#status li').click(function () {
var my_var = $(this).attr('data'); //Use this value for your page
$("#message").show();
$("#success-alert").load('<?php echo base_url() ?>/changestatus/150/', {my_var : my_var});
$("#message").fadeTo(2000, 500).slideUp(500, function(){
$("#message").hide();
});
});
Instead of using $("#success-alert").load() you should use $.post to send post data (enter link description here).
$.load uses GET to fetch data from web server.

PHP: Input MySQL query

Hey guys I am a little confused, I have a listing page that displays all of my rows in my SQL table.
An example of what I am developing can be seen here: http://www.drivencarsales.co.uk/used-cars.php
So as you can see I have developed a listing page that fetches all of the table rows, each row is equivalent to one vehicle.
I now want to let users filter the results using the form to the left, I was going to use AJAX originally however I feel as if it would take way to long to learn how to develop it that way.
Here is the code setup I am using to achieve the example I have shown:
<?php
include('database.php');
try {
$results = $db->query("SELECT Make, Model, Colour, FuelType, Year, Mileage, Bodytype, Doors, Variant, EngineSize, Price, Transmission, PictureRefs, ServiceHistory, PreviousOwners, Options, FourWheelDrive FROM import ORDER BY Make ASC");
} catch (Exception $e) {
echo "Error.";
exit;
}
try {
$filterres = $db->query("SELECT DISTINCT Make FROM import ORDER BY Make ASC");
} catch (Exception $e) {
echo "Error.";
exit;
}
?>
As you can see the first block of code has two SQL selectors, the $results is used to fetch the whole table and list all vehicles.
The second block is used to display the 'Make' column for the form.
This block of code is the actual form:
<form>
<select class="form-control select-box" name="">
<option value="make-any">Make (Any)</option>
<?php while($make = $filterres->fetch(PDO::FETCH_ASSOC))
{
echo '
<option value="">'.$make["Make"].'</option>
';
} ?>
</select>
<button href="#" class="btn btn-block car-search-button btn-lg btn-success"><span class="glyphicon car-search-g glyphicon-search"></span> Search cars
</button>
</form>
As you can see this block is using a while loop to display all of the 'Make's' in the 'Make' column and uses a DISTINCT clause so that it doesn't show identical options.
Here is the block that lists the results to the page:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '
<div class="listing-container">
<h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3>
<h3 class="price-listing">£'.number_format($row['Price']).'</h3>
</div>
<div class="listing-container-spec">
<img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/>
<div class="ul-listing-container">
<ul class="overwrite-btstrp-ul">
<li class="diesel-svg list-svg">'.$row["FuelType"].'</li>
<li class="saloon-svg list-svg">'.$row["Bodytype"].'</li>
<li class="gear-svg list-svg">'.$row["Transmission"].'</li>
<li class="color-svg list-svg">'.$row["Colour"].'</li>
</ul>
</div>
<ul class="overwrite-btstrp-ul other-specs-ul h4-style">
<li>Mileage: '.number_format($row["Mileage"]).'</li>
<li>Engine size: '.$row["EngineSize"].'cc</li>
</ul>
<button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked
</button>
<button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details
</button>
<button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive
</button>
<h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4>
</div>
';
} ?>
So down to my question... How can I filter these results displayed in the listing block using the select element, when a user selects a 'Make' from the select element I want them to be able to submit the form and return all rows in the SQL table containing the same 'Make' string and hide other rows that are false.
Any ideas how I can achieve this or any easier ways?
Thanks
My best guess is for you to use JS to submit the form again, when select-option is selected, with a parameter stating the model.
Then in your PHP file, you should look for that parameter and edit the query-string accordingly.
see this answer on how to submit a form when option is selected.
This answer will show you how to handle parameters in PHP (using GET method)

PHP: Filtering SQL query with select options

Hey guys I am a little stuck at the moment, basically I am trying to find out how I can filter my SQL queries however having a bit of trouble understanding how it can be done.
Basically I am listing all of the 'Makes' of the brands I have on my site into a form. I am simply taking the column from my products table that contains every product.
Here is an example of the code, this is the PDO and MySQL selection:
<?php
include('database.php');
try {
$results = $db->query("SELECT Make, Model, Colour, FuelType, Year, Mileage, Bodytype, Doors, Variant, EngineSize, Price, Transmission, PictureRefs, ServiceHistory, PreviousOwners, Options, FourWheelDrive FROM import ORDER BY Make ASC");
} catch (Exception $e) {
echo "Error.";
exit;
}
try {
$filterres = $db->query("SELECT DISTINCT Make FROM import ORDER BY Make ASC");
} catch (Exception $e) {
echo "Error.";
exit;
}
?>
I have added DISTINCT to that block of code as there are duplicate 'Make's' in the SQL column.
Here is the form, as you can see I am using a while loop to display every make in the table into it's own option.
<form>
<select class="form-control select-box">
<option value="make-any">Make (Any)</option>
<?php while($make = $filterres->fetch(PDO::FETCH_ASSOC))
{
echo '
<option value="">'.$make["Make"].'</option>
';
} ?>
</select>
<button href="#" class="btn btn-block car-search-button btn-lg btn-success"><span class="glyphicon car-search-g glyphicon-search"></span> Search cars
</button>
</form>
I am using this code to display the SQL rows into listed results:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '
<div class="listing-container">
<h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3>
<h3 class="price-listing">£'.number_format($row['Price']).'</h3>
</div>
<div class="listing-container-spec">
<img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/>
<div class="ul-listing-container">
<ul class="overwrite-btstrp-ul">
<li class="diesel-svg list-svg">'.$row["FuelType"].'</li>
<li class="saloon-svg list-svg">'.$row["Bodytype"].'</li>
<li class="gear-svg list-svg">'.$row["Transmission"].'</li>
<li class="color-svg list-svg">'.$row["Colour"].'</li>
</ul>
</div>
<ul class="overwrite-btstrp-ul other-specs-ul h4-style">
<li>Mileage: '.number_format($row["Mileage"]).'</li>
<li>Engine size: '.$row["EngineSize"].'cc</li>
</ul>
<button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked
</button>
<button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details
</button>
<button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive
</button>
<h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4>
</div>
';
} ?>
My question is how can I use the selection element to filter the exact 'Make', so for example if the SQL row contains the same 'Make' as the user has selected then I would like the whole row to display into the list and any other makes to not show.
Any code examples to how I can achieve this?
Thanks
You need to have something like:
$where = "";
if (!!$selectedMake) {
$stmt = $db->prepare("SELECT Make, Model, Colour, FuelType, Year, Mileage, Bodytype, Doors, Variant, EngineSize, Price, Transmission, PictureRefs, ServiceHistory, PreviousOwners, Options, FourWheelDrive FROM import ORDER BY Make ASC");
$stmt->execute();
} else {
$stmt = $db->prepare("SELECT Make, Model, Colour, FuelType, Year, Mileage, Bodytype, Doors, Variant, EngineSize, Price, Transmission, PictureRefs, ServiceHistory, PreviousOwners, Options, FourWheelDrive FROM import where Make = ?");
$stmt->execute(array($selectedMake));
}
Note that the order by is not needed in the else block, as you have a unique Make. If your Make is textual, then you might need '%?%' instead of ? in the query.
EDIT:
If I understood well, you still have a problem, namely, you lack the knowledge to determine what the value of $selectedMake should be. First of all, you should have a name for your select tag, so you should have this:
<select class="form-control select-box" name="selected-make">
This way when you submit the form, the value of your selected tag will be sent to the server. So if you want to pass a value when the form submits, you should give the given tag a name.
A form can be get or post. If it is get, then the passed value should be in get. Try it out with:
echo var_dump($_GET);
If it is post, the passed value should be in post. Try it out with:
echo var_dump($_POST);
Finally, you can initialize your $selectedMake like this:
$selectedMake = "";
if (isset($_GET["selected-make"])) {
$selectedMake = $_GET["selected-make"];
} else if (isset($_POST["selected-make"])) {
$selectedMake = $_POST["selected-make"];
}
There are lot of ways to achieve this, but you can use ajax request here.
Send ajax post request to your sql query page with selected option as a post parameter.
On the query page, you can pass that post parameter into where clause of sql query.
Then fill up the table on ajax success response.

Categories