Dependent drop down with multiple .onchange - javascript

I am working on a search system where the user is prompted with 4 drop downs on the index.php. I have that the user selects the first drop down and then the values of the 2nd, 3rd and 4th drop down values changes to the value that is relevant to the first drop down. I am using the _POST to get the onchange value and to display the data to the rest of drop down. I have also done the same that if the user selects the 2nd drop down on the initial search the 1st ,3rd and 4th values changes to the values that are relevant to the selected drop down. I have done this for all the drop downs. The system is working, but is there a better way of doing this rather than having multiple _POST and .onchange values?
This is the script for the drop down:
$(document).ready(function(){
/////start commodity post
$('#pfcommodity').on('change', function(){
var pfcommodity = $(this).val();
if(pfcommodity){
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pfcategory",
data:'pfcommodity='+pfcommodity,
success: function(data)
{
//console.log(data);
$("#pfcategory").html(data);
}
});
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pforigin",
data:'pfcommodity='+pfcommodity,
success: function(data)
{
$("#pforigin").html(data);
}
});
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pfmanufacture",
data:'pfcommodity='+pfcommodity,
success: function(data)
{
$("#pfmanufacture").html(data);
}
});
}
});////close commodity post
////open category post
$('#pfcategory').on('change', function(){
var pfcategory = $(this).val();
if(pfcategory){
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pfcategory",
data:'pfcategory='+pfcategory,
success: function(data)
{
//console.log(data);
$("#pfcommodity").html(data);
}
});
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pforigin",
data:'pfcategory='+pfcategory,
success: function(data)
{
$("#pforigin").html(data);
}
});
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pfmanufacture",
data:'pfcategory='+pfcategory,
success: function(data)
{
$("#pfmanufacture").html(data);
}
});
}
});////close category post
// ////open origin post
$('#pforigin').on('change', function(){
var pforigin = $(this).val();
if(pforigin){
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pfcategory",
data:'pforigin='+pforigin,
success: function(data)
{
//console.log(data);
$("#pfcommodity").html(data);
}
});
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pforigin",
data:'pforigin='+pforigin,
success: function(data)
{
$("#pfcategory").html(data);
}
});
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pfmanufacture",
data:'pforigin='+pforigin,
success: function(data)
{
$("#pfmanufacture").html(data);
}
});
}
});////close origin post
// ////open manufacure post
$('#pfmanufacture').on('change', function(){
var pfmanufacture = $(this).val();
if(pfmanufacture){
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pfcategory",
data:'pfmanufacture='+pfmanufacture,
success: function(data)
{
//console.log(data);
$("#pfcommodity").html(data);
}
});
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pforigin",
data:'pfmanufacture='+pfmanufacture,
success: function(data)
{
$("#pfcategory").html(data);
}
});
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pfmanufacture",
data:'pfmanufacture='+pfmanufacture,
success: function(data)
{
$("#pforigin").html(data);
}
});
}
});////close manufacture post
});
This is the first query pfcategory.php
<?php
if (isset($_POST['pfcommodity'])){
$connect=mysqli_connect("localhost","root","","import-conditions");
$output='';
$sql="SELECT DISTINCT category FROM processfood WHERE commodity = '".$_POST["pfcommodity"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Category</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["category"].'</option>';
}
echo $output;
}
if (isset($_POST['pfcategory'])){
$connect=mysqli_connect("localhost","root","","import-conditions");
$output='';
$sql="SELECT DISTINCT commodity FROM processfood WHERE category = '".$_POST["pfcategory"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Commodity</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["commodity"].'</option>';
}
echo $output;
}
if (isset($_POST['pforigin'])){
$connect=mysqli_connect("localhost","root","","import-conditions");
$output='';
$sql="SELECT DISTINCT commodity FROM processfood WHERE origin = '".$_POST["pforigin"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Commodity</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["commodity"].'</option>';
}
echo $output;
}
if (isset($_POST['pfmanufacture'])){
$connect=mysqli_connect("localhost","root","","import-conditions");
$output='';
$sql="SELECT DISTINCT commodity FROM processfood WHERE manufacture = '".$_POST["pfmanufacture"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Commodity</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["commodity"].'</option>';
}
echo $output;
}
?>
this is pforigin.php
<?php
$connect=mysqli_connect("localhost","root","","import-conditions");
$output='';
if (isset($_POST['pfcommodity'])){
$sql="SELECT DISTINCT origin FROM processfood WHERE commodity = '".$_POST["pfcommodity"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Country of Origin</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["origin"].'</option>';
}
echo $output;
}
if (isset($_POST['pfcategory'])){
$sql="SELECT DISTINCT origin FROM processfood WHERE category = '".$_POST["pfcategory"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Country of Origin</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["origin"].'</option>';
}
echo $output;
}
if (isset($_POST['pforigin'])){
$sql="SELECT DISTINCT category FROM processfood WHERE origin = '".$_POST["pforigin"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Category</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["category"].'</option>';
}
echo $output;
}
if (isset($_POST['pfmanufacture'])){
$sql="SELECT DISTINCT category FROM processfood WHERE manufacture = '".$_POST["pfmanufacture"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Category</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["category"].'</option>';
}
echo $output;
}
?>
this is pfmanufacture.php
<?php
$connect=mysqli_connect("localhost","root","","import-conditions");
$output='';
if (isset($_POST['pfcommodity'])){
$sql="SELECT DISTINCT manufacture FROM processfood WHERE commodity = '".$_POST["pfcommodity"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Manufacture</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["manufacture"].'</option>';
}
echo $output;
}
if (isset($_POST['pfcategory'])){
$sql="SELECT DISTINCT manufacture FROM processfood WHERE category = '".$_POST["pfcategory"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Manufacture</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["manufacture"].'</option>';
}
echo $output;
}
if (isset($_POST['pforigin'])){
$sql="SELECT DISTINCT manufacture FROM processfood WHERE origin = '".$_POST["pforigin"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Manufacture</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["manufacture"].'</option>';
}
echo $output;
}
if (isset($_POST['pfmanufacture'])){
$sql="SELECT DISTINCT origin FROM processfood WHERE manufacture = '".$_POST["pfmanufacture"]."'";
$result=mysqli_query($connect,$sql);
$output.='<option value="">Select Country of Origin</option>';
while ($row=mysqli_fetch_array($result)) {
$output.='<option value="">'.$row["origin"].'</option>';
}
echo $output;
}
?>
All of the other pages follow this same pattern. There is no problem with it so far, but is there a better way of doing this?

