-1

I have a problem. I tried all possible solutions but always getting undefined index. I've tried this before and it works fine. I don't know what happened today, I've just copy paste it.

What I'm trying to do in here is to have an AJAX search.

prod_stocks_add.php

    <?php
     include("headerindex.php");
      include("sidebar.php");
     ?>

    <div class="right_col" role="main">
      <div class="">
        <div class="col-md-12 col-sm-12 col-xs-12">
   <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="prod_info.php">Product Stocks</a></li>
      <li class="breadcrumb-item active">Add Stocks</li>
      <a href="prod_stocks.php" class="btn btn-warning btn-lg pull-right"><i class="fa fa-history"></i>&nbsp;Back</a>
    </ol>

    <div class="x_panel">
    <div class="x_title">
      <h4><b>Add Stocks<b></h4>
          <div class="clearfix"></div>
    </div>
          <div class="x_content">
            <div class="row">
              <div class="col-sm-12">
                <div class="card-box table-responsive">
                  <form role="form" method="post" action="#" class="form-horizontal form-label-left" novalidate enctype="multipart/form-data">
                    <div class="item form-group">
                      <div class="control-label col-md-12 col-sm-12 col-xs-6 form-group top_search" style="margin-left: 90px;">
                        <div class="input-group">
                          <input type="text" name="search" id="search" placeholder="Search for...">
                          <div id="back_result"></div>
                        <!--   <span class="input-group-btn">
                            <select class="btn btn-primary" name="searchfilter" id="searchfilter">
                              <option value="Barcode">Barcode</option>
                              <option value="Item">Item</option>
                            </select>
                            </span> -->
                            <div class="col-md-3 col-sm-3 col-xs-6" style="margin-bottom: -500px;">
                            <!-- <button type="button" class="btn btn-success"><i class="fa fa-check"></i><span>Go</button> -->
                            </div>
                            </div>
                        </div>
                      </div>
                    <br>
                    <div class="item form-group">
                    <label class="control-label col-md-6 col-sm-6 col-xs-12" for="category" name="lbl_category">Item <span class="required">*</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                      <label></label>
                    </div>
                  </div>
                  <div class="item form-group">
                    <label class="control-label col-md-6 col-sm-6 col-xs-12" for="barcode" name="lbl_barcode">Barcode <span class="required">*</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                      <label></label>
                    </div>
                  </div>
                  <div class="item form-group">
                    <label class="control-label col-md-6 col-sm-6 col-xs-12" for="batch" name="lbl_batch">Batch Stock <span></span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                      <input type="int" id="batch" name="txt_batch" class="form-control col-md-7 col-xs-12" style="width:200px;">
                    </div>
                  </div>
                  <div class="item form-group">
                    <label class="control-label col-md-6 col-sm-6 col-xs-12" for="total" name="lbl_total">Total Stock <span class="required">*</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12 form-group">
                      <label></label>
                    </div>
                  </div>
                  <div class="item form-group" style="margin-top:-300px">
                    <label class="control-label col-md-1 col-sm-1 col-xs-6" for="image" name="lbl_img">Image <span class="required"></span>
                    </label>
                    <div class="col-md-1 col-sm-1 col-xs-6">  
                     <!--  <a tabindex="-1" href="#myModal" data-toggle="modal"><b><i class="fa fa-file-image-o" aria-hidden="true"></i>  PICTURE</b></a><br></br>
                      <a tabindex="-1" href="#myModal" data-toggle="modal" role="button"><i class="fa fa-file-image-o fa-5x" aria-hidden="true"></i></a><br></br>
                      --> 
                    </div>
                  </div>
                  <div class="ln_solid"></div>
                  <div class="form-group">
                    <div class="col-md-6 col-md-offset-3">
                      <button type="submit" class="btn btn-primary">Cancel</button>
                      <button class="btn btn-success" name="btnsubmit">Submit</button>
                    </div>
                  </div>
                </form>
                </div>
              </div>
            </div>
          </div>
    </div>
