I have a dynamically generated select where customer can choose supplier ($sid) for product ($pid):
<select name="<?php echo $pid; ?>" onchange="func(this.value)">
<?php foreach...{ ?>
<option name="<?php echo $pid; ?>" value="<?php echo $sid; ?>">
<?php echo $value; ?>
</option>
<?php } ?>
</select>
And ajax call which has to assign the chosen value to the product:
<script>
function func(selectedValue){
var pid = $('name').val();
$.ajax({
url: 'update.php',
type: 'POST',
data: {sid : selectedValue, pid : pid},
success: function() {
alert("Ok");
location.reload();
}
});
}
</script>
And update.php
<?php
$pid = $_REQUEST['pid'];
$val = $_REQUEST['sid'];
$sid = json_encode($val);
$query = "UPDATE `orders` SET sid = '$sid' WHERE pid = '$pid'";
try {
$DBH = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
$STH=$DBH->prepare($query);
$STH->execute();
}
catch(PDOException $e) {
echo $e->getMessage();
}
$DBH=null;
?>
But the information does not update. Where is my mistake?
var pid = $('name').val(); with var pid = selectedValue;
Try this
<?php
$pid = $_REQUEST['pid'];
//$val = $_REQUEST['sid']; // you may write wrong here
//$sid = json_encode($val);
$sid= $_REQUEST['sid'];
$query = "UPDATE `orders` SET sid = '$sid' WHERE pid = '$pid'";
try {
$DBH = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
$STH=$DBH->prepare($query);
$STH->execute();
}
catch(PDOException $e) {
echo $e->getMessage();
}
$DBH=null;
?>
javascript
<script>
function func(selectedValue){
var pid = $('#product option:selected').attr('name');
$.ajax({
url: 'update.php',
type: 'POST',
data: {sid : selectedValue, pid : pid},
success: function() {
alert("Ok");
location.reload();
}
});
}
</script>
Html:
<select id="product" name="<?php echo $pid; ?>" onchange="func(this.value)">
<?php foreach...{ ?>
<option name="<?php echo $pid; ?>" value="<?php echo $sid; ?>">
<?php echo $value; ?>
</option>
<?php } ?>
</select>
You can replace :
var pid = $('name').val();
with this:
var pid = $(this).attr('name');
The above code will fetch the value of 'name'
The below code will fetch sid
$(this).val();
The problem is you don't get the correct pid because of this wrong jquery selector
$('name').val()
You need to add id attribute to <select> tag, let's say it's product
<select id="product" name="<?php echo $pid; ?>" onchange="func(this.value)">
<?php foreach...{ ?>
<option name="<?php echo $pid; ?>" value="<?php echo $sid; ?>">
<?php echo $value; ?>
</option>
<?php } ?>
</select>
Since $pid is always the same, you can get it by using this selector
$('#product').attr('name')
and set pid to the above as follows
<script>
function func(selectedValue){
var pid = $('#product').attr('name');
$.ajax({
url: 'update.php',
type: 'POST',
data: {sid : selectedValue, pid : pid},
success: function() {
alert("Ok");
location.reload();
}
});
}
</script>
You're missing the important part putting a name to the select not the value.
Instead use id to call your function in your script.
<select name="supplier" id="getValue">
<?php foreach...{ ?>
<option value="<?php echo $sid; ?>">
<?php echo $value; ?>
</option>
<?php } ?>
</select>
On your javascript put this code:
note that the line var formVals = $('form').serialize(); will get all the inputs that your form will pass.
$('#getValue').on('change', function() {
var formVals = $('form').serialize();
$.ajax({
url: "update.php",
type: 'POST',
async : false,
data: formVals,
success: function(data) {
alert("Ok");
location.reload();
}
});
});
and lastly change $_REQUEST to $_POST['supplier'];
Change your HTML like this: (change to onchange="func(this)")
<select name="<?php echo $pid; ?>" onchange="func(this)">
<?php foreach...{ ?>
<option name="<?php echo $pid; ?>" value="<?php echo $sid; ?>">
<?php echo $value; ?>
</option>
<?php } ?>
</select>
And in the code you call ajax:
<script>
function func(element){
var selectedValue = $(element).val();
var pid = $(element).attr('name');
$.ajax({
url: 'update.php',
type: 'POST',
data: {sid : selectedValue, pid : pid},
success: function() {
alert("Ok");
location.reload();
}
});
}
</script>
And in the update.php file:
<?php
$pid = $_POST['pid'];
$val = $_POST['sid'];
$sid = json_encode($val);//I don't know why you have this line, this line should be removed
$query = "UPDATE `orders` SET sid = '$sid' WHERE pid = '$pid'";
try {
$DBH = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
$STH=$DBH->prepare($query);
$STH->execute();
}
catch(PDOException $e) {
echo $e->getMessage();
}
$DBH=null;
?>
Related
I'm trying to get data from the database using ajax to insert it in other element but the post data not passing to get-data.php
so what the reason can be and the solution
addBuilding.php
<?php
require_once("./dbConfig.php");
$selectIL = "SELECT * FROM iller ";
$selectIL = $db->prepare($selectIL);
$selectIL->execute();
$res = $selectIL->get_result();
?>
<form action="" method="post">
<select name="pp" id="cites">
<option value="">-select state-</option>
<?php
while ($row = $res->fetch_assoc()) {
?>
<option value="<?= $row['id'] ?>"><?= $row['il_adi'] ?></option>
<?php
}
?>
</select>
<select name="district" id="district">
<option value="">-select district-</option>
</select>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="getdata.js"></script>
getdata.js
$(document).ready(function() {
$("#cites").change(function() {
if ( $("#cites").val()!="") {
$("#district").prop("disabled",false);
}else {
$("#district").prop("disabled",true);
}
var city = $("#cites").val();
$.ajax({
type: "POST",
url:"get-data.php",
data:$(city).serialize(),
success: function(result) {
$("#district").append(result);
}
});
});
});
get-data.php
I can see the form data in network inspection put no data passing to get-data.php
<?php
require_once("./dbConfig.php");
if (isset($_POST['pp'])) {
$cites = $_POST['cites'];
$selectIlce = "SELECT * FROM ilceler where il_id=? ";
$selectIlce = $db->prepare($selectIlce);
$selectIlce->bind_param("i", $cites);
$selectIlce->execute();
$res = $selectIlce->get_result();
?>
<?php
while ($row = $res->fetch_assoc()) {
?>
<option value="<?= $row['id'] ?>"><?= $row['ilce_adi'] ?></option>
<?php
}
}
?>
You need to echo the results in get-data.php
<?php
while ($row = $res->fetch_assoc()) {
?>
echo "<option value='". $row["id"]."'>".$row['ilce_adi']."</option>";
<?php
}
}
?>
1- Get data by serialize from form:
$("form").serialize()
2- Add dataType: "json" to ajax option:
$.ajax({
type: "POST",
url:"get-data.php",
data:$(city).serialize(),
dataType: "json",
success: function(result) {
$("#district").append(result);
}
});
So i want to make my select dropdown box flexible, however i tried using AJAX which i found online, but the AJAX request is a standalone data, it does not return back the data.
Is there any convenient way to get the data and able to submit to another PHP file ?
Here is my Code
index.php
<td>
<select id="ownerID" name="OwnerID" class="id" required>
<?php
$Employee_ID='';
$sql1="SELECT Employee_ID FROM user1 WHERE Position1='QE' OR Position1='OTHER'";
$result1=odbc_exec($conn,$sql1);?>
<option value="">Choose</option>
<?php while($row1=odbc_fetch_array($result1)){
$Employee_ID=$row1['Employee_ID'];
?>
<option value ="<?php echo $Employee_ID;?>"><?php echo $Employee_ID;?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td id="response" style="margin-left:50px;">
</td>
AJAX
<script type="text/javascript">
$(document).ready(function(){
$("select.id").change(function(){
$("#response option").remove();
var selectedOwner = $(".id option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { id : selectedOwner}
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
post-requst.php
if(isset($_POST["id"])){
$id = $_POST["id"];
$Form_Tracking_ID=null;
$sql="SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 IS NULL AND CEF_ID IS NULL
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 IS NULL AND CEF_ID = ' '
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 = ' ' AND CEF_ID IS NULL
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 = ' ' AND CEF_ID = ' '";
$result=odbc_exec($conn,$sql);
if($id !== 'Choose'){
echo "<label>Tool ID:</label>";
echo "<br><select id='toolid' name='ownerid' required>"; ?>
<option value="">Choose</option>
<?php while($row=odbc_fetch_array($result)){
$search=$row['Form_Tracking_ID']; ?>
<option value="<?php echo $search ?>"><?php echo $search ?></option>
<?php }
echo "</select>";
}
}
You can use a function for get data from database, getting value of 1º select and put them on 2º select
//Get value from 1 select
$("#firstSelect").change(function () {
let firstSelectValue = $("#firstSelect").val();
$("#secondSelect").text("");
//Calling a function to get value from database
getDataForSecondSelect(firstSelectId);
})
function getDataForSecondSelect(firstSelectValue) {
$.ajax({
url: `getDataForSecondSelect.php?value=${firstSelectValue}`,
method: "GET",
dataType: "JSON",
success: function (message) {
if (message.length != 0) {
$('#secondSelect').prop('disabled', false);
for (let i = 0; i <= message.length; i++) {
$("#secondSelect").prepend(`<option value=${message[i]["id"]}>${message[i]["name"]}</option>`);
}
} else {
$("#subcategoriaProduto").text("");
$("#subcategoriaProduto").prepend("<option>There's no data</option>");
$('#subcategoriaProduto').prop('disabled', true);
}
}
});
}
I'm trying to implement live-table edit, but I'm having some trouble with my select options. The input type="text" is fully functional though.
Ever since I tried to add select, it seemed to brake my entire lay-out. First there were multiple rows and columns displayed on the page. But now there's only one and the columns show up empty after the one that contains select.
And the second problem is that ajax doesn't post the table edit since I added select to the mark-up. I'm thinking that this is because the mark-up breaks, but I'm not sure.
If anybody knows what to do, I'd appreciate it.
Markup
<?php
$query = ("select * from projectlist");
$resultaat = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($resultaat, MYSQL_ASSOC)){
$id = $row['projectid'];
?>
<tr class="predit">
<form action="" method="post">
//Working input
<td>
<span id="klant_<?php echo $id; ?>" class="text"><?php echo $row["Klant"]; ?></span>
<input type="text" class="ip" id="klant_ip_<?php echo $id; ?>" value="<?php echo $row["Klant"]; ?>">
</td>
//Same approach, but with select instead of input
<td>
<span id="project_<?php echo $id; ?>" class="text"><?php echo $row["Project"]; ?></span>
<select id="project_ip_<?php echo $id; ?>" class="ip">
<?php
//Fetch select options from another table
$query = ("select * from projecten");
$resultaat = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($resultaat, MYSQL_ASSOC)){
$listid = $row["projectcode"];
$projectnaam = $row["projectnaam"];
?>
<option value="<?php echo $projectnaam; ?>" id="<?php echo $listid; ?>"><?php echo $projectnaam; ?></option>
<?php
}
?>
</select>
</td>
</tr>
</form>
<?php
}
?>
JQuery Ajax
$(document).ready(function(){
//Projeclist
$(".predit").click(function(){
var ID=$(this).attr('id');
$("#klant_"+ID).hide();
$("#project_"+ID).hide();
$("#klant_ip_"+ID).show();
$("#project_ip_"+ID).show();
}).change(function(){
var ID=$(this).attr('id');
var klant=$("#klant_ip_"+ID).val();
var project=$("#project_ip_"+ID).val();
var dataString = 'id='+ ID
+'&Klant='+klant
+'&Project='+project;
//alert(dataString);
var project_txt = $("#project_ip_"+ID+" option:selected").text();
$.ajax({
type: "POST",
url: "post_table.php",
data: dataString,
cache: false,
success: function(html){
$("#project_"+ID).html(project_txt);
$("#klant_"+ID).html(klant);
},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
},
});
});
$(".ip").mouseup(function() {
return false
});
$(document).mouseup(function(){
$(".ip").hide();
$(".text").show();
});
});
post_table.php
<?php
include('config.php');
$klant = $_POST['Klant'];
$project = $_POST['Project'];
$id = $_POST['id'];
$query = "update projectlist
set Klant='$klant',
Project='$project'
where projectid='$id'";
mysql_query($query, $con);
?>
My table is not displayed when i select any project name. I guess the onchange function is not working properly but i couldn't figure out the problem.
Code is as follows:
<div class="span6">
<?php $sql = "SELECT * from login_projects WHERE login_id='".$record['login_id']."'";
$res_sql = mysql_query($sql); ?>
<label>Project Name <span class="f_req">*</span></label>
<!--<input type="text" name="city" class="span8" />-->
<select name="project_name" onchange="get_list_onnet()" id="project_name" class="span8">
<option value="">--</option>
<?php while($rec_sql = mysql_fetch_array($res_sql)){ ?>
<option value="<?php echo $rec_sql['project_id']; ?>">
<?php echo $rec_sql['project_name']; ?></option>
<?php } ?>
</select>
</div>
Function:
<script>
function get_list_onnet(){
var project_name=$("#project_name").val();
$.ajax
({
type: "POST",
url: "ajax.php",
data: {action: 'get_list_onnet',list_onnet:project_name},
success: function()
{
document.getElementById("dt_a").style="block";
$("#dt_a").html(html);
}
});
};
</script>
<script>
$(document).ready(function() {
//* show all elements & remove preloader
setTimeout('$("html").removeClass("js")',1000);
});
</script>
Ajax.Php Page:
function get_list_onnet(){
$list_onnet=$_POST['list_onnet'];
$sql_list_onnet=mysql_query("SELECT * from projects,project_wise_on_net_codes
where projects.project_id = project_wise_on_net_codes.project_id AND
project_wise_on_net_codes.project_id='$list_onnet'");
$row1 = mysql_num_rows($sql_list_onnet);
if($row1>0)
{
echo "<tr><th>id</th><th>Project Name</th><th>Country Code</th><th>On-net prefix</th>
<th>Action</th></tr>";
$k = 1; while($row_list_onnet=mysql_fetch_array($sql_list_onnet))
{
$project3 = $row_list_onnet['project_name'];
$countrycode1 = $row_list_onnet['country_code'];
$prefix1 = $row_list_onnet['on_net_prefix'];
$id_proj = $row_list_onnet['project_id'];
$on_prefix = $row_list_onnet['on_net_prefix'];
echo "<tr><td>".$k."</td><td>".$project3."</td><td>".$countrycode1."</td>
<td>".$prefix1."</td><td><a href='process/update_process_onnet.php?ID=".$id_proj."&Onnet=".$on_prefix."'>Delete</a></td>
</tr>";
$k++;
}
}
else
{
echo "<script>alert('No Record Found')</script>";
}
}
The problem is that it is always going in the else condition and nothing is displayed in the table.
I have an HTML text input field - for example:
<input id="CustID" name="CustID" dir="rtl" value="<? echo $CustID;?>" size="35" required="true" maxlength="9" >
When I insert the number of the user, I need to open a select box to show all ticket for this user.
for example
<select name="ticket" id="ticket" >
<?
$query="SELECT * FROM ticket where CustID='$CustID' ";
$result=mysql_query($query) or die("error: " . mysql_error());
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['ticket'] ; ?>"><?php echo $row['ticket'] ; ?></option>
<? } ?>
</select>
How can i use this with AJAX?
This is what I have so far:
<script src="js/jquery.js"></script>
<script language="javascript">
function getData(id) {
$.ajax ({
url: "php_page.php",
type: "POST",
data: {custid:id},
success: function(data){
$("#return").html(data)
}
)} // i have error her why ??
}
</script>
<input type="text" value="<?php echo $CustID;?>" onkeyup="getData(this.value)"/>
<?
include("functions/connect.php");
$query = "select * from customers2 , tickets where customers2.CustID='".$CustID."' and tickets.CustNo=customers2.CustomersNo";
$result=mysql_query($query) or die("error: " . mysqli_error());
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['ticket'] ; ?>"><?php echo $row['ticket'] ; ?></option>
<? } ?>
</select>
Put your php on a separate page called php_page.php. Create your ajax call using the jquery library on your display page:
function getData(id) {
$.ajax ({
url: "php_page.php",
type: "POST",
data: {custid:id},
success: function(data){
$("#return").html(data)
}
)}
}
On your form page create a div with id "return" where you want your select options to show up and also call this function either with a button click or onkeyup:
<input type="text" value="<?php echo $CustID;?>" onkeyup="getData(this.value)"/>
Oh, and your mysql connect should use the mysqli library:
$con=mysqli_connect($host,$username,$password,$database);
$query = //same as before
$result=mysqli_query($query) or die("error: " . mysqli_error());
while($row=mysqli_fetch_array($result))
{
?>
<option value="<?php echo $row['ticket'] ; ?>"><?php echo $row['ticket'] ; ?></option>
<? } ?>
</select>
use AJAX to pass CustID to Select page.
i.e
index.php
<script>
function callAjax(str)
{
ajax
}
</script>
<input type = "text" name = "CustID" onblur="callAjax()"/>
<div id = "show">where to display the ajax results</div>
ajax.php
all that code with the select and options.
i will do but the result is get me all record on select and i wont only record of the user i enter ID
index.php
<script src="js/jquery.js"></script>
<script language="javascript">
function getData(id) {
$.ajax ({
url: "php_page.php",
type: "GET",
data: {custid:id},
success: function(data){
$("#return").html(data)
}
})
}
</script>
<input type="text" id="CustID" name="CustID" onkeyup="getData(this.value)"/>
<div id="return"></div>
php_page.php
<select>
<option value="">عرض الكل</option>
<?
include("functions/connect.php");
if(isset($_GET['CustID']))
{
$CustID = $_GET['CustID'];
$sql_check = mysql_query("select * from customers2 , omra , haj , tickets where customers2.CustID='".$CustID."' and tickets.CustNo=customers2.CustomersNo") or die(mysql_error());
if(mysql_num_rows($sql_check)){
while($rows = mysql_fetch_array($sql_check)){
?>
<option value="<?php echo $rows['TicketType'] ; ?>">تذكرة <?php echo $rows['TicketType'] ; ?> برقم <?php echo $rows['TicketRealNo'] ; ?></option>
<? } } ?>
</select>
<? } ?>