display Specific data using Ajax and jquery and html select button - php

hello community i need help on this what i really want to do is to select from database using onchange() function through Ajax.then return the result to the client.i used Ajax to send the information to the server side and but i am having problem return it with the where condition
//this is the html page
<body style="font-family:arial bold; ">
<div style="text-align:left; padding:1%; font-family:Arial bold; color:#cccccc;font-size:40px;"> Select</div>
<select class="form-control" id="color" name="color" >
<option >Please select an option</option>
<option> Red</option>
<option >Yellow</option>
<option >white</option>
<option >Black</option>
<option >Violet</option>
</select>
<br/>
//this is where the output will be displayed with parameter (res);
<div id="dis"></div>
</body>
//this is the script.js
$(function(){
$('#color').on('change', function()
{
var selt= this.value ;
d = $('#color').val();
alert(d);
$.ajax({
url: "ajax-cart.php",
method: "POST",
data: {
request:"select",
selt:selt
}
}).done(function(res) {
$('#dis').val(res) ;
console.log(res);
});
});
//this is ajax cart.php
<?php// START THE SESSION
session_start();// CONFIGURATION
require("db.php");
// PROCESS REQUESTS
switch ($_POST['request']) {
// THIS PART is for the select button
case "select":
require("db.php");
$conn = new mysqli($dbServername, $dbUsername, $dbPassword, $dbName );
$val = $_POST['selt'];
$data = $conn->query("SELECT * FROM `goods` where color = '.$val.' LiMIT 4");
echo Json_encode($data);
break;
this is the console result {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}

#Blessed Media you just missed fetching mysql result, you are just returning query not result.
change your query to
$data = $conn->query("SELECT * FROM goods where color = '".$val."' LiMIT 4");
Add
$result = $data->fetch_array(MYSQLI_ASSOC);
after
$data = $conn->query("SELECT * FROM goods where color = '.$val.' LiMIT 4");
and then
echo json_encode($result);

When sending query to database you don't need to concatenate variables into the query. Just use variables as defined:
Wrong:
$data = $conn->query("SELECT * FROM `goods` where color = '.$val.' LiMIT 4");
Correct:
$data = $conn->query("SELECT * FROM `goods` where color = '$val' LiMIT 4");
After that you will need to produce data from query result. Please check this Q/A for more details.

Related

Query new data based on combobox, and display it in new textbox

I have a combobox that contains a project number id. Based on the selection of this combobox I want to display the amount of rows in another table containing the same project number id. This value will be appended to the blue box "Number of POs".
My file "new-customer-po.php". I'll display it in parts for simplicity.
<?php
//Query for projectnumber
$query_1 = "SELECT PROJECTNOID, ProjectNumber, ProjectTitle, (SELECT (SELECT
CustomerName FROM tblCustomers WHERE Customer = CUSTOMERID) AS Customer
FROM tblCustomerContacts WHERE CustomerProjectLeadID =
CUSTOMERCONTACTID) AS CustomerProjectLeadID FROM tblProjects ORDER BY
ProjectNumber DESC";
$result_1 = mysqli_query($conn, $query_1);
$options_1 = "";
while($row_1 = mysqli_fetch_array($result_1))
{
$options_1.='<option value="'.$row_1[0].'">'.$row_1[1]." - ".$row_1[2]." - ".$row_1[3].'</option>';
}
?>
further down this page I have the following html
<label>Project Number <b style="color:red;">*</b></label>
<select id="proj" name="projectnum" class="inputvalues" required>
<option disabled selected value>-- Project # - Title - Customer --</option>
<?php echo $options_1; ?>
</select><br>
<div id="currentnumpo">
<label>Number of POs</label><input name="numpos" class="inputvalues" id="reqtxtfield" readonly/><br>
</div>
and after the closing html tag
<script type="text/javascript" >
jQuery(document).ready(function($) {
$("#proj").on('change', function() {
var num = $(this).val();
if(num){
$.ajax ({
type: 'POST',
url: 'getnumberpo.php',
data: { num },
success : function(htmlresponse) {
$('#currentnumpo').html(htmlresponse);
console.log(htmlresponse);
}
});
}
});
});
</script>
My "getnumberpo.php"
<?php
echo $_POST['projectnum'];
if(isset($_POST['projectnum'])){
$sql = "SELECT COUNT(*) FROM tblCustomerPOs WHERE ProjectNum = '".$_POST['projectnum']."'";
$result = $conn->query($sql);
if ($sql) {
while($row = $conn->query($sql)) {
echo '<label>Number of POs</label><input name="numpos" class="inputvalues" id="reqtxtfield" placeholder="';
echo $row[0];
echo '" readonly/><br>';
}
}
$sql = NULL;
}
?>
I'm very new to javascript/ajax so i'm sorry if none of what i'm doing makes sense.
So far when I change the dropdown the whole textbox for "number of po's" dissappears. I've ran the query on "getnumberpo.php" on mysql workbench and it works just fine.
Ex: When I select a project from the dropdown. It will query another table called tblCustomerPOs and check how many rows contain the project number that was selected.
Thanks for the help
If anyone comes across this in the future and wanted the answer...
getnumberpo.php (Server-Side Script)
<?php
require "../inc/dbinfo.inc";
$projectnum =$_POST['projectnum'];
$sql = mysqli_query($conn, "SELECT COUNT(*) AS mycount FROM tblCustomerPOs WHERE ProjectNum = '$projectnum'"); //RESPONSE IS QUERY WITH REAL $PROJECTNUM
$res = mysqli_fetch_object($sql)
$count = $res->mycount;
echo json_encode($count);
exit();
?>
new-customer-po.php (Javascript)
//AUTO UPDATE NUMBER OF POS
$(document).ready(function(){
$('#projectnum').change(function(){
var projectnum = $(this).val();
var data_String;
data_String = 'projectnum='+projectnum;
$.post('getnumberpo.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#currentnumpo').val(data)
});
});
});
new-customer-po.php (html)
<label>Project Number <b style="color:red;">*</b></label>
<select id="projectnum" name="projectnum" class="inputvalues" required>
<option disabled selected value>-- Project # - Title</option>
<?php echo $options_1; ?>
</select><br>
<label>Number of Customer POs</label><input type="text" name="currentnumpo" id="currentnumpo" class="inputvalues" readonly/><br>