</div>
      </div>
    </div>
    <script>
    $(document).ready(function(){

       var callAjax = (function(){

        var search = $('#search').val();

        $.ajax({
          url: 'get_users.php',
          dataType: "text",
          type: 'POST',
          data: {search: search},
          success: function(output){
            alert(output);
          }
        });

        }
      });
    </script>

    <?php
    include("footerindex.php");
    ?>

And this is my get_users.php

    <?php
    include("../db/conn.php");
    $name = $_POST['search'];
    $sql = "select * from product_info where prod_name like '%".$name."%'";
    $array = mysqli_query($conn, $sql) or die(mysqli_error($conn));
    $row = mysqli_fetch_array($array);

    echo $row['prod_name'];


    ?>

This is the error:

Notice: Undefined index: search in C:\xampps\htdocs\josephine\admin\get_users.php on line 3 ddddd

It returns the data which is "ddddd" from the database. What I don't get is the undefined index of search from AJAX

Ivan
  • 34,531
  • 8
  • 55
  • 100
  • 2
    A note for the future: Validate/sanitize the `$_POST` to ensure that it is being passed. Then, when it doesn't get passed the error doesn't show. – Script47 Aug 17 '17 at 08:56
  • 2
    **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Aug 17 '17 at 08:58
  • 1
    check your network tab in the browser and examine the ajax request to see if the search value is actually being passed to the server in your request. – ADyson Aug 17 '17 at 09:00
  • Are you sure you're calling `callAjax()`? I don't see anything that calls it. – Barmar Aug 17 '17 at 09:15
  • I don't see where are you submiting the form – Masivuye Cokile Aug 17 '17 at 09:15
  • @Barmar exactly the function is never used, and the button does not have any click function attached to it – Masivuye Cokile Aug 17 '17 at 09:16
  • Then I'm curious how data is returned if the function is never called when the OP says *It returns the data which is "ddddd" from the database.*. – Script47 Aug 17 '17 at 09:21
  • Missing close parenthesis . check your js syntax @Script47 – JYoThI Aug 17 '17 at 09:23
  • @Script47 where do you see the function being called in the question above? or the OP does not show us all the code – Masivuye Cokile Aug 17 '17 at 09:28
  • @MasivuyeCokile I don't see it being called I'm pointing out that without it being called the OP is saying that they are getting data back. – Script47 Aug 17 '17 at 09:30
  • Take a look on my answer .it might help you – JYoThI Aug 17 '17 at 09:44

3 Answers3

1

To get rid of the error, you need to do something like so:

<?php
include("../db/conn.php");
$name = (isset($_POST['search'])) ? $_POST['search'] : ""; // see this line
$sql = "select * from product_info where prod_name like '%".$name."%'";
$array = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$row = mysqli_fetch_array($array);

echo $row['prod_name'];


?>

PHP 7 addressed this issue; See: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

But you should change your sql stuff because you're vuln to injection.

Edit: -1?!?! I'm actually triggered. This is the CORRECT way of handling this issue. It's not "masking" it as someone with over 300k rep says.
READ THIS : PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"

The notices above appear often when working with $_POST, $_GET or $_SESSION. For $_POST and $_GET you just have to check if the index exists or not before you use them.

Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34
IsThisJavascript
  • 1,726
  • 2
  • 16
  • 25
  • 2
    That just masks the problem. `$_POST['search']` should always be set when he makes the AJAX call. – Barmar Aug 17 '17 at 09:04
  • 1
    Ideally you'd wrap the whole code in the `isset` and have an `else` condition where you'd return to the user a message to fill the field in and on the front end you'd prevent them from sending an empty field. – Script47 Aug 17 '17 at 09:06
  • Please see the answer from this question: https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef @Barmar – IsThisJavascript Aug 17 '17 at 09:06
  • I know that question well. It doesn't solve this problem. The variable should always be set because he has `{search: search}` in the `$.ajax` call. – Barmar Aug 17 '17 at 09:12
  • @Script47 Even if the user doesn't fill in the field, `$_POST['search']` should still be set. It will be set to an empty string, so there shouldn't be a PHP warning. – Barmar Aug 17 '17 at 09:13
  • He's handling his Ajax correctly?! You get this notice anytime you use a $_GET or $_POST without using said check – IsThisJavascript Aug 17 '17 at 09:13
  • @Barmar I know, I was merely suggesting to the OP a 'better' way to handle the situation, I understand the issue the OP is facing. – Script47 Aug 17 '17 at 09:16
  • @barmar did you -1 me? – IsThisJavascript Aug 17 '17 at 09:18
  • @Script47 Checking for an empty input is better done in the client, so you don't make the ajax request at all. – Barmar Aug 17 '17 at 09:18
  • @Barmar please read the second part of my original comment, I already mentioned that. Though, I'd still have the check both client/server side. – Script47 Aug 17 '17 at 09:19
  • @WillParky93 No I didn't. – Barmar Aug 17 '17 at 09:19
  • 1
    Regardless of checking for an empty input on client. You still need it on the server or else php will throw this issue. It always has and always will when working with $_GET and $_POST. Please test this in your environment. – IsThisJavascript Aug 17 '17 at 09:20
  • 1
    @Barmar you said "Checking for an empty input is better done in the client, so you don't make the ajax request at all." True in terms of improved user experience, but for security / robustness it should always be checked on the server as well, in case a malicious user bypasses the UI. The server-side should be the first part of that sequence to be implemented, since it's the most important. UX niceness can be added later. – ADyson Aug 17 '17 at 09:21
  • I understand that in general, but in this case an empty input could be perfectly valid, it matches everything. – Barmar Aug 17 '17 at 09:24
  • PHP is telling you that someone can craft a null POST and send it to the page. You're trusting the client too much.. – IsThisJavascript Aug 17 '17 at 09:27
  • 1
    @WillParky93 The right thing to do when given invalid input is report an error, not just replace it with a null string. – Barmar Aug 17 '17 at 09:29
1

1st : If user submiting empty string means you have to notify the user that should not be empty .

2nd : Try to use prepared statement to avoid sql injection .

3rd : you need to call the ajax function on button click .

<button  type="button" id="button_submit" class="btn btn-success" name="btnsubmit">Submit</button>

4th: if your going to return more rows as a json data you need to set your dataType to json

 dataType: "json",

PHP :

 <?php
    include("../db/conn.php");
    if(!empty($_POST['search'])){
    $sql = "select * from product_info where prod_name like '%?%'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s',$_POST['search']);
    $res=$stmt->execute();
    if(!$res){ echo $stmt->error; }
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    //here you can use while loop to fetch all the record and do the json_encode() and return all the rows.
    echo $row['prod_name'];

    }else{

      echo "Product search string should not empty ";
    }

    ?>

Ajax :

$(document).ready(function(){

     $(document).on('click','#button_submit',function(){

        var search = $('#search').val();

        $.ajax({
          url: 'get_users.php',
          dataType: "text",
          type: 'POST',
          data: {search: search},
          success: function(output){
            alert(output);
          }
        });
          return false;
      });
  });
JYoThI
  • 11,977
  • 1
  • 11
  • 26
0

in one of your buttons call the callAjax() function when its clicked since you do not have type submit button :

<button type="button" class="btn btn-success" onclick="callAjax();"><i class="fa fa-check"></i><span>Go</button>

Then remove the ajax function inside the document ready function as it might be undefined in some browsers :

<script>

        var callAjax = (function(){

        var search = $('#search').val();

        $.ajax({
          url: 'get_users.php',
          dataType: "text",
          type: 'POST',
          data: {search: search},
          success: function(output){
            alert(output);
          }
        });

        });
    </script>

Then take care of the sql injections problems as specified above comments.

Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34