I'm creating a website where the user is supposed to check a couple of checkboxes and then the site will present the data in a table.
I have been looking at this "guide", but cant make it work on my page. I get no results on my index.php, and the submit.php just shows "Array[]"
This is what I have so far:
Index.php holds the checkboxes and the jQuery script.
Checkboxes is in a drop down menu, like this:
<div id="menu">
<div id="mainmenu">Gender</div>
<div id="submenu1" style="display:none">
<div id="submenu"><a href="#">
<input type="checkbox" name="gender" value="male">Male</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="gender" value="female">Female</a></div>
</div>
<div id="mainmenu">Price range</div>
<div id="submenu2" style="display:none">
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="200">200-299$</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="300">300-399$</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="400">400-499$</a></div>
</div>
jQuery script:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function makeTable(data){
console.log(data);
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
function getSnowboardFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.id);
}
});
return opts;
}
function updateSnowboards(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
$('#boards tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getSnowboardFilterOptions();
updateSnowboards(opts);
});
checkboxes.trigger("change");
</script>
At last I have submit.php, which holds the php code for selecting the right stuff.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=...', '...', '...');
$opts = $_POST['filterOpts'];
$qMarks = str_repeat('?,', count($opts) - 1) . '?';
$statement = $pdo->prepare("SELECT gender, price_range, brand, model, rocker_type, flex, size_range, image FROM snowboards)");
$statement -> execute($opts);
$results = $statement -> fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
Right now the SELECT query isn't specified, because I don't know how.
If someone knows what I'm doing wrong, or have better suggestion to solve it, please tell.
Related
Output of my requirement
I have tried many times to get the required result in html page.
am calling a function when i check a box in html ,the function giving back result of json data and this json data i wanna display dynamically into my card style.
Here is hmtl code:
<div id="filter"style="margin-top:100px;margin-left:100px">
<h2>Filter options</h2>
<div>
<input type="checkbox" id="Samsung" checked>
<label for="Samsung">Samsung</label>
</div>
<div>
<input type="checkbox" id="iPhone" checked>
<label for="iPhone">iPhone</label>
</div>
<div>
<input type="checkbox" id="HTC" checked>
<label for="HTC">HTC</label>
</div>
<div>
<input type="checkbox" id="LG" checked>
<label for="LG">LG</label>
</div>
<div>
<input type="checkbox" id="Nokia" checked>
<label for="Nokia">Nokia</label>
</div>
</div>
<table id="phones" >
<thead>
</thead>
<tbody >
<div style="margin-top:100px;margin-left:100px;margin-right:100px" >
<div>
<label style="margin-bottom:50px;margin-left:80px"><h2>Find your best hotel</h2></label>
</div>
<div class="col-xs-12 col-sm-4" style="background-color:lavender;height:310px;width:310px"><label id="hotel_image"></label></div>
<div class="col-xs-12 col-sm-6" style="background-color:lavenderblush;"><label id="hotel_name"></label></div><br>
<div class="col-xs-12 col-sm-3" style="background-color:lavender;margin-left:100px;margin-top:10px"><label id="hotel_price"></label></div>
<div class="col-xs-12 col-sm-3" style="background-color:#ccc;margin-top:220px;margin-left:300px"><label id="book_me"></label></div>
</div>
</tbody>
</table>
Here is javascript code:
<script>
function getPhoneFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.id);
}
});
return opts;
}
function updatePhones(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(data){
$.each(data, function() {
$.each(this, function(k , v) {
if(k==='img_path'){
v = "<a href='image_description.html'><image src='img_path' height='300px' width='300px' ></a>";
("#hotel_image").html(v);
} else if (k==='price'){
("#hotel_price").html(v);
} else if (k==='brand'){
("#hotel_name").html(v);
}
})
});
}
})
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getPhoneFilterOptions();
updatePhones(opts);
});
$checkboxes.trigger("change");
</script>
am geeting data json data from submit.php like this:
[
{
"img_path":"photo1.jpg",
"price":"2000",
"brand":"AAMSOTO"
},
{
"img_path":"photo4.jpg",
"price":"2500",
"brand":"AfMSOTO"
},
{
"img_path":"photo2.jpg",
"price":"3000",
"brand":"CAMSOTO"
},
{
"img_path":"photo3.jpg",
"price":"4000",
"brand":"BAMSOTO"
}
]
Assuming data is a javascript object the following inside your success method should work:
Make sure data is a javascript object, if its not you will have to use JSON.parse() to turn the JSON data into one.
$.each(data, function() {
var imageUrl = this['img_path']
var price = this['price']
var brand = this['brand']
const img = document.createElement('img');
img.src = imgUrl;
document.getElementById('#hotel_image').appendChild(img);
document.getElementById('#hotel_price').appendChild(document.createTextNode(price));
document.getElementById('#hotel_name').appendChild(document.createTextNode(brand));
}
I want select result Ajax request and Replace it on my input.
result display in result div,I want selected one of them and insert to mobile input and hidden results
<form method="post" action="#" class="form-horizontal" id="adduser">
<div class="form-group"><label class="col-sm-2 control-label">Mobile</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="mobile" id="mobile" autocomplete="off" />
<div id="result"></div></div>
</div>
<input type="submit" name="useradd" id="useradd" class="btn btn-block btn-w-m btn-success" value="add">
</form>
ajax jquery :
<script>
$(document).ready(function(){
var req = null;
$('#mobile').on('keyup', function(){
var mobile = $('#mobile').val();
if (mobile && mobile.length > 2)
{
$('#loading').css('display', 'block');
if (req)
req.abort();
req = $.ajax({
url : 'ajax.php',
type : 'POST',
cache : false,
data : {
mobile : mobile,
},
success : function(data)
{
console.log(data)
if (data)
{
$('#loading').css('display', 'none');
$("#result").html(data).show();
}
}
});
}
else
{
$('#loading').css('display', 'none');
$('#result').css('display', 'none');
}
});
});
</script>
fetch data and return in Ajax.php
if(isset($_POST['mobile'])) {
$user = new User();
$result = $user->Searchuser($_POST['mobile']);
$mobiles= array();
$names = array();
while ($info = $result->fetch(PDO::FETCH_ASSOC)) {
echo $info['firstname'].'-'.$info['mobile'].'<br/>';
}
}
Look this pic :
I want select Dany and insert that to mobile input
Here is my ajax
$(".submit").click(function(){
var vp = $("input#vehicle_plate").val();
var vm = $("input#vehicle_model").val();
var vt = $("input#vehicle_type").val();
var da = $("input#date_acquired").val();
var ad = $("input#assigned_driver").val();
var dataString = 'vehicle_plate='+ vp + '&vehicle_model='+ vm + '&vehicle_type='+ vt + '&date_acquired='+ da + '&assigned_driver='+ ad;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
And here is my PHP where i pass my 'dataString'
<?PHP
include("db.classes.php");
$g = new DB();
$g->connection();
if($_POST)
{
$vehiclePlate = $g->clean($_POST["vehicle_plate"],1);
$vehicleModel = $g->clean($_POST["vehicle_model"],1);
$vehicleType = $g->clean($_POST["vehicle_type"]);
$assignedDriver = $g->clean($_POST["assigned_driver"],1);
$ad = date('Y-m-d', strtotime($_POST["datepicker"]));
$g->add($vehiclePlate, $vehicleModel, $vehicleType, $assignedDriver, $ad);
}
$g->close();
?>
And here is my database query
public function add($vehiclePlate, $vehicleModel, $vehicleType, $assignedDriver, $ad)
{
$sql = "insert into vehicles(`vehicle_plates`,`DA`,`type`, `model`, `driver`) values('$vehiclePlate', '$ad', '$vehicleType', '$vehicleModel', '$assignedDriver')";
if(!mysql_query($sql))
{
$this->error = mysql_error();
return true;
}
else
{
return false;
}
}
the AJax returns succesful but when i try and see the table in my databse the inserted row are al 'Undefined' what seems to be causing this?
EDIT:
Here is my HTML
<div id="rform">
<form action = "list.php" method="post">
<fieldset>
<legend>Fill Up the Form</legend><br>
<div>
<label class="label-left">*Vehicle Plate:</label>
<input class="label-left" type="text" name="vehicle_plate" id="inputbox1" value maxlength="50">
</div>
<div>
<label class="label-left">*Vehicle Type:</label>
<select class="label-left" id="inputbox" name ="vehicle_type" onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
<option value="Motorcycle">Motorcycle</option>
<option value="Tricycle">Tricycle</option>
<option value="Pick-up">Pick-up</option>
<option value="Truck">Truck</option>
</select><br><br>
</div>
<div>
<label class="label-left">*Vehicle Model:</label>
<input class="label-left" type="text" name="vehicle_model" id="inputbox" value maxlength="50">
</div>
<div>
<label class="label-left">Date Acquired:</label>
<input class="label-left" name="date_acquired" id="datepicker" value maxlength="50"><br><br>
</div>
<div>
<label class="label-left">Assigned Driver:</label>
<input class="label-left" type="text" name="assigned_driver" id="inputbox" value maxlength="50"><br><br>
</div>
<div>
<label class="label-custom" color = red>NOTE: "*" Fields are required</label><br><br>
</div>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
<input id="button" type="submit" value="Add" name = "subBtn" class = "submit"/>
</fieldset>
</form>
</div>
Well the problem is with your selectors:
var vp = $("input#vehicle_plate").val();
var vm = $("input#vehicle_model").val();
var vt = $("input#vehicle_type").val();
var da = $("input#date_acquired").val();
var ad = $("input#assigned_driver").val();
Your input selectors doesn't have any id attribute instead you need to select them by their name attribute (or you can give id attributes to your html input elements so your above selectors will work):
var vp = $("input[name=vehicle_plate]").val();
var vm = $("input[name=vehicle_model]").val();
var vt = $("input[name=vehicle_type]").val();
var da = $("input[name=date_acquired]").val();
var ad = $("input[name=assigned_driver]").val();
It will pass your values correctly to server.
you are concatenating your dataString like a GET - string which is used for passing it via URLs but doesn't work in POST - requests like this.
you have to pass your POST data inside an javascript-object:
data: { vehicle_plate: vp, vehicle_model: vm, vehicle_type: vt }
...and so on.
Use serialize() it's simpler and less prone to errors.
$(".submit").click(function () {
var dataString = $("#rform form").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function () {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
I'm new in bootstrap and i need some help please, i want to create a typeahead drop-down that return 3 values from my mysql database when the user search for a contact name in "ContactName" TEXTBOX and fill up 3 edit box with the information of
-contact name
-Telephone Number
-email address
thanks a lot on advance for all your effort
this is the code that i try it to return one value i need to modified to return all those tree value
Now when i try to search the contact name it will return with correctly with no question to ask but i don't know how to modify the code to bring 3 value like i mention above
enter code here
**php page: Customer.php**
-------------------------------------------
<?php
$host = "localhost";
$uname = "root";
$pass = "";
$database = "db34218";
$connection=mysql_connect($host,$uname,$pass) or die("connection in not ready <br>");
$result=mysql_select_db($database) or die("database cannot be selected <br>");
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysql_query ("SELECT ContactName, Telephone, Email FROM customer WHERE ContactName LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['ContactName'];
}
echo json_encode ($array); //Return the JSON Array
}
?>
**html and java page and some php: Customersearch.php**
------------------------------------------------
<body>
.
.
.
<div class="row-fluid">
<div class="span4">
<label>ContactName </label>
<input type="text" name="ContactName" value="<?php echo $row_Recordset_QuoteCustomer['ContactName']?>" data-provide="typeahead" class="typeahead input-xlarge" autocomplete="off">
</div>
<div class="span2">
<label>Telephone </label>
<input type="text" name="Telephone" value="<?php echo htmlentities($row_Recordset_QuoteCustomer['Telephone'], ENT_COMPAT, 'utf-8'); ?>" class="span12">
</div>
<div class="span2">
<label>Email </label>
<input type="text" name="Email " value="<?php echo htmlentities(row_Recordset_QuoteCustomer['Email '], ENT_COMPAT, 'utf-8'); ?>" class="span12">
</div>
.........
.
.
.
.
.
.
<script src="../js/jquery.js"></script>
<script src="../js/bootstrap-transition.js"></script>
<script src="../js/bootstrap-alert.js"></script>
<script src="../js/bootstrap-modal.js"></script>
<script src="../js/bootstrap-dropdown.js"></script>
<script src="../js/bootstrap-scrollspy.js"></script>
<script src="../js/bootstrap-tab.js"></script>
<script src="../js/bootstrap-tooltip.js"></script>
<script src="../js/bootstrap-popover.js"></script>
<script src="../js/bootstrap-button.js"></script>
<script src="../js/bootstrap-typeahead.js"></script>
<script src="../js/SpecWorkPages/getItemsList.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('input.typeahead').typeahead({
source: function (query, process)
{
$.ajax(
{
url: 'Customer.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data)
{
console.log(data);
process(data);
}
});
}
});
})
</script>
</body>
</html>
<?php
mysql_free_result($RecordsetQuote);
mysql_free_result($Recordset_QuoteStatus);
mysql_free_result($Recordset_QuoteCustomer);
?>
If I'm understanding you correctly, you are getting results back but unable to populate the input fields. Although I don't use Twitter Bootstrap typeahead I do something very similar with jQuery's autocomplete feature. The code below is untested and of course you'll need to modify it for yourself but hopefully will be of some help.
See this working jsFiddle demo for something similar.
PHP
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
array_push($array,array('ContactName'=>$row['ContactName'],'Telephone'=>$row['Telephone'],'Email'=>$row['Email']));
}
echo json_encode($array);
You can check what gets returned by manually entering the URL (ex: yoursite/Customer.php?query=SomeContactName). You should see something similar to this:
[{"ContactName":"Some Contact","Telephone":"5555555555","Email":"email#whatever.com"},
{"ContactName":"Some Other Contact","Telephone":"5555555555","Email":"anotheremail#whatever.com"}]
HTML/Javascript
<script>
$('input.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: 'Customer.php',
type: 'POST',
dataType: 'JSON',
// data: 'query=' + query,
data: 'query=' + $('#contactName').val(),
success: function(data)
{
var results = data.map(function(item) {
var someItem = { contactname: item.ContactName, telephone: item.Telephone, email: item.Email };
return JSON.stringify(someItem.contactname);
});
return process(results);
}
});
},
minLength: 1,
updater: function(item) {
// This may need some tweaks as it has not been tested
var obj = JSON.parse(item);
return item;
}
});
</script>
Here are a couple other posts that you might want to take a look at How to return the response from an AJAX call? and Bootstrap typeahead ajax result format - Example
i am using Ajax to make a filtered search system. I have three different tabs where users can search by names, by category and location.
I am able to seacrh when user enters name in the search box(tab-1).
In second tab, how can I use the same Ajax, so when user clicks a link, the id is passed in the ajax script to my php, and that id is passed as varibale in my mysql query.
First time with Ajax, any help would be highly appreciated.
AJAX script:
$(document).ready(function () {
$("#search_results").slideUp();
$("#button_find").click(function (event) {
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function (event) {
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way() {
$("#search_results").show();
var search_this = $("#search_query").val();
$.post("search.php", {
searchit: search_this
}, function (data) {
$("#display_results").html(data);
})
}
html:
<form id="searchform" method="post">
<input id="search_query" name="search_query" placeholder="What You Are Looking For?"
size="50" type="text" />
<input id="button_find" value="Search" type="submit" />
</form>
<div id="display_results">
</div>
<div class="tab">
<input id="tab-2" name="tab-group-1" type="radio" />
<label for="tab-2">Search by Category</label>
<div class="content">
<div id="searchbycategory">
<div id="nav_1_a">
<ul>
<li>All Categories</li>
<li>Category-1</li>
<li>Category-2</li>
<li>Category-3</li>
</ul>
<div id="display_results">
</div>
</div>
<!-- END nav_1_a -->
</div>
</div>
</div>
<div class="tab">
<input id="tab-3" name="tab-group-1" type="radio" />
<label for="tab-3">Search by location</label>
<div class="content">
<div id="searchbylocation">
<div id="nav_1_a">
<ul>
<li>All</li>
<li>Location-1</li>
<li>Location-2</li>
<li>Location-3</li>
<li>Location-4</li>
</ul>
</div>
search.php:
<?php
$connection = mysql_connect('localhost', 'user', 'pwd');
$db = mysql_select_db('db', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term);
echo "Enter name to search";
else{
$sql = mysql_query("select col1,col2 from tab2 where tab2.somecolm like
'{$term}%'", $connection);
echo "<ul>";
if (mysql_num_rows($sql)){
while($info = mysql_fetch_array($sql, MYSQL_ASSOC ) ) {
echo "<li>";
echo "" . $info['col2'] . "";
echo "</li>";
}
}else{
echo "No matches found!";
}
echo "</ul>";
}
?>
Pass block id to search_ajax_way function:
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way(this.id);
});
Then pass block id in data param in ajax request:
function search_ajax_way(blockId){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this, 'blockId': blockId}, function(data){
$("#display_results").html(data);
})
}
Now blockId will be availible in your php script as $_POST['blockId'].
You say you want to pass the id when a link is clicked, but you don't have any code that handles link clicks. Add a click handler for links, and modify search_ajax_way() to accept an optional id for when links are clicked:
$("a").click(function (event) {
event.preventDefault();
search_ajax_way(this.id);
});
function search_ajax_way(clickedId) {
$("#search_results").show();
var postData = { searchit: $("#search_query").val() };
if (clickedId) {
postData.clickedId = clickedId;
}
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}
The id will be available in PHP as $_POST['clickedId']
Edit: Actually, I'd refactor to use search_ajax_way() as the event handler, rather than calling it from an anonymous event handler:
$("#button_find,a").click(search_ajax_way);
$("#search_query").keyup(search_ajax_way);
function search_ajax_way(event) {
event.preventDefault();
$("#search_results").show();
var postData = {
searchit: $("#search_query").val(),
clickedId: this.id
};
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}