Use selected Option as variable in PHP Select Dropdown

I'm pulling data from an Azure SQL database using PHP and have successfully created a drop-down (Select) box with Options that are pulled from the database.
The SQL query returns 2 columns, Title & Cycle_ID.
I have set the Title as the text string and the Cycle_ID as the value.
I now want to store the value (Cycle_ID) of the current selection in a variable (MyVariable), which I will use in the SQL query for the next drop-down box I'm creating, i.e. WHERE Cycle_ID = MyVariable.
This way the user progressively narrows their selection as they work their way down through my drop-down boxes.
My current code is below, but I don't know how to create and store the current selection to MyVariable.
<?php
//create the database connection and define the query
$serverName = "myserver";
$connectionOptions = array(
"Database" => "mydatabase",
"Uid" => "mysqlaccount",
"PWD" => "mypassword"
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
//defines cycle query
$cyclesql= "SELECT [Cycle_ID]
,[Title]
FROM [ods].[Cycle]
WHERE End_Date > DATEADD(month,-6,GETDATE()) AND Updated IS NOT NULL
ORDER BY Cycle_ID Asc";
$cycleResults= sqlsrv_query($conn, $cyclesql);
if ($cycleResults == FALSE)
echo (sqlsrv_errors());
?>
<html>
<body>
<form action="cyclefile.php" method="post">
<div id="select">
<p>Select the week:</p><select name='Week'>
<option value="">Select...</option>
<?php
//starts loop
while ($row = sqlsrv_fetch_array($cycleResults, SQLSRV_FETCH_BOTH)) {
//defines cycle variable
$cycle = $row['Title'];
//defines cycle_id variable
$cycle_id = $row['Cycle_ID'];
//displays cycle variable as option in select (dropdown) list and cycle_id as value
echo '<option value="'.$cycle_id.'">'.$cycle.'</option>';
}
?>
</select>
</div>
</form>
</body>
</html>
I suggest you to make an ajax call on selection and pass the selected value to process your result in another file where you can run your query.
<select name="cycle_data" id="cycle_id">
<option value="cycle1" > Cycle 1</option>
<option value="cycle2" >Cycle 2</option>
</select>
Then lets do a script:
<script type="text/javascript">
$(document).ready(function(){
$("#cycle_id").change(function(){
var cycle_data = $(this).val();
var dataString = "cycle_data="+cycle_data;
$.ajax({
type: "POST",
url: "get-data.php",
data: dataString,
success: function(result){
// Process your result here
}
});
});
});
</script>

Integrating href with $_GET value into a select option

I am trying to get some data of a certain item selected in a select option and automatically display it on the textfield as shown in this image:
But it is not working. Is there a remedy for this or such type of coding is not workable at all? Hopefully someone can help me on this.
Here is the code I made:
$credit_accounts = $db->query("SELECT * FROM credits");
echo'<select id="customer_order_id" name = "customer_order_id">
<option value = "">SELECT ACCOUNT</option>';
foreach($credit_accounts as $key){
$id = $key['purchase_order_id'];
$name = $key['customer_firstName']."\t\t".$key['customer_lastName'];
echo'<option value = "'.$id.'">'.$name.'</option>';
}
echo'
</select>';
Note: The link will execute a query that will retrieve certain data of the selected item. If link is declared outside the loop without the <option></option> tag, it works accordingly. But if it is place within the loop of course with the <option></option> tag, it is not working like a link at all. Please help me out.
Sorry for my english , I will write some long answer hopefully it will also help others,so i am giving solution for doing following.
Please not : this solution is written and use SIMPLE MYSQL,AJAX and PHP function If you further want DATA SECURITY refer [PHP MySQLI Prevent SQL Injection
Objective : To get/display DATA from DATABASE related to a particular(ly 1) user/product and then fetch/display it in HTML page (additionally: without page refresh ) IN A FORM.
CODE :
<?php
//php-database connection script
$db_config = mysqli_connect("localhost", "username", "pass", "database_name");
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
?>
<?php
//this pHP SCRIP FIRES when you select a USERNAME (if u want not to SELECT but type then change ONCHANGE to ONKEYUP function & change username input type to text)
if(isset($_POST['uname'])){
$u = $_POST['uname'];
$sql = "SELECT email , gender FROM credits WHERE username='$u' LIMIT 1";
$query= mysqli_query($db_config,$sql);
while($row2 = mysqli_fetch_array($query)){
//Here we form a STRING SEPRATED BY QUAMMAS and ECHO IT TO PAGE
//later on we will fill this data in input fields
echo $row2['email'].",".$row2['gender'];
exit();
}exit();}
?>
<!-- HERE is your form where user will select or type his username-->
<form >
Select username :<br/>
<select id="user_name" onchange="load_data()">
<option value=""> select an ouser</option>
<option value="v1111"> v111</option>
</select><br/>
Email<br/>
<input type ="text" id="email" value=""><br/>
Gender :
<select id="gender">
<option value='m'>male</option>
<option value='f'>female</option>
</select>
</form>
<span id='status' ></span>
<script>
//AJAX OBJECT CREATION script it works as get or post mechanism
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;
}
}
//here is function which fires when username is selected
function load_data(){
var value = document.getElementById('user_name').value;
//declare ajax obj, and name(url) of same page you are coding.
var ajax = ajaxObj("POST", "url.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var str = ajax.responseText;
//split STRING and extract individual data
var res = str.split(',');
//here we fetch his username into input field BINGO!do same for gender.
_('email').value = res[0];
//res[1] will have gender related data.
}
}
//Declaration to send URL encoded variable (username in this case)
ajax.send("uname="+value);
}
</script>
If you want further resources and info about data security see BRAD's comments in comments section

