Populating options list with SQL - php

So I'm currently in the process of trying to populate a select option list with some SQL using ajax and php. I've tried various different pieces of code however I still can't seem to crack it. Here is the ajax from the actual page its self...
$.ajax ({
url:'orderentry_ajax.php',
cache:false,
data: {'request': 'getCounty', 'County': County},
dataType: 'json',
async: false,
success: function(data)
{
$('#errMsg').html(data.errMsg);
if(data.numRecs>0)
{
//divStr = divStr + data.custName + data.contactName + data.contactNumber + data.contactEmail;
countyStr = countyStr + "<select>";
for (var i=0; i<data.dataArray.length; i++)
{
countyStr = countyStr +
"<option value='data.dataArray[i].County'>" +
"Please Select" + data.dataArray[i].County + "</option>";
}
countyStr = countyStr + "</select>";
$('#Countys').html(countyStr);
}
}
//countyStr = countyStr + data.dataArray[i].County +
});
As far as I'm concerned I did a similar exercise except I was populating the options list with another table, I've made the two pieces of ajax and php identical and it still doesnt seem to want to work. Here is the php from the ajax page....
if (trim($request) =='getCounty')
{
//product update
$County = $_REQUEST['County'];
$errMsg = "";
$con = mysqli_connect('127.0.0.1', 'root', 'c0mplex', 'HRDatabase');
//Check if connect..
if (mysqli_connect_errno($con))
{
$errMsg = 'Could not connect to Database.' . mysqli_connect_error();
}
else
{
// passed record for submit
$qryStr = "SELECT * FROM county WHERE `county` = $County";
//echo $qryStr;
$result = mysqli_query($con, $qryStr);
if (mysqli_error($con))
{
//echo (mysqli_error($con));
$errFlg=1;
$errMsg="Error during update, please try again. " . mysqli_error($con);
}
else
{
while ($row = mysqli_fetch_array($result))
{
$County = $row['county'];
$rowing = array();
$rowing['county'] = $County;
$dataArray[] = $rowing;
}
$numRecs = mysqli_num_rows($result);
}
}
mysqli_close($con);
//to test error :
// $errMsg="testing error";
$info ->dataArray = $dataArray;
$info ->numRecs = $numRecs;
$info ->errMsg = $errMsg;
$info ->County = $County;
echo json_encode($info);
//echo $msg;
}
The select option list has an ID on it of 'Countys' just to give a heads up. Any help would be greatly appreciated guys.
Cheers

Replace below line in your ajax code for adding html dymically
countyStr = countyStr + "<option value='" + data.dataArray[i].County + "'>" + "Please Select" + data.dataArray[i].County + "</option>";

Related

Item isn't deleted from database through ajax call