First reduce the jquery code by using a class for the event handler, use a data-type attribute to pass in the type.
<select class="pf_select" data-type="commodity">
<option value="">Select Category</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<select>
Doing so you can remove all but one of them jquery calls, with a small change.
$('.pf_select').on('change', function() {
var elm = $(this);
var type = elm.data('type');
var commodity = elm.val();
if (commodity !== '') {
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pfcategory",
data: 'pf' + type + '=' + commodity,
success: function(data) {
elm.html(data);
}
});
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pforigin",
data: 'pf' + type + '=' + commodity,
success: function(data) {
elm.html(data);
}
});
$.ajax({
method: "POST",
url: "/import-conditions/processfood/pfmanufacture",
data: 'pf' + type + '=' + commodity,
success: function(data) {
elm.html(data);
}
});
}
});
Now onto the PHP:
You only need to connect to the database once, so just put that at the top.
Then all that changes between the calls, is the table name and the POST variable key. So you can easily wrap the database call and the html render, into a single function and pass in variables.
Then you simply call the function inside your if statement.
<?php
$connect = mysqli_connect("localhost","root","","import-conditions");
function pf_select($key, $select_label = 'Select Category') {
global $connect;
$stmt = $connect->prepare('
SELECT DISTINCT category
FROM processfood
WHERE '.$key.' = ?');
$stmt->bind_param('s', $_POST['pf'.$key]);
$stmt->execute();
$result = $stmt->get_result();
$output = '<option value="">'.$select_label.'</option>';
while ($row = $result->fetch_assoc()) {
$output .= '<option value="'.$row["category"].'">'.$row["category"].'</option>';
}
return $output;
}
if (isset($_POST['pfcommodity'])) {
exit(pf_select('commodity', 'Select Category'));
}
if (isset($_POST['pfcategory'])) {
exit(pf_select('category', 'Select Commodity'));
}
if (isset($_POST['pforigin'])) {
exit(pf_select('origin', 'Select Commodity'));
}
if (isset($_POST['pfmanufacture'])) {
exit(pf_select('manufacture', 'Select Commodity'));
}
Much more readable, and manageable.
Note: I did not add database error checking, you should add that anyway, and also read up on preventing SQL injection.

Related

get states of country return null

I am trying to get country states but it returns null
here is my code
the adding form
<select class="form-control" id="country-dropdown">
<option value="">Select Country</option>
<?php
$countries = get_rows('tbl_countries');
foreach($countries as $country):
echo '<option value='.$country['id'].'>'.$country['name'].'</option>';
endforeach;
?>
</select>
<select name="state" class="form-control" id="state-dropdown" required="required">
</select>
<select name="city" class="form-control" id="city-dropdown" required="required">
</select>
Ajax Code
to get country states
<script>
$(document).ready(function() {
$('#country-dropdown').on('change', function() {
var country_id = this.value;
$.ajax({
url: "getStates.php",
type: "GET",
data: {
country_id: country_id
},
cache: false,
success: function(result){
$("#state-dropdown").html(result);
$('#city-dropdown').html('<option value="">Select State First</option>');
console.log("this is "+ result);
}
});
});
$('#state-dropdown').on('change', function() {
var state_id = this.value;
$.ajax({
url: "getCities.php",
type: "GET",
data: {
state_id: state_id
},
cache: false,
success: function(result){
$("#city-dropdown").html(result);
}
});
});
});
</script>
code in getStates file
<?php
//connect file
include "../init.php";
$country_id = $_GET['country_id'];
$stmt = $con->prepare("SELECT * FROM tbl_states WHERE country_id = ?");
$stmt->execute(array($country_id));
$rows = $stmt->fetchAll();
foreach($rows as $row){
echo '<option value='.$row['id'].'>'.$row['name'].'</option>';
}
The result is null
if I remove the country_id condition it returns all states not the choosen country states
wheres the problem with my code

Why do I keep getting NULL returned?

I am creating a booking system for a university project and I am trying to add an author to the table 'authors' for some reason when I add a field it returns as NULL in my database and undefined on my html page? Can anyone help me with this I have shown my HTML, Javascript and php code below.
Can anyone help me with this and guide me in the right direction. I have a feeling it is something to do with my names eg. authors or author
Thanks in advance.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="w3.js"></script>
<script src="https://scm.ulster.ac.uk/zhiwei.lin/js/jquery.tmpl.min.js"></script>
</head>
<body>
<div id="authors">
<ul id="authors_list"></ul>
</div>
<div class="mainArea">
<label>Author:</label>
<input type="text" id="author" name="name" required>
<button id="btnSave">Save</button>
<button id="btnUpdate">Update</button>
</div>
<p>Click Here to Delete Last Author
<button id="btnDelete">Delete</button></p>
</body>
</html>
Js
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: "json",
url: "api.php/authors",
success: showAllAuthors,
error: showError
});
});
function showAllAuthors(responseData) {
$.each(responseData.authors,function(index,authors){
$("#authors_list").append("<li type='square'> author:"+authors.author+"");
$("#authors_list").append("</li>");
});
}
function showError(){
alert("Sorry, there was a problem!");
}
$(document).ready(function(){
$("#btnSave").click(function(){
$.ajax({
type: 'POST',
dataType: "json",
url: "api.php/authors",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: showResponse,
error: showError
});
});
});
function authors(Author){
this.author=Author;
}
function showResponse(responseData) {
console.log(responseData);
}
function showError() {
alert("Sorry, there was a problem!");
}
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: "json",
url: "api.php/authors/12",
success: showResponse,
error: showError
});
});
$(document).ready(function(){
$("#btnUpdate").click(function(){
$.ajax({
type: 'PUT',
dataType: "json",
url: "api.php/authors/12",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: alert("Updated!")
});
});
});
$(document).ready(function(){
$("#btnDelete").click(function(){
$.ajax({
type: 'DELETE',
dataType: "json",
url: "api.php/authors/13",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: alert("Deleted!")
});
});
});
PHP
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
use Slim\Slim;
$app=new Slim();
$app->get('/authors','getAuthors');
$app->post('/authors','addAuthor');
$app->get('/authors/:id','getAuthor');
$app->put('/authors/:id','updateAuthor');
$app->delete('/authors/:id', 'deleteAuthor');
$app->run();
function deleteAuthor($id) {
$sql = "DELETE FROM authors WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
responseJson("Deleted",200);
}catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function updateAuthor($id) {
$request = Slim::getInstance()->request();
$body = $request->getBody();
$authors = json_decode($body);
$sql = "UPDATE authors SET author=:author WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("author", $authors->author);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
responseJson("Updated",200);
} catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function getAuthor($id) {
$sql = "SELECT * FROM authors WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$authors = $stmt->fetchObject();
$db = null;
responseJson(json_encode($authors),200);
} catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function getAuthors(){
$sql = "select * FROM authors ORDER BY id";
try {
$db = getConnection();
$stmt = $db->query($sql);
$authors = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
responseJson('{"authors":'.json_encode($authors).'}',200);
}catch(PDOException $e){
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function addAuthor(){
$request = Slim::getInstance()->request();
$authors=json_decode($request->getBody());
$sql= "INSERT INTO authors (author)
VALUES (:author)";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("author", $authors->author);
$stmt->execute();
$authors->id=$db->lastInsertId();
$db = null;
responseJson(json_encode($authors),201);
}catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function getConnection(){
$dbhost="localhost";
$dbuser="B00657229";
$dbpass="9wz7Fr9J";
$dbname="B00657229";
$dbh= new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser,$dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function responseJson($responseBody,$statusCode){
$app = Slim::getInstance();
$response = $app->response();
$response['Content-Type']='application/json';
$response->status($statusCode);
$response->body($responseBody);
}
?>
There seems to be a mistake in your js code:
$(document).ready(function(){
$("#btnSave").click(function(){
$.ajax({
type: 'POST',
dataType: "json",
url: "api.php/authors",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: showResponse,
error: showError
});
});
you set data two times, one time with
{author: $("#author").val()} and other time with JSON.stringify(authors) i don't think you need the second one, but I did not test this.

Change event not triggered on ajax call

In the below code I have a dropdown (id-name) which populated from listplace.php'. Also made another ajax call which when the dropdown item is selected it lists the specific product fromdataprod.php`
Problem: when I click on the specific item from drop-down it does not trigger the Ajax event
I checked the dataprod.php it works correctly, but even after binding the change event with my dropdown box I m not getting the result. Please help..
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<script>
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = this.value;
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});
</script>
<?php } ?>
dataprod.php
<?php
include("config.inc.php");
$name1 = $_POST['name1'];
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code,
product_image, product_price FROM products_list where product_name='$name1'");
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
You need to pass the selected value in the ajax call.
change this line from
var name1 = this.value;
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
to
var name1 = this.value;
$.ajax ({
data: {name1: name1},
type: 'POST',
HTML:
you can store the values in hidden field like:
<input type='hidden' name='name1' id='name1' value='<?= $_GET["name1"] ?>'>
Javascript:
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = $('#name1').val();
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});

multiple option boxes same name jquery ajax

I've got multiple select boxes that have the same name. Right now when I select the value from the first select box its submitting that one and updating the database. When I select and item on an other select box its submitting the value from the first one. I feel like the javascript isn't right. Any idea what is wrong?
Heres my html:
<?php foreach ($result as $row): ?>
<select class="form-control" name="category[]" required>
<option value="" disabled selected>Select The Category </option>
<option value="station">Station</option>
<option value="equipment">Tools/Equipment</option>
<option value="supplies">Supplies</option>
</select>
<input id="taskID" value="<?php echo $row['id']; ?>" hidden></input>
<?php endforeach; ?>
jquery:
$(document).on('change', 'select[name="category[]"]', function(event){
$('select[name="category[]"]').each(function(){
var formData = {
'task': $('select[name="category[]"]').val(),
'name': $('input[name="taskID[]"]').val(),
};
$.ajax({
type: 'POST',
url: 'php/addressBook.php',
data: formData,
dataType: 'html',
encode: true
})
.done(function(msg) {
$(".alert").html(msg);
})
.fail(function(data) {
console.log(data);
})
event.preventDefault();
});
});
addressBook.php
if (isset($_POST['task'])) {
$task = $_POST['task'];
$id = $_POST['name'];
$stmt = $con->prepare("UPDATE members SET task = ? WHERE id = ?");
$stmt->bind_param('ss', $task, $id);
$stmt->execute();
}
Change the class attribute to: class="form-control categorySelect"
$('.categorySelect').change(function(event){
for(selectInstance of $('.categorySelect')){
var formData = {
'task': $(selectInstance).val(),
'name': $(selectInstance).next().val()
};
$.ajax({
type: 'POST',
url: 'php/addressBook.php',
data: formData,
dataType: 'html',
encode: true
})
.done(function(msg) {
$(".alert").html(msg);
})
.fail(function(data) {
console.log(data);
})
event.preventDefault();
}
});

Get value in textbox using ajax response

I want Broker Commsion on Selection of Admin with the help of Ajax Only.
<select id="user_id" onchange="funCom(this);" >
<option value="" >Select Broker </option>
<?php $aData=$oGeneral->get_records('tbl_user');
$aUsertDetails = $oGeneral->aAdmin;
$iUserDetails = $oGeneral->iAdmin;
for($i=0;$i<$iUserDetails;$i++){?>
<option value="<?=$aUsertDetails[$i]['fld_id']?>">
<?php echo $aUsertDetails[$i]['fld_name']; ?></option>
<?php }?>
</select>
<input type="text" id="comm" name="fld_commision" value="" onkeyup="sum()" required>
Funtion calling
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
dataType: 'text',
type: 'post',
async: false,
data: SendData,
success: function(data)
{
//var commision=stripHTML(data);
//$('#comm').val(commision); again not working
//$('#comm').text(data); Tried this but fail
$('#comm').val(data); //output is <body></body></html>7000
// i want only 7000 i have tried
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
} });
}
It is Ajaxhandler.php.
Here I am geting the commsion value which needs to put into textbox. The value is showing in <div> but I want in text box.
<?php
require('../configuration/configuration.php');
$oGeneral = new GeneralClass();
$oUser = new UserClass();
$token= $_REQUEST['Token'];
switch($token) {
case 'search-comm': $id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo $total;
break;
}
?>
Change your datatype to json and try this.
Funtion calling
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
dataType: 'json',
type: 'post',
async: false,
data: SendData,
success: function(data)
{
//var commision=stripHTML(data);
//$('#comm').val(commision); again not working
//$('#comm').text(data); Tried this but fail
$('#comm').val(data.total); //output is <body></body></html>7000
// i want only 7000 i have tried
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
} });
}
is Ajaxhandler.php
$token= $_REQUEST['Token'];
switch($token)
{
case 'search-comm': $id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo json_encode(array('total'=>$total));
break;
}
?>
try this code, I test in my computer and that works!
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
type: 'POST',
data: {Token:Token,id:id},
}).done(function( data ) {
$("#comm").val(data.total);
});
<?php
$token= $_REQUEST['Token'];
header('Content-type: application/json');
switch($token)
{
case 'search-comm':
$id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo json_encode(array('total'=>$total));
die;
}
echo json_encode(array('total'=>""));
die;
?>

Categories

Resources