0

Ajax Jquery is not working in php page. I want retrieve mysql database in same php page without refresh the page. By selecting option from data list other text box will fill depend on list. Please help me to find the error.Thank you.

here is my javascript code

 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
        $(document).ready(function(){
            $("#item").change(function(){
                //alert("Changed");
                $.ajax({

                    type:"POST",
                    url:"json.php",
                    data:{item:$("#item").val()},
                    success: function(data){
                        var iobj = $.parseJSON(data);
                        $.each(iobj, function(){
                            $("#item").val(this['hsn']);
                            $("#pack").val(this['pack']);
                        });
                    }
                });
            });
        });
    </script>

php file

<td valign="middle">
  <input list="code" name="item" id="item" class="textbox" tabindex="8">
   <td valign="middle">

  <?php
   $item=mysqli_query($con,"SELECT itname,itemcode FROM itementry");
   echo '<datalist id="code" width="150%" style="font-size:30px;">';
   while($row=mysqli_fetch_array($item)){

   $itm = $row['itname'] .'|' .$row['itemcode'];
   $ITMMM = $row['itemcode'];
   echo '<optgroup>';
   echo '<option value="'.$ITMMM.'" style="font-size: 50px;">';

   echo '</option>';
   echo '</optgroup>';
    }
   echo '</datalist>';
   ?>
 </td>
 <td valign="middle"><input type="text" name="hsn" id="hsn" class="textbox" tabindex="9"></td>
 <td valign="middle"><input type="text" name="pack" id="pack" class="textbox" tabindex="10"></td>
 <td valign="middle"><input type="text" name="rack" id="rack" class="textbox" tabindex="11"></td>
 <td valign="middle"><input type="text" name="punit" id="punit" class="textbox" tabindex="12"></td>

json.php

    <?php
include 'connect.php';
$item = $_POST['item'];
$start = strpos($item,'|')+2;
$code = substr($item, $start);
echo 'Item code:'.$item;

$sql = "select * from itementry where itemcode  ='".$item."'";
$result = mysqli_query($con, $sql)or die(mysqli_error($con));

$rows = array();

while ($r = mysqli_fetch_assoc($result)){
    $rows[]=$r;    
}
echo json_encode($rows);
?>
Ajoy
  • 189
  • 1
  • 5
  • 17
  • Console errors? PHP Error messages? Where is `#item` IDs must be unique. – mplungjan Dec 03 '17 at 07:36
  • That PHP code is vulnerable to SQL Injection. You are not sanitizing `$item`. – Sumner Evans Dec 03 '17 at 07:38
  • No error. It will not shown any error probably just data is not retrieve from from database to other field. – Ajoy Dec 03 '17 at 07:39
  • can please help me, how to do it. – Ajoy Dec 03 '17 at 07:40
  • Does `alert("Changed");` actually alert? And where is #item – mplungjan Dec 03 '17 at 07:44
  • item is there i for to add. Added now. – Ajoy Dec 03 '17 at 07:46
  • Don't you mean `$("#hsn").val(this['hsn']);` – mplungjan Dec 03 '17 at 08:03
  • yes $("#hsn").val(this['hsn']); it is not working. – Ajoy Dec 03 '17 at 08:09
  • Generally if you are POSTing to the same page you need to isolate the portion of code that responds to the ajax request otherwise it is likely the response will include all of the page and not just the specific data you requested. Use `ob_clean();` then the cmds to process request then `exit/die` – Professor Abronsius Dec 03 '17 at 08:16
  • 1
    We have no use for "It's not working" You need to debug. Right click, inspect the network traffic and see if there is an error - add an error : function(): https://stackoverflow.com/a/14563181/295783 – mplungjan Dec 03 '17 at 08:17
  • But i using same code for other software. Dont understand why it is not working for this. – Ajoy Dec 03 '17 at 08:27
  • Ok, so why are you sending an echo message AND a json_encoded array? Might that be your issue as the console errors suggest? Plus please watch your variable naming and styling. – TimBrownlaw Dec 03 '17 at 09:22

1 Answers1

0

Ok so I've taken your code and made up something from it...