I'm running around the issue which I don't really know how to solve - I simply want to remove uploaded file from the database, but I'm failing to do so.
My personal guess now is that my delete_shop_item.php doesn't work or that upload.php loop messes up the deletion process from the database (but that's only my guess).
Ajax:
$(document).on('click', '#rmvBtn', function() { /*press the button to remove selected item*/
del_title = $("#"+ $("#selectOpt").val()); /* select dynamically generated option to remove*/
$.ajax({
type: 'POST',
url: 'delete_shop_item.php',
cache: false,
processData: false,
data: {title:del_title.val()},
success: function() {
$("#" + $("#selectOpt").val()).remove();
$("#selectOpt option:selected").remove();
}
});
delete_shop_item.php
$title = $_POST['title'];
$pdo = new PDO('mysql:host=localhost;dbname=project', 'root', '');
$query = 'DELETE FROM photos WHERE title = :title';
$stmt = $pdo->prepare($query);
$stmt->bindPARAM(':title', $title);
$stmt->execute();
upload.php
<?php $count = 1;
while($data = mysqli_fetch_array($result)) {
if($count === 1) {
echo "<div class='img_container'>";
}
echo "<div class='img_div' id='".$data['title']."'>";
echo "<img src='uploads/" . $data['filename']."'>";
echo "<p class='img_title' >" .$data['title']. "</p>";
echo "<p class='img_desc'>" .$data['photo_description']. "</p>";
echo "<p>" .$data['price']. "</p>";
echo "</div>";
if($count % 5 === 0) {
echo "</div>";
$count = 1;
continue;
}
$count++;
}
?>
try data: {title:del_title} in ajax request

Image change from dropdown using AJAX

Here I have one drop down menu on which selection other dropdown changes result the id of other dropdown is "style_code". Now I also want to change image on dropdown selection, it is like when I select color from dropdown it changes sizes which is other dropdown, but I also want to change image on color selection.
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data:'id='+val,
success: function(data){
$("#style_code").html(data);
}
});
}
</script>
Here is check.php
<?php
$con=mysqli_connect("localhost","root","","db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con,$query);
while ( ($row=mysqli_fetch_array($results))){?>
<option value="<?php echo $row["color_name"]; ?>">
<?php echo $row['size'] ; ?>
</option>
<?php
}
}
?>
Your difficulty comes from the fact that you are returning HTML code from the PHP script. My advice is to return JSON data then generate style_code children with jQuery.
It would be something like that :
check.php
<?php
$con = mysqli_connect("localhost", "root", "", "db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query = "SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
$data = new stdClass(); // This object will carry the results
while (($row = mysqli_fetch_object($results))) {
$data->option[] = $row;
}
// Another query to get the image name
$query = "SELECT name FROM image_name WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
if ($row = mysqli_fetch_object($results)) {
$data->image_name = $row->name;
}
header('Content-Type: application/json');
echo json_encode($data);
}
HTML & Javascript:
...
<div class="thumb-image" id="style_image" >
<img src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" />
</div>
...
<script language="javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data: {id: val},
dataType:'json',
success: function(data) {
$("#style_code").children().remove(); // empty the dropdown
// Add new options in the dropdown from the result data
data.option.forEach(function (item) {
$("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
});
// Change the 'src' attribute of the <img>
$("#style_image").find('img').attr('src', 'images/' + data.image_name + '?d=' + Date.now().toString());
}
});
}
</script>

how to show another dropdown box depend on dropdown box value

please i need help
i need to do specail command
when some value selected then show another dropdown box
my first dropdown box is in php
and he is my code :
$conn = mysqli_connect("localhost", "root",
"", "phoneunlock" )
or die("Cannot connect to database:" .
mysqli_connect_error($conn));
echo "<select name='selectedValue' class= 'dropdown' >";
echo '<option value="">'.'Please Select Service'.'</option>';
$sql = "SELECT id, manufacter FROM product";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{ echo "<option value='" . $row['manufacter']. "'>" . $row['manufacter'] . '</option>';
}
echo '</select>';
and know i need some command like this :
if dropdown box selected = value then
do this
end if
sow please can any one help me
if you mean like chained combobox. try using jQuery like this :
$('#yourcomboid').on('change', function() {
var id = $(this).val();
$('#youranothercombo').empty();
$.ajax({
url: 'your-route-to-get-data/' + id,
success: function(data) {
$('#youranothercombo').empty();
for(var i = 0; i < data.length; i++) {
var item = data[i];
$('#youranothercombo').append($('<option></option>').val(item.column-name).text(item.column-name));
}
}
});
});
Hope this code works.

Dynamic drop down menus

I want to create a dynamic drop down where the options of the second drop down changes after the selection of the first drop down.
The test.php file
<?php
$con=mysqli_connect("localhost","******","****","******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM countries");
?>
<select id="country" name='country' onchange="get_states();">
<option value=''>Select</option>
<?php
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['country_id'] . "'>" . $row['country_name'] . "</option>";
}
?>
</select>
<div id="get_state"></div> // Sub will be appended here using ajax
<script type="text/javascript">
function get_states() { // Call to ajax function
var country = $('#country').val();
var dataString = "country="+country;
$.ajax({
type: "POST",
url: "getstates.php", // Name of the php files
data: dataString,
success: function(html)
{
$("#get_state").html(html);
}
});
}
</script>
<?php
mysqli_close($con);
?>
and the gestates.php is:
<?php if ($_POST) {
$country = $_POST['country'];
if ($country != '') {
$sql1 = "SELECT * FROM states WHERE country_id=" . $country;
$result1 = mysql_query($sql1);
echo "<select name='state'>";
echo "<option value=''>Select</option>";
while ($row = mysql_fetch_array($result1)) {
echo "<option value='" . $row['id'] . "'>" . $row['state_name'] . "</option>";}
echo "</select>";
}
else
{
echo '';
}
}
?>
However the above code does not work!
on change on first drop-down you need to make an ajax call which will get the options and you can then populate the next drop-down
Try adding single quotes around $country
$sql1 = "SELECT * FROM states WHERE country_id='" . $country . "'";
or
$sql1 = "SELECT * FROM states WHERE country_id='$country'";
EDIT: Also, you can only echo one result. Your second echo will be ignored by Jquery as the first will be considered a success.
You should format your results differently.
Perhaps a json encoded array.
In your php:
while($row = mysql_fetch_array($result1))
{
$data[$row['id']] = $row['state_name'];
}
echo json_encode($data);
In your Jquery set dataType: 'json'
$.each(html,function(key,value){
$("#get_state").append($('<option>',{
value:key,
text: value
}));
});

