jQuery code causing conflict in results - php

I would like to ask, is there a better way to run this code. I have a form with a select of #BA_customer which when selected populates a second menu with the address of the selected client. I also need to display a dept dropdown based on the customer selecetion. I think the code I have is causing a conflict where the customer is being passed twice in 2 seperate statements. What is the correct way to do this? Many thanks
<script language="javascript" type="text/javascript">
$(function() {
$("#BA_customer").live('change', function() { if ($(this).val()!="")
$.get("../../getOptions.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_address").html(data); });
});
});
</script>
<script language="javascript" type="text/javascript">
$(function() {
$("#BA_customer").live('change', function() { if ($(this).val()!="")
$.get("../../getDept.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_dept").html(data); });
});
});
</script>
+++++++ dept.php Code +++++++++++++++++++++
$customer = mysql_real_escape_string( $_GET["BA_customer"] ); // not used here, it's the customer choosen
$con = mysql_connect("localhost","root","");
$db = "sample";
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
$query_rs_select_dept = sprintf("SELECT * FROM departments where code = '$customer'");
$rs_select_dept = mysql_query($query_rs_select_dept, $con) or die(mysql_error());
$row_rs_select_dept = mysql_fetch_assoc($rs_select_dept);
$totalRows_rs_select_dept = mysql_num_rows($rs_select_dept);
echo '<label for="dept">Select a Department</label>'.'<select name="customerdept">';
echo '<option value="">Select a Department</option>';
while ($row_rs_select_dept = mysql_fetch_assoc($rs_select_dept))
{
$dept=$row_rs_select_dept['name'];
echo '<option value="dept">'.$dept.'</option>';
}
echo '</select>';
++++ SOLUTION +++++++++++++
mysql_select_db($db, $con);
$query_rs_dept = sprintf("SELECT * FROM departments where code = '$customer'");
$rs_dept = mysql_query($query_rs_dept, $con) or die(mysql_error());
$totalRows_rs_dept = mysql_num_rows($rs_dept);
echo '<label for="dept">Select a Department</label>'.'<select name="customerdept">';
echo '<option value="">Select a Department</option>';
while ($row_rs_dept = mysql_fetch_assoc($rs_dept))
{
$dept=$row_rs_dept['name'];
echo '<option value="dept">'.$dept.'</option>';
}
echo '</select>';
Remove the first $row_rs_select_dept = mysql_fetch_assoc($rs_select_dept); from the script and it works. Just posted solution in case some other soul needs help with problem like this.

Maybe you could send the two requests together?
$(function() {
$("#BA_customer").live('change', function() {
if($(this).val()!="")
$.get("../../getOptions.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_address").html(data);
});
$.get("../../getDept.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_dept").html(data);
});
});
});

Related

how to find the id of the input i am changing in order to post in Ajax