The supplied code in this answer "Works" based upon what you provided. It gets a response and fills in the two other hsn and pack form inputs which is what your question is regarding.

SO look through it and see what is what and what different to what you have.

Test Database

CREATE DATABASE IF NOT EXISTS `phptutorials_st9` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `phptutorials_st9`;

-- --------------------------------------------------------

--
-- Table structure for table `itementry`
--

CREATE TABLE IF NOT EXISTS `itementry` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `itname` varchar(48) NOT NULL,
  `itemcode` int(11) NOT NULL,
  `hsn` varchar(48) NOT NULL,
  `pack` varchar(48) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `itementry`
--

INSERT INTO `itementry` (`id`, `itname`, `itemcode`, `hsn`, `pack`) VALUES
(1, 'Item 1', 1, 'hsn 1', 'pack 1'),
(2, 'Item 2', 2, 'hsn 2', 'pack 2');

connect.php

<?php
$con = mysqli_connect('localhost','root','test','phptutorials_st9');

index.php

<?php
include 'connect.php';
?>

<td valign="middle">
    <label>Item</label>
    <input list="code" name="item" id="item" class="textbox" tabindex="8">
<td valign="middle">

    <?php
    $item = mysqli_query($con, "SELECT itname,itemcode FROM itementry");
    //var_dump($item->num_rows);
    echo '<datalist id="code" width="150%" style="font-size:30px;">';
    //@TB Added MYSQLI_ASSOC to only get associative entries
    while ($row = mysqli_fetch_array($item, MYSQLI_ASSOC)) {
        $itm = $row['itname'] . '|' . $row['itemcode']; // Where is this used
        $ITMMM = $row['itemcode'];
        echo '<optgroup>';
        echo '<option value="' . $ITMMM . '" style="font-size: 50px;">';
//@TB Added
//        echo $itm;
        echo '</option>';
        echo '</optgroup>';
    }
    echo '</datalist>';
    ?>
</td>
<td valign="middle"><input type="text" name="hsn" id="hsn" class="textbox" tabindex="9"></td>
<td valign="middle"><input type="text" name="pack" id="pack" class="textbox" tabindex="10"></td>
<td valign="middle"><input type="text" name="rack" id="rack" class="textbox" tabindex="11"></td>
<td valign="middle"><input type="text" name="punit" id="punit" class="textbox" tabindex="12"></td>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="list.js"></script>

list.js

$(document).ready(function () {
    // $("#item").on('change', function () {
    $("#item").change(function () {
        var item = $("#item").val();
        console.log('Item Changed');
        $.ajax({
            type: "POST",
            url: "json.php",
            data: {item: item},
            success: function (data) {
                var iobj = $.parseJSON(data);
                console.log(iobj);
                $.each(iobj, function () {
                    $("#hsn").val(this['hsn']);
                    $("#pack").val(this['pack']);
                });
            }
        });
    });
});

json.php

<?php
include 'connect.php';
$item = $_POST['item'];
$start = strpos($item,'|')+2;
$code = substr($item, $start);
//echo 'Item code:'.$item;
$sql = "SELECT * FROM itementry WHERE itemcode  ='".$item."'";
$result = mysqli_query($con, $sql)or die(mysqli_error($con));

$rows = array();

while ($r = mysqli_fetch_assoc($result)){
    $rows[]=$r;
}
echo json_encode($rows);

I cannot go over everything as this isn't a code review but things to watch.

  1. Be Consistent with variable naming and don't use shortnames like $itm You also use $itname. Is that meant to be $item_name? Then you use $ITMMM ( all capitals ) no idea what that means.
  2. Be Consistent with use of your mysqli. You use mysqli_fetch_array and mysqli_fetch_assoc... Probably stick with mysqli_fetch_assoc - Look them Up!

  3. Learn you use your browsers developer tools and use the console when validating your jquery/AJAX stuff.

TimBrownlaw
  • 5,457
  • 3
  • 24
  • 28
  • Thats save my lot of time and your advice is very useful for me. I will keep in mind of naming variable name. And the real issue is I was printing $item in json.php now every thing ok. Thank you once again. – Ajoy Dec 03 '17 at 15:24