ajax success function not returning json decoded data

I have searched stackoverflow for similar questions but nothing helped. This is my ajax call to adding.php file. I called this on jquery keyup event. When I inspect in browser I see php file returning response. However, the data in response never reaches success function of ajax.
$.ajax({
url: "anding.php",
type: "POST",
dataType: 'json',
data: JSON.stringify({mycol:mycol,mycolval:mycolval,string:string}),
contentType: 'application/json',
success: function(data){
alert(data);
var output = data.substring(0, data.indexOf('arventures'));
last = data.substring(data.indexOf('arventures') + 10);
last--;
$('.remove').remove();
$('.main_tr').after(output);
if (output == '' || output == null) {
$('.message').html('No results found.');
}
else {
$('#row1').addClass('highlight');
}//highlight row1 by default
}
});
This is my php file which returns the response. I have pasted the entire code because I dont know which part is causing the issue.
adding.php
<?php
include 'connection.php';
$postdata = json_decode(file_get_contents("php://input"), true);
//var_dump($postdata);exit;
//var_dump($postdata);
$query = "SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = '".$table_name."'
AND table_schema = '".$mysql_database."'";
$result = mysqli_query($con,$query);
$results = array();
while ($line = mysqli_fetch_assoc($result)) {
$results[] = $line;
}
$query = null;
foreach ($results as $r) {//search in order.1st search in column 1 then column 2...so on
$append = " SELECT * from " . $table_name . " WHERE " . $r['COLUMN_NAME'] . " like '" . $postdata['string'] . "%'";
$query = $query . $append;
for($i=1;$i<=(count($postdata['mycol']))-1;$i++)
{
$append1=" AND " .$postdata['mycol'][$i]. " like '" . $postdata['mycolval'][$i] . "%'";
$query = $query . $append1;
}
$query=$query." UNION";
}
$query = substr($query, 0, -6);
$result2 = mysqli_query($con, $query);
$pos = strrpos($postdata['string'], '%');
$str_count = substr_count($postdata['string'], '%');
$results2 = array();
$results3 =array();
while ($line = mysqli_fetch_assoc($result2)) {
if (strpos($postdata['string'], '%') !== false || strpos($postdata['string'], '_') !== false) {// highlight in star search
$str = preg_replace('/[^a-zA-Z0-9-]/', '', $postdata['string']);
$line = preg_replace("|^($str)|Ui", "<span class='highlights'>$1</span>", $line);
} else {
$string=$postdata['string'];
$line = preg_replace("|^($string)|Ui", "<span class='highlights'>$1</span>", $line); //highlight in normal search
}
$results2[] = $line;
}
$result2 -> data_seek(0);
while ($line1 = mysqli_fetch_assoc($result2)) {
$results3[] = $line1;
}
for ($i=1;$i<=count($results2);$i++) {
echo "<tr id='row".$i."' class='remove table_row'>";
$j=0;
foreach($results as $r1){
if($j==0){
echo "<td class='index_field' dB_id='".$results3[$i-1][$r1['COLUMN_NAME']]."'>".$results2[$i-1][$r1['COLUMN_NAME']]."</td>";
} else {
echo "<td>".$results2[$i-1][$r1['COLUMN_NAME']]."</td>";
}
$j++;
}
echo "</tr>";
}
echo 'arventures' . $i;
mysqli_close($con);
Your ajax call never reaches the success function because you have specified dataType as JSON. Either remove dataType or return JSON instead of normal HTML.

Categories