I can not make a search using this check boxes. When I run the code (check), nothing happens. I have to check it for make an advance search and it will select data from database.
My HTMLcode:
<td><input type="checkbox" name="fac1" value="checked"/>AIRCOND</td>
<td><input type="checkbox" name="fac2" value="checked"/>FAN</td>
My PHP code:
$fac1=isset($_POST["fac1"]);
$fac2=isset($_POST["fac2"]);
$qry = "SELECT * FROM homestay WHERE ";
if(isset($_POST['fac1']) && $_POST['fac1'] == 'checked')
{
$fac1 = true;
}
if(isset($_POST['fac2']) && $_POST['fac2'] == 'checked')
{
$fac2 = true;
}
$string = isset($_POST['fac1']) ? $_POST['fac1'] : (isset($_POST['fac2']) ? $_POST['fac2'] : '');
OR
if(isset($_POST['fac1']) && $_POST['fac1'] == 'checked')
{
$string = $fac1;
}
if(isset($_POST['fac1']) && $_POST['fac2'] == 'checked')
{
$string = $fac2;
}
Pass your string variable in query:
$qry = "SELECT * FROM homestay WHERE $string = 'true'";
Doing it like as Ronak suggested would result in a way too long code for multiple search options. Not counting that you have to save every option checked next time you load the page with one option checked.
You could simplify this with ajax, so that it would display the results in your div for example.
first make a form:
<form id="searchOptions">
<td><input type="checkbox" name="fac1" value="checked"/>AIRCOND</td>
<td><input type="checkbox" name="fac2" value="checked"/>FAN</td>
</form>
Then put the script in header:
<script>
function submitSearchForm() {
$.ajax({type:'POST', url: 'search.php', data:$('#searchOptions').serialize();?>, success: function(response) {
$('#resultDisplay').innerHTML = response;
}});
return false;
}
</script>
Notice:
You will also need jquery.min in header
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Related
I want to create a dropdown list that populated by another dropdown list. I'm using AJAX and PHP.
I have created my AJAX file like this:
<?php
if(isset($_POST['selname']))
{
include('config.php');
$clientId = $_POST['selname'];
$query = "SELECT tv.*, v.* FROM t_vorder tv LEFT JOIN m_vehicle v ON tv.tv_vehicleid = v.v_id WHERE tv_orderid = '$clientId'";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$namek = "";
$namek .= $row['v_id'];
if($row['v_jenis'] != "" || !empty($row['v_jenis']))
{
$namek .= ' - '.$row['v_jenis'];
}
if($row['v_platno'] != "" || !empty($row['v_platno']))
{
$namek .= ' - '.$row['v_platno'];
}
if($row['v_merk'] != "" || !empty($row['v_merk']))
{
$namek .= ' - '.$row['v_merk'];
}
$xx .= "<option value='$row[v_id]'>$namek</option>";
}
return $xx;
exit;
}
?>
After that, I called this AJAX file to my main program, here's my JQuery code:
function getVehicle()
{
var selname = $("select[name=noorder]").val();
$('#combobox2').html('');
$.ajax({ url: "getVehicle.php",
data: {"selname":selname},
type: 'post',
dataType: "json",
success: function(output) {
console.log(output);
$('#combobox2').append(output);
}
});
}
And last is my HTML code:
<select name="noorder" id="combobox" class="form-control">
//get my vehicle from database
<?php
$querycon = mysqli_query($conn, "SELECT * FROM m_order WHERE o_status='1' ORDER BY o_id");
while($rowcon = mysqli_fetch_array($querycon, MYSQLI_ASSOC))
{
$invoice = sprintf("%s%"."04d", $rowcon['o_code'], $rowcon['o_id']);
?>
<option value="<?php echo $rowcon['o_id']; ?>"><?php echo $invoice; ?></option>
<?php
}
?>
</select>
<select name="kendaraan" class="form-control" id="combobox2" onclick="getVechile();">
</select>
My Ajax works fine, my console log return that the file finished load. But my dropdown list not appended by Jquery. Anyone know where's my mistakes?
You did't request for json obj/data into ajax success callback, then no need for dataType: "json", inside ajax properties. Remove that and change return $xx; into echo $xx;
AJAX request gets data from PHP file only when its printed out on the page.
Returning and data from PHP (AJAX backend) to jQuery/Javascript does not mean anything.
Change
return $xx;
to
echo $xx;
You use the dataType: "json" in your ajax call, so it get response in JSON. First remove dataType: "json" line from ajax call. Then replace return $xx; with echo $xx; in your php script.
Hope this solution may works for you, Thanks!
I have some code which populates like so:
<select class="form-control" name="accommodation_ID" id="accommodation_ID">
<option value="-1">-- Please Select --</option>
<?php
$AccomodationID = 13; //For testing purposes
$accommodation_query = mysqli_query($conn,"SELECT ENTITIES.LastName,
ACCOMMODATION.AccomodationID, ACCOMMODATION.PUPoint
FROM ACCOMMODATION, ENTITIES WHERE ENTITIES.Entity_ID =
ACCOMMODATION.Entity_ID")
or die("Error: ".mysqli_error($conn));
while($accommodation_Results = mysqli_fetch_array($accommodation_query)){
if($accommodation_Results['AccomodationID'] == $AccomodationID){
echo '<option selected value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
$PUPoint = $accommodation_Results['PUPoint'];
}
else{
echo '<option value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
}
}
?>
</select>
<label>Pick Up Point</label>
<input type="text" name="PUPoint" readonly value="<?php echo $PUPoint; ?>">
This code works no problem, it checks the database and looks for a match, if it does, set is as the selected option, grab the PUPoint (Pickup point) variable and store it in the input field.
My problem now, is when I go to select a different option from the dropdown list, the pickup point input field doesn't update anymore. This is what I had, working before I implemented the above:
j$('select[name=accommodation_ID]').change(function(event) {
event.preventDefault();
var accommodationID = j$(this).val();
post_data = {'accommodation_ID':accommodationID};
var data = {
"action": "Accommodation_Details"
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
j$('input[name=PUPoint]').val( data["PUPoint"] );
},
error: function (request) {
console.log(request.responseText);
}
});
});
booking_Modify.php
//checks and switch statement related code
$return = $_POST;
$return["accommodation_ID"] = $_POST["accommodation_ID"];
$return["SQL"] = "SELECT * FROM ACCOMMODATION WHERE AccommodationID = ".$_POST["accommodation_ID"]."";
$query = mysqli_query($conn,"SELECT * FROM ACCOMMODATION WHERE AccomodationID = ".$_POST["accommodation_ID"]."")
or die("Error: ".mysqli_error($conn));
$row = mysqli_fetch_array($query);
$return["PUPoint"] = $row["PUPoint"];
$return["json"] = json_encode($return);
echo json_encode($return);
I've done some echoing/console.log and noticed that it's always passing the same Accommodation ID number (13) into booking_Modify.php. It doesn't change when I select a different option now. I don't know if it's because of the "selected" attribute applied to the option element now. Any ideas would be greatly appreciated
You have defined your $AccomodationID = 13; //For testing purposes before which is printed in every iteration of the while loop instead of the current ID. Probably you want to write $accommodation_Results['AccomodationID'] as the option value.
I'm trying to create a HTML table that lists all the rows in a database table. Then, next to each row I want to have a button so the user can delete that entry. I have created the table but I can't get the buttons to work.
I have been searching around and I found this post How to Call a PHP Function on the Click of a Button but I can't get it to work. I've never used ajax before so I might not understand the code correctly.
Here is the code:
Go through all the data from the table and create a button for each entry
<?php
for ($x = 0; $x < sizeof($data); $x++) {
?>
<input type="submit" class="tableButton" name="<?php echo $x ?>" value="<?php echo $x ?>">
<?php
}
?>
When a tableButton is clicked, send its value to ajax.php
$('.tableButton').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = { 'action': clickBtnValue };
$.post(ajaxurl, data, function (response) {
});
});
ajax.php
Get the value of the button that was pressed and do something with it
<?php
if (isset($_POST['action'])) {
$data = $_POST['action'];
echo $data;
}
?>
Currently I just have it echo the value to test it but it's displaying nothing. What I would have it do is run this query:
DELETE from myTable WHERE id = $data;
Or if someone knows a better way to do this please let me know.
Edit
After doing a lot more searching I found out why this wasn't working how I expected. As I suspected since I've never used AJAX before there was something I missed, I didn't know the echo wouldn't print directly to the screen. I just changed the echo to a delete query and tested that and it works... So the code is fine, but I think I should learn AJAX sometime. Thanks for all the responses.
I'm also aware of the sql injection that is possible here, this was just a quick mock-up, thanks.
It is hard to help you from this point of view we got.
You should do some debugging, like:
Check if the associated ajax.php is called (by checking the console with "F12" for example)
If yes, check the data being passed through your ajax POST
If not, maybe the reference link is wrong
Let me hear what you got.
You can try by this way. I think it will help you
Html File
<html>
<head>
<title>Test</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$('.tableButton').live('click', function(){
var id = $(this).val();
$.ajax({
url:'ajax.php'
,data:{id:id}
,type:'post'
,success:function(data){
if(data == 'success'){
$('#' + id).remove();
}
}
});
});
</script>
<?php
for ($x = 0; $x < 5; $x++) {
?>
<input type="submit" class="tableButton" id="<?=$x?>" name="<?php echo $x ?>"value="<?php echo $x ?>">
<?php
}
?>
</body>
</html>
ajax.php
<?php
if(isset($_POST['id'])){
$id = $_POST['id'];
//delete operation here
//if(deleted) echo 'success';
}
?>
Ok. First of all you need to create the button with row id. You can do it using mySQL and PHP loops. Create it in this following format.
<input type="submit" name="test" data-id="23" value="Remove" class="delete_row" />
<input type="submit" name="test" data-id="24" value="Remove" class="delete_row" />
<input type="submit" name="test" data-id="25" value="Remove" class="delete_row" />
<input type="submit" name="test" data-id="26" value="Remove" class="delete_row" />
Here replace the data-id in each button with the id of row you are looking to delete.( Replace 23,24 etc with database ids dynamically ).
Java script
$(document).ready(function(){
$(".delete_row").click(function(e){
e.preventDefault();
var deleteId = $(this).attr("data-id");//unique id of the raw to be deleted
var request = $.ajax({
url: "ajax.php",
type: "POST",
data: { id : deleteId },
dataType: "json"
});
request.done(function( msg ) {
if( msg.status )
alert("Deleted successfully!");
else
alert("Something gone wrong!!");
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
ajax.php
<?php
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$delete_id = $_POST["id"];
if( is_numeric( $delete_id ) ){
/*DELETE QUERT WHERE id = $delete_id (Try to use mysqli or PDO ) */
/* $affected_rows = effected_rows() */
if( $affected > 0 )
{
echo json_encode( array("status" => true ) );die;
}
}
echo json_encode( array("status" => false ) );die;
}
die("Get out of here!");
?>
I hope this will help you :)
I have an autocomplete jQuery menu, that output the name of all the users I have, from a MySQL database. I'm trying to link each selection to the proper profile. For that, the URL is something like: /profile.php?id=341, 341 that stands for the ID of the user selected.
The only problem, is that when I try to put the ID of a given user, ALL the ID of ALL the user are shown in the URL... and I want only the ID of the selected user!
I have tried with PHP, but I don't know what to add to the following line to make it work.
$req = mysql_query("select id, Username, EmailAddress from ***");
Should it be something like WHERE Username='username'....? Finally, I know that I should maybe try something else, without PHP, but I just want to test it that way! Thanks!
<input type="text" name="course" id="course" />
<script type="text/javascript" src="jquery.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#course").autocomplete("/test/test2.php", {
selectFirst: false,
formatItem: function(data, i, n, value) {
//make the suggestion look nice
return "<font color='#3399CC'>" + value.split("::")[0] + "</font>";
},
formatResult: function(data,value) {
//only show the suggestions and not the URLs in the list
return value.split("::")[0];
}
}).result(function(event, data, formatted) {
//redirect to the URL in the string
var pieces = formatted.split("::");
window.location.href = '/profile.php?id='+
<?php
mysql_connect ("***", "***","***") or die (mysql_error());
mysql_select_db ("***");
$req = mysql_query("select id, Username, EmailAddress from ***");
while($dnn = mysql_fetch_array($req))
{
echo $dnn['id'];
}
?>
;
console.log(data);
console.log(formatted);
});
});
</script>
Your MySQL query is true to every user in the database, so it returns all the users. If you want to go to "foo"'s profile, you need to tell the database to fetch "foo"'s id only. A unique row that the user has maybe there email and must be their username.
I assume you have an array in javascript which contains selected users:
var users = new Array("Daniel","Amy","Sandy");
then you need to use ajax to communicate to php:
<script>
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}//This can become an external file to link
</script>
so then you can post data to php:
<script>
var returnedStr = "";
function searchuser(){ //use searchuser function on a button to call
var usersStr = users.toString(); //the string that contain the users separated by ","
var ajax = ajaxObj("POST", "thisurl.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "fail"){ //i didn't include this in php, but you can add it yourself if you can't fetch from mysql
echo "Failed";
} else {
returnedStr = ajax.responseText;// when php echos
}
}
}
ajax.send("u="+usersStr);
}
</script>
then your php will need to handle the string:
<?php
if(isset($_POST["u"])){
$returnArr = array();
$returnStr = "";
$processedArr = explode(',', $_POST['u']); //Here the posted data will turn into an array
$lengthArr = count($processedArr);
for ($i=0; $i<=$lengthArr; $i++)
{
$req = mysql_query("SELECT id FROM xxx WHERE Username='$processedArr[$i]' LIMIT 1");
while($dnn = mysql_fetch_array($req))
{
array_push($returnArr, $dnn['id']);
}
}
$returnStr = implode(",",$returnArr);
echo ($returnStr);
}
?>
Now in Javascript returnedStr will hopefully be 1,2,3 or something like that.
Please comment if this doesn't work!
I am developing ajax Based Search , This is demo of how it will be. I am faceing Problem in returning result. I need to show the Result 2 times. But its only showing once. Below is my HTML code
<form action="" method="post" id="demoform">
<select style="width:250px;padding:5px 0px;color:#f1eedb;" name="product" class="product">
<option>TENNIS</option>
<option>FOOTBALL</option>
<option>SWIMMING</option>
</select>
</form>
<div id="result">Display Result Here</div>
I Using The Below Ajax Script to Retrieve Data :-
$(".product").change(function(){
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
product : $(".product option:selected").text(),
},
success : function(data){
$('#result').removeClass().addClass((data.error === true) ? 'error' : 'success')
.html(data.msg).show();
if (data.error === true)
$('#demoForm').show();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#result').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show();
}
});
});
The post.php file has the following code :-
<?php
require('connect.php');
$get_select = $_POST[product];
if($get_product!='FOOTBALL'){
$return['error'] = true;
return['msg'] = 'Incorrect Selection';
echo json_encode(return);
}
else {
$return['error'] = false;
$i=0;
while($i<2) {
return['msg'] = $get_product;
}
echo json_encode(return);//Returns only one result.
}
?>
I need to show the result Two times as "CRICKET CRICKET", but its only showing once.
What should i do to get both the result.
Is it possible that this line is confusing php:
while($i<2) {
return['msg'] = $get_product;
}
Should it be $return? Using a reserved word like 'return' is a tad iffy too.
Please change the following code:
else {
$i=0;
$messageToReturn = "";
while($i<2) {
$messageToReturn .= $get_product; //Append to your variable
}
return json_encode($messageToReturn); //Returns the result
}
I would suggest to change the while to a for loop.
In that case you will get this:
else {
$messageToReturn = "";
for($i = 0; $i < 2; $i++)
{
$messageToReturn .= $get_product; //Append to your variable
}
return json_encode($messageToReturn);
If you know the times you need to repeat, use a for loop. The while is never ending. So you can get a possible stack overflow...