Get value from dropdown list to use in MySQL query

So I'm having this issue with geting a value from a dropdown list in HTML into a variable so that I can do the mysql query. This will be a little tricky to explain but I will do my best. (Do not be shy in correcting my english or my expressions so that the question becomes more concrete and easy to understand).
So I have this dropdown list that gets his values from a mysql query.
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
This "connects" with this query:
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'");
$result4 = mysql_query($sql4, $link);
This query will populate the dropdown list with values. What I'm seeking to do is to populate another dropdown list. For examples I select a list of countrys, and when I select on country it should appear all it's citys in the other dropdown list.
I have been searching guys. Belive me I have.
P.s: Please do not get mad if I change the question a couple of times when I see that you guys show me a way to explain it better. Sorry if my english isn't perfect. Thank you guys for the help.
You can do it with ajax and jquery. I try to write little example
<!-- index.php -->
<select name="desig_act" id="desig_act">
<?php while ($row2 = mysql_fetch_assoc($result4)): ?>
<option value="<?=$row2['new_name_freg']?>">
<?=$row2["new_name_freg"]?>
</option>
<?php endwhile; ?>
</select>
<!-- select tag for countries -->
<select name="country" id="country"></select>
write a little script to return countries as json
<?php //ajax-countries.php
$link = mysql_connect(); // connect as usual
$query = ("SELECT * FROM countries");
$result = mysql_query($query, $link);
$json = array();
while ($row = mysql_fetch_assoc($result)) $json[] = $row;
echo json_encode($json);
?>
Then you can have some sort of script like:
// script.js
$("#desig_act").change(function(){
$.getJSON( "ajax-countries.php", function( data ) {
$.each( data, function(key, val) {
$("#desig_act").append("<option val='" + key + "'>" + val + "</option>");
});
});
I hope it can be useful
1: Create a PHP script to return the data
Essentially just generate the value based off the $_GET input.
2: Create a json request in jquery
Calls the PHP file which will return the data and you will use that data to add more values to the select.
<?php
//Step 1 - The posted ajax data that will return our json request.
if(isset($_GET['fetchrow'])) //Is our ajax request called on page load? If yes, go to this code block
{
//Other stuff like DB connection
$pesq = mysql_escape_string($_GET['fetchrow']); //Put our variable as the variable sent through ajax
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'"); //Run our query
$result4 = mysql_query($sql4, $link); //Please change from mysql_* to mysqli
$data = array(); //The array in which the data is in
while($row = mysql_fetch_assoc($result4)) //Look through all rows
{
array_push($data, $row); //Put the data into the array
}
echo json_encode($data); //Send all the data to our ajax request in json format.
die; //Don't show any more of the page if ajax request.
}
?>
<html>
<head>
<script type='application/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js'></script> <!--Include jquery -->
<script>
//Step #2:
//The jquery script calls ajax request on change of the first select
$( "#desig_act" ).change(function() {
$.getJSON('thisfilename.php', {fetchrow:$("#desig_act").val()}, function(data){ //Get the json data from the script above
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) { //Loop through all results
html += '<option value="' + data[i].new_name_freg + '">' + data[i].new_name_freg + '</option>'; // Add data to string for each row
}
$('#otherselect').html(html); //Add data to the select.
});
});
</script>
</head>
<body>
<!-- Your html code -->
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
</td>
<!-- The new select -->
<select name='otherselect' id='otherselect'>
</select>
<!-- Rest of html code -->
</body>
</html>

Get data from jquery ajax call back to php to use in future SQL queries

I am looking to get the selected field from a dropdown box in order to use it in a future dropdown box, but I can't figure out how to echo the variable through the ajax back to the html.
<p>Trainer</p>
<select name = "trainer_has_update_pokemon">
<option>Select Trainer</option>
<?php
$query = "SELECT name FROM Trainer";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($name);
while ($stmt->fetch()) {
echo"<option>$name</option>";
}
$stmt->close();
}
?>
</select>
Pokemon
<select name = "type_of_update_pokemon">
</select>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
$('select[name="trainer_has_update_pokemon"]').change(function(){ // when trainer_has_update_pokemon changes
$.ajax({
type:"POST", //send a post method
url:'pkmn_dropdown.php', // path to ajax page
data:"trainer_name="+$(this).val(), //set trainer_name to value
success:function(response){ // retrieve response from php
$('select[name="type_of_update_pokemon"]').html(response); // update select
}
});
});
});
</script>
<select name="nickname_of_update_pokemon">
</select>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
$('select[name="type_of_update_pokemon"]').change(function(){ // when trainer_has_update_pokemon changes
$.ajax({
type:"POST", //send a post method
url:'nickname_dropdown.php', // path to ajax page
data:"pkmn_name="+$(this).val() & "trainer_name=" +$trainer_name,//set trainer_name to value
success:function(response){ // retrieve response from php
$('select[name="nickname_of_update_pokemon"]').html(response); // update select
}
});
});
});
</script>
the php for the name dropdown:
<?php
//connect to db
$trainer_name = $_POST['trainer_name'];
$query = "SELECT DISTINCT p.name FROM Pokemon p WHERE p.owner_id = (SELECT t.trainer_id FROM Trainer t WHERE t.name = '$trainer_name')";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($pkmn_name);
while ($stmt->fetch()) {
echo"<option>$pkmn_name</option>";
}
$stmt->close();
echo $trainer_name;
}?>
The php for the nickname dropdown:
<?php
//connect to db
$pkmn_name = $_POST['pkmn_name'];
$query = "SELECT p.nickname FROM Pokemon p, Trainer t WHERE p.name = '$pkmn_name AND p.owner_id = t.trainer_id AND t.name = $trainer_name";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($nickname);
while ($stmt->fetch()) {
echo"<option>$nickname</option>";
}
$stmt->close();
}?>
Any ideas how to get the selected trainer name from the first dropdown box so i can use it in the nickname dropdown box
What exactly is happening when you run the above code? Does the nickname select lose all of it options? Does your ajax response contain the options string as expected?
Modifying the innerHTML of a select does not work in IE. You will need to add actual elements. Try something like this.
$( 'select[name="nickname_of_update_pokemon"]' ).empty().append( $( response ) );
In your ajax success function.

Categories