I have created an array of DropDown menus on a while-loop and I would like to post the value on change of the menu. The problem is that since I have created the menus with a loop and the id $_SESSION['List_company_id'] is being overwritten so I cannot get the id of the menu to post.
$i=0;
while($query_data = mysqli_fetch_row($result)) {
$_SESSION["List_company_id"]=$query_data[3];
$_SESSION["List"]=$query_data[1];
$_SESSION["list_name"]=$query_data2[2];
echo '<div class="form-group">';
echo "<p>List number $i</p>";
echo '<span class="icon-case hidden-xs"><i class="fa fa-home"></i></span>';
echo "<select class='dropdown' name=\"".$_SESSION['List_company_id']."\">";
echo "<option selected = 'selected' value=\"".$_SESSION["List_company_id"]."\">".$query_data[2]."</option>";
$query1="SELECT * FROM `calling_lists`";
$result1=mysqli_query($connection,$query1) or die ("Query to get data from list table failed: ".mysql_error());
while ($row1=mysqli_fetch_array($result1)) {
$list_name=$row1["calling_list_name"];
$list_description=$row1["calling_list_description"];
$list_id=$row1["calling_list_id"];
echo "<option value=\"$list_id\">$list_name</option>";
};
echo "</select>";
echo "</div>";
$i=$i+1;
};
echo '</form>';
echo "</div>";
?>
The Ajax I would like to use looks like:
<script type="text/javascript">
$(document).ready(function(){
$("#.$_SESSION['List_company_id'].").change(function(){
var company = $(this).val();
var dataString = "list="+list;
if($_SESSION['List_company_id']){
$.ajax({
type:'POST',
url:"get-data1.php",
data:dataString,
success:function(html){
$('#contact').html(html);
}
});
}
});
});
Finally my get-data1.php looks like:
<?php
/* Connect to MySQL and select the database. */
$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
$database = mysqli_select_db($connection, DB_DATABASE);
$c=$_POST['$_SESSION['List_company_id'];
$query="UPDATE `calling_list_company` SET `calling_list_id`='$c' WHERE `calling_list_company_id`='".$_SESSION["company_id"]."' ;";
$result=mysqli_query($connection,$query) or die ("Query to get data from contact_company table failed: ".mysqli_connect_error());
?>
I have found the answer after a lot of trial and error, "using this.id" in case anybody needs it the working code is here below:
<script type="text/javascript">
$(document).ready(function(){
$(".dropdown").change(function(){
var id=(this.id);
var value=(this.value);
if(value){
$.ajax({
type:'POST',
url:"get_dropdown.php",
data:{"list_company_id":id,"calling_list_id": value},
success:function(html){
$('#risu').html(html);
}
});
}
});
});

get data from database using ajax not working

i have this code:connection to database
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$conn = new mysqli("localhost", "root", "", "jquery");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
now i already have data indatabase in table called city witch it have only id and desc and this is the code
if (isset($_POST['city'])) {
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$results = [];
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($Results);
}
else
{
echo "empty";
}
}
here is the html part:
<select required="required" id="city">
<option disabled selected value=''> select a city </option>
</select>
and here is the function:
function city() {
$.ajax({
"url": "divs.php",
"dataType": "json",
"method": "post",
//ifModified: true,
"data": {
"F": ""
}
})
.done(function(data, status) {
if (status === "success") {
for (var i = 0; i < data.length; i++) {
var c = data[i]["city"];
$('select').append('<option value="'+c+'">'+c+'</option>');
}
}
})
.always(function() {
});
}
so the problem is that there is nothing in select list its always empty, any help? thank u
One small mistake is here:
You are using
echo json_encode($Results);
instead of
echo json_encode($results);
In PHP variable names are case sensitive. So, use proper case for all the variables.
You are not getting the response data in HTML <SELECT> TAG here is what you can do.
image to table
HTML FILE CODE:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="" method="post">
<select>
</select>
</form>
<script>
$(document).ready(function(){
city();
});
function city(){
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data){
var res = JSON.parse(data)
for(var i in res){
var showdata = '<option value="'+res[i].city_name+'">'+res[i].city_name+'</option>';
$("select").append(showdata);
}
}
});
}
</script>
</body>
</html>
HERE IS THE PHP CODE
`
<?php
$conn = new mysqli('localhost','root','','demo');
if($conn->connect_error){
die ("Connection Failed".$conn->link->error);
}
if(isset($_POST['city'])){
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($results);
}
else
{
echo "no city available";
}
}
?>
`
HERE IS THE OUTPUT IMAGE
You have used $results but while echoing you are using $Results which is a different variable so use,
echo json_encode($results);
Also, you are telling that city has only id and desc so in JS code use desc instead of city
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data) {
var res = JSON.parse(data);
$(res).each(function(){
var c = this.city_name; // use city_name here instead of city
$('select').append('<option value="'+c+'">'+c+'</option>');
});
}
});

Auto complete base on value of dropdown in database

I'm stuck with this problem with in a week. What I have here is dropdown select with ajax posting value to another dropdown but now I need to post into textbox with autocomplete function. What I need is connect my autocomplete query and my ajax so that if I select for example ballpen, all ballpen will recommend in autocomplete. Please Help me with this. I need to finish it.
Here's my code
Ajax.php
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
</script>
</head>
<body>
<br/>
Drop1
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
Auto Complete <input id="tag">
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').html(data);
}
});
});
</script>
getajax.php
In here I post the value in another dropdown but not I need to post into textbox.
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
while($row = $result1->fetch_assoc())
{
?>
<option value ="<?php echo $row['item_code'];?>"><?php echo $row['item'];?></option>';
<?php
}
}
?>
autocomplete.php
<?php
//$q=$_GET['q'];
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["q"]);
//$main = $mysqli->real_escape_string($_POST["mainlist_id"]); AND cat_code='$main'
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' GROUP BY id ORDER BY item" );
if($sql)
{
while($row=mysqli_fetch_array($sql))
{
echo $row['item']."\n";
}
}
?>
//whenever u select the tag field will get focus, and it automatically start searching so u no need to type see the callback focus function with $(this).autocomplete("search", ""); and minlength 0. u have to send the main value and get the response from here too
<script>
$(document).on("keyup", "#tag", function(){
$("#tag").autocomplete({
source: function(request, response) {
$.getJSON("autocomplete_gethere.php", { main: $("#main").val() }, response);
},
minLength:0
}).focus(function() {
$(this).autocomplete("search", "");
});
});
</script>
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').focus(); //please note this, here we're focusing in that input field
}
});
});
</script>
untested, if any question post comment

