here in my code i am trying to fetch and display the data after selecting a option from the dropdown using onChange, fetching data from a PHP file and via ajax displaying it in textarea in same select.php file but unfortunately it is not working out for me am quit confused were i made a mistake, please help me out on this.
select.php
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#channel").change(function(){
$.post("ajax.php", { channel: $(this).val() })
.success(function(data) {
$(".result").html(data);
});
});
});
</script>
</head>
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" id = 'channel' name="ProductCategoryID" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="1234">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group result"></div>
ajax.php
<?php
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode = '$channel' ";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
while($row = mysql_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
Try using:
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
May be it would help
replace,
$.post("ajax.php", { channel: $(this).val() })
with
$.post("ajax.php", { 'channel': $(this).val() })
$.post("ajax.php", { channel: $(this).val() },function(data) {
$(".result").html(data);
});
Please remove .success(function(data){ }) from the code and it will work :)
Try to initiate $msg first and use mysqli module.
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode =$channel";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
UPDATE
Update your post request with:
$.post("ajax.php",
{ channel: $(this).val() },
function(data) {
$(".result").html(data);
}
);
OR
$.post("ajax.php",
{ channel: $(this).val() },
successCallback
);
function successCallback(data){
//process data..
}
see https://api.jquery.com/jquery.post
Related
I'm trying to receive post data with php from ajax in same page but seems like i have some issues that i have no idea to solve them
here is my html/php code :
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php
while ($row = $result->fetch_assoc())
{
echo "<option value=".$row['N_omran'].">".$row['N_omran']."</option>";
}
?>
</select><br>
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row) {
echo " <h4>Nom : {$row['nom']}</h4>
<h4>Prénom : {$row['prenom']}</h4>
<h4>Téléphone : {$row['tel']} </h4>
<h4>Maticule d'assurance : {$row['matricule_assu']}</h4>
<h4>Adresse : {$row['adress']}</h4>";
}
} ?>
And here is my Ajax post request :
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function () {
alert("Post request successfully done")
}
});
}
});
the code below can replace all your data with the new ones with clean writing :)
// get data from Database
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
} ?>
// show rows to be selected
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?= $row['N_omran'] ?>"> <?= $row['N_omran'] ?></option>
<?php } ?>
</select><br>
// show recieved data
<?php if ($row) { ?>
<div id="informations">
<h4>Nom : <span id="nom"><?= $row['nom'] ?></span></h4>
<h4>Prénom : <span id="prenom"><?= $row['prenom'] ?></span></h4>
<h4>Téléphone : <span id="tel"><?= $row['tel'] ?> </span></h4>
<h4>Maticule d'assurance : <span id="matricule_assu"><?= $row['matricule_assu'] ?></span></h4>
<h4>Adresse : <span id="adress"><?= $row['adress'] ?></span></h4>
</div>
<?php } ?>
// script for making ajax call
<script>
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function (response) {
$("#nom").text(response.nom);
$("#prenom").text(response.prenom);
$("#tel").text(response.tel);
$("#matricule_assu").text(response.matricule_assu);
$("#adress").text(response.adress);
}
});
}
});
</script>
$json_data=file_get_contents('php://input');
$json=json_decode($json_data,true);
if(array_key_exists("selectName",$json)){
$selectOption =$json["selectName"];
}
I'm trying to send two values from a form to another PHP using ajax post method. One value is the value that's already entered in an input box, and the other is a value that is being typed into another input box. It acts like a search box. I tried executing the SQL query in my SQL workbench and it returns the value properly. What am I doing wrong in my code?
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
$("#sbb").html(sbb);
//searchq7();
});
}
This is the input box where I search and get the value from:
<input type="text" name="region" list="state" value="<?php echo $region; ?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" list="sbb" value="<?php echo $suburb; ?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6" >
<option> </option>
</datalist>
This is the search-suburb.php file:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state="'.$st.'" AND `title` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$suburb = $row['title'];
?>
<option value="<?php echo $suburb; ?>"><?php echo $suburb; ?> </option>
<?php
} // while
} // else
} // main if
<input type="text" name="region" list="state" value="<?=(isset($_POST['region'])?$_POST['region']:'');?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" onkeyup="searchq6()" list="sbb" value="<?=(isset($_POST['suburb'])?$_POST['suburb']:'');?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6"></datalist>
Javascript:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
var decode = jQuery.parseJSON(sbb); // parse the json returned array
var str = ""; // initialize a stringbuilder
$.each(decode, function (x, y) {
str+="<option value='" + y.title +"'>";
});
$("#sbb").html(str);
}); // end of post
}// end of searchq6 function
Php:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='{$st}' AND `title` LIKE '%{$searchq}%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
} else{
$data = array();
while($row = mysqli_fetch_array($query))
$data[] = $row;
echo json_encode($data);
}
} // main if
Got the answer from small snippets gathered through the comments
Changed the query to:
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='".$st."' AND `title` LIKE '%".$searchq."%' LIMIT 10")or die("Could not search!");
And the ajax to:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate})
.done(function(sbb) {
$("#sbb").html(sbb);
});
//searchq7();
}
Thanks for all the comments guys
I am new with ajax somebody help me I want to create a form that include input field.
Whenever I click the button I will get the value of input field and it declared it as data in AJAX and the value from ajax it pass to PHP script. It will display a table.
My question is how to get the value of input field and declared it as data in AJAX. After click the table will declared in success in AJAX Script that will show a table.
Thank you in advance
UPDATE:
#J_D, Here's my html code for my form:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<table cellpadding="15px">
<tr>
<td>Transmittal #</td>
<td><input type="text" class="form-control" style="padding-left:5px;" name="transmittal_number_inquiry" id="transmittal_number_inquiry" class="transmittal_number_inquiry" onKeyPress="return isNumberKey(event)" required></td>
</tr>
</table>
<div style="float:right; padding-right:110px; padding-top:10px;">
Inquire
<?php /*?><input type="submit" class="btn btn-info" data-toggle="modal" id="btn-inquire-transmittal-number" name="btn-inquire-transmittal-number" data-backdrop="false" value="Inquire"><?php */?>
<?php /*?><button type="submit" class="btn btn-info" data-toggle="modal" id="btn-inquire-transmittal-number" name="btn-inquire-transmittal-number" data-backdrop="false">Inquire</button><?php */?>
</div>
</form>
Here's my AJAX Code:
$(document).ready(function(){
$('.btn-inquire-traensmittal-number').click(function(){
$inputtextval = $('#transmittal_number_inquiry').val();
$.ajax({
type: 'POST',
url: getTransmittalNum.php,
data: {'transmittal_number_inquiry' : $inputtextval},
success: function(res){
}
});
});
});
Here's the getTransmittalNum.php code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "etransmittal";
$selectedTransmittal = $_GET['q'];
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['inquire-transmittal-number'])){
$query = "SELECT en.transid, en.transdate, CONCAT(userlist.lname, ', ', userlist.fname, ' ', userlist.mname) AS sender_name,
userlist.`department`, en.document_number, doctype.document_type, doctype.document_description, vendor.`vendor_name`, en.`remarks`,
en.status_id, stat.status_name, en.total_amount
FROM tbl_encode_transmittal en
LEFT JOIN tbl_vendor vendor ON vendor.`vendor_id` = en.vendor_id
LEFT JOIN tbl_doctype doctype ON doctype.`doc_id` = en.doctype_id
LEFT JOIN tbl_userlist userlist ON userlist.userid = en.sender_id
LEFT JOIN tbl_userlist userlist1 ON userlist1.userid = en.`receiver_id`
LEFT JOIN tbl_status stat ON stat.status_id = en.status_id
WHERE en.`transid` = '{$_POST['transmittal_number_inquiry']}'";
$result = mysqli_query($con, $query);
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
}
else{
echo 'MYSQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($con);
}
?>
Try following code :
$(document).ready(function(){
$('#btn-inquire-transmittal-number').click(function(){
$inputtextval = $('#transmittal_number_inquiry').val();
$.ajax({
type: 'POST',
url: 'getTransmittalNum.php', // wrap code with quote
data: {'transmittal_number_inquiry' : $inputtextval},
dataType : 'json', // expecting result type json
success: function(res){
// once you got result,
// populate table here
}
});
});
});
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "etransmittal";
//$selectedTransmittal = $_GET['q']; //<---- u need this?????
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['transmittal_number_inquiry'])){ // <-- check for existence
$query = "SELECT en.transid, en.transdate, CONCAT(userlist.lname, ', ', userlist.fname, ' ', userlist.mname) AS sender_name,
userlist.`department`, en.document_number, doctype.document_type, doctype.document_description, vendor.`vendor_name`, en.`remarks`,
en.status_id, stat.status_name, en.total_amount
FROM tbl_encode_transmittal en
LEFT JOIN tbl_vendor vendor ON vendor.`vendor_id` = en.vendor_id
LEFT JOIN tbl_doctype doctype ON doctype.`doc_id` = en.doctype_id
LEFT JOIN tbl_userlist userlist ON userlist.userid = en.sender_id
LEFT JOIN tbl_userlist userlist1 ON userlist1.userid = en.`receiver_id`
LEFT JOIN tbl_status stat ON stat.status_id = en.status_id
WHERE en.`transid` = '{$_POST['transmittal_number_inquiry']}'";
$result = mysqli_query($con, $query);
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
}
else{
echo 'MYSQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($con);
}
?>
I've quickly made a page that shows the current items in the database. I've created the function to adjust stocks levels but I am now trying to add the function to delete items. For some reason all it does is reduce the stock level to 0 but doesn't delete the item from the database.
Also would it be possible/better to put the code the generates the table into another file and load it here? As I need it to auto update when you run either the stock update or deletion function.
AJAX/HTML CODE
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$('#dataSubmit').on('submit',function(e){
$.ajax({
url:'files/update.php',
data:$(dataSubmit).serialize(),
type:'POST',
success:function(data){
console.log(data);
if(data != "Error") {
$("#data").html(data).show().fadeOut(9000);
}
else {
$("#data").html(data).show().fadeOut(9000);
}
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
document.getElementById("dataSubmit").reset();
});
});
$(document).ready(function(){
$('#deleteItem').on('dsubmit',function(e){
$.ajax({
url:'files/delete.php',
data:$(deleteItem).serialize(),
type:'POST',
success:function(data){
console.log(data);
if(data != "Error") {
$("#datad").html(data).show().fadeOut(9000);
}
else {
$("#datad").html(data).show().fadeOut(9000);
}
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
document.getElementById("deleteItem").reset();
});
});
</script>
</head>
<body>
<h2> Update Stock Levels </h2>
<form name="dataSubmit" id="dataSubmit" action="">
Product ID: <input type="number" name="Product_ID" value=""><br>
New Stock Amount: <input type="text" name="Product_Stock" value=""><br>
<input type="submit" name="submit" >
<div id="data"></div>
<h2> Delete Items </h2>
<form name="deleteItem" id="deleteItem" action="">
Product ID: <input type="number" name="Product_ID" value=""><br>
<input type="submit" name="dsubmit" >
<div id="datad"></div>
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Product Name</th><th>Product Description</th> <th>Product Price</th><th>Product Stock Amount</th></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cms";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Product_ID, Product_Name, Product_Desc, Product_Price, Product_Stock FROM Products");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
</body>
</html>
PHP CODE
<?php
$dsn = 'mysql:host=localhost;dbname=cms';
$user = 'root';
$password = '';
try {
$pdo = new PDO($dsn, $user, $password);
$pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "DELETE FROM Products WHERE Product_ID = :Product_ID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Product_ID', $_POST['Product_ID'], PDO::PARAM_INT);
$stmt->execute();
?>
You are not binding to a submit event on the delete action, you have a typo
$('#deleteItem').on('dsubmit',function(e){
^
The form is just submitting instead.
I'm trying to create a php form that sends textarea data to database. The database table uploads has 3 data items that are needed:
user_id
category
content
HTML:
<form id="myform" action="php/savetext.php" method="POST" enctype="multipart/form-data">
<p><strong>Add your story here.</strong></p>
<input type="hidden" name="fbid" id="fbid">
<input type="hidden" name="category" id="category">
<textarea cols="50" rows="10" name="usertext" id="storyArea"></textarea>
<input type="submit" name="submit" value="Saada" />
<script type="text/javascript">
$( "#fbid" ).val( "sdf88d99sd" );
$( "#category" ).val( "texts" );
</script>
</form>
savetext.php:
include_once('config.php');
if (isset($_POST['user_id']) && isset($_POST['category']) && isset($_POST['usertext'])) {
$user_id = mysql_real_escape_string($_POST['fbid']);
$category = mysql_real_escape_string($_POST['category']);
$content = mysql_real_escape_string($_POST['usertext']);
addUser($user_id, $category, $content);
}
else {
echo 'Upload failed! Try again.';
}
function addUser($user_id, $category, $content) {
$query = "SELECT id FROM uploads WHERE user_id = '$fbid' LIMIT 1";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
if ($rows > 0) {
$query = "UPDATE uploads SET user_id = '$user_id', category = '$category' WHERE content = '$content'";
}
else {
$query = "INSERT INTO uploads (user_id, category, content) VALUES ('$user_id', '$category', '$content')";
}
mysql_query($query);
echo 'Upload was succesful. Thank you!';
}
But this doesn't work. Any ideas on how to correct this?
please review this code ,there is no field with name user_in in <form></form>
if (isset($_POST['fbid']) && isset($_POST['category']) && isset($_POST['usertext'])) {
$user_id = mysql_real_escape_string($_POST['fbid']);
$category = mysql_real_escape_string($_POST['category']);
$content = mysql_real_escape_string($_POST['usertext']);
addUser($user_id, $category, $content);
}