Pass AJAX Variable to PHP and displaying MySQL results after selection from Dynamic Dropdown

I'm having a problem passing a variable selected from a dynamic drop dropdown to a PHP file. I want the PHP to select all rows in a db table that match the variable. Here's the code so far:
select.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#type").attr("disabled","disabled");
$("select#category").change(function(){
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>wait...</option>"); var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("form#select_form").submit(function(){
var cat = $("select#category option:selected").attr('value');
var type = $("select#type option:selected").attr('value');
if(cat>0 && type>0)
{
var result = $("select#type option:selected").html();
$("#result").html('your choice: '+result);
$.ajax({
type: 'POST',
url: 'display.php',
data: {'result': myval},
});
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="0">choose...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<?php include "display.php"; ?>
<div id="result2"></div>
</body>
</html>
select.class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT * FROM profession";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['id_cat'] . '">' . $row['prof_name'] . '</option>';
}
return $category;
}
public function ShowType()
{
$sql = "SELECT * FROM specialties WHERE id_cat=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['id_type'] . '">' . $row['sp_name'] . '</option>';
}
return $type;
}
}
$opt = new SelectList();
?>
And here's the display.php that I want the variable passed to. This file will select the criteria from the db and then print the results in select.php.
<?php
class DisplayResults
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowResults()
{
$myval = $_POST['result'];
$sql = "SELECT * FROM specialities WHERE 'myval'=sp_name";
$res = mysql_query($sql,$this->conn);
echo "<table border='1'>";
echo "<tr><th>id</th><th>Code</th></tr>";
while($row = mysql_fetch_array($res))
{
while($row = mysql_fetch_array($result)){
echo "<tr><td>";
echo $row['sp_name'];
echo "</td><td>";
echo $row['sp_code'];
echo "</td></tr>";
}
echo "</table>";
//}
}
return $category;
}
}
$res = new DisplayResults();
?>
I'd really appreciate any help. Please let me know if I can provide more details.
Link to db diagram: http://imgur.com/YZ0SuVw
The first dropdown draws from the profession table, the second from the specialties table. What I'd like to do is to display all of the rows in the jobs table that match the specialty selected in the dropdown box. This will require the result from the variable (result) from the dropdown to be converted into the spec_code that is in the job table. Not sure exactly how to do this. Thanks!
I just want to outline some points about following block of code:
where did you defined myval
data: {'result': myval}: result not require any quota change it to data: {result: myval}
why you need to get HTML from selected options? it's better to send option values the change
$("select#type option:selected").html();
to
$("select#type option:selected").val();
if(cat>0 && type>0)
{
var result = $("select#type option:selected").html();
$("#result").html('your choice: '+result);
$.ajax({
type: 'POST',
url: 'display.php',
data: {'result': myval},
});
}

jQuery and MySQL

I have taken a jQuery script which would remove divs on a click, but I want to implement deleting records of a MySQL database. In the delete.php:
<?php
$photo_id = $_POST['id'];
$sql = "DELETE FROM photos
WHERE id = '" . $photo_id . "'";
$result = mysql_query($sql) or die(mysql_error());
?>
The jQuery script:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The div goes away when I click on it, but then after I refresh the page, it appears again...
How do I get it to delete it from the database?
EDIT: Woopsie... forgot to add the db.php to it, so it works now >.<
There's no way the php could even come close to working. Where is the database? Check out http://www.php.net/manual/en/mysql.examples-basic.php from which you can see there's more to the database than just a query.
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
You have your data as a GET string, but you are using a POST request, try changing your string variable to an object. Like :
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = { id : id };
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
Plus I am hoping you are preparing your MySQL connection properly in your PHP, you cannot just call mysql_query and hope it will know which database you mean, and how to connect to it by itself :)
Look at #Quotidian answer! :)

Categories