0

I have a php page where users type in a specific id number in a text field and click a "SEARCH" button. Upon clicking "SEARCH", a php script runs to connect to a MySQL Database table "xxx"and grab the row id that matches the id number entered by the user. The SELECT statement grabs the database values: "productionstage" and "floornotes" for the identified row.

What I need to do is take those results and display them back on my form page:

A select menu needs to dynamically display the option corresponding to the "productionstage" value for the row and then a textarea needs to display the value from "floornotes".

MY CODE:

HTML:

<form id="workorderMovement" name='workorderMovement_form' action="workordermovementGET.php" method="post">



<fieldset id="userid">

<span>Welcome <?php echo $user ?> </span>

</fieldset> 




<fieldset id="sgnum">

<fieldset id="fieldset" style="text-align: center;"> 
    <span>Please enter the SG Number</span>
</fieldset>

<input type="text" name="sgnumber" id="sgnumber"> &nbsp;&nbsp;&nbsp; <input type="button" name="searchButton" id="searchButton" value="SEARCH">

</fieldset> 


<br/>
<br/>



<fieldset id="stageSelectField">

  <fieldset id="fieldset" style="text-align: center;"> 
    <span>Please select the Stage Completed</span>
  </fieldset>

<select name="stageSelect" id="stageSelect">
    <option value="Please Select">Please Select</option>
    <option value="Film Done">Film Done</option>
    <option value="Staged Done">Staged Done</option>
    <option value="Cleanroom Done">Cleanroom Done</option>
    <option value="GB2 Done">GB2 Done</option>
    <option value="Bagging Done">Bagging Done</option>
    <option value="Inspection Done">Inspection Done</option>
    <option value="LC Done">LC Inspection Done</option>
    <option value="IGU Done">IGU Done</option>
</select>

</fieldset> 


<br/>
<br/>


<fieldset id="floorNotesField">

  <fieldset id="fieldset" style="text-align: center;"> 
    <span>Please enter any new work order notes</span>
  </fieldset>

  <textarea type="text" name="floorNotes" id="floorNotes" class="floorNotesText"></textarea>

</fieldset>


<br/>
<br/>
<br/>

</form> <!-- End Work Order Movement Form -->

<fieldset id="doneButtonField">

  <input type="button" name="doneButton" id="doneButton" value="DONE">

</fieldset> 

MY AJAX:

         j("#searchButton").click(function(){


            //send Workorder Movement Data values to php using ajax.

                var sgnumber = j('#sgnumber').val();
                j.ajax ({
                    method: 'POST',
                    url: "workordermovementGET.php",
                    data: {sgNumber: sgnumber},
                    dataType: 'json',
                    success: function( data ){
                        if(data.status){
                            j("select#stageSelect option").filter(function() {
                                return j(this).val() == data.productionstage; 
                                }).prop('selected', true);
                                j("textarea#floorNotes").val(data.floornotes);
                            }

                    }
                 });

        });

MY PHP:

include('inc.php');


//Get Table Options.
if (isset($_POST['sgNumber'])) {
    $sgNumber = $_POST['sgNumber'];

    //connect  to the database 
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if(mysqli_connect_errno() ) {
        printf('Could not connect: ' . mysqli_connect_error());
        exit();
    }

    $conn->select_db($dbname);

    if(! $conn->select_db($dbname) ) {
        echo 'Could not select database. '.'<BR>';
    }

    $sql= "SELECT productionstage, floornotes FROM invoices WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $sgNumber);
    $stmt->execute();
    $stmt->store_result();     

    if ($stmt->num_rows == 1) {
        $stmt->bind_result($productionstage, $floornotes);
        $stmt->fetch();

        echo json_encode(array('status' => true, 'productionstage' => $productionstage, 'floornotes' => $floornotes));
    } else {
        echo json_encode(array('status' => false));
    }


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//Free the result variable. 
 $result->free();


//Close the Database connection.
 $conn->close();


}//End If statement

?>

I need to know how to properly post part of my ajax result as a select option (the database value will match one of the predefined select options) and and take the rest of the results and display in the textarea. Also, if I can do this dynamically, that would be perfect.

Thank you!

rdimouro
  • 225
  • 1
  • 4
  • 17
  • You have a SQL injection vulnerability in your code! – Hut8 Dec 05 '16 at 15:31
  • Yes I am aware. I am concurrently researching how to avoid that... Any suggestions for known links/tutorials is greatly appreciated. Thank you! – rdimouro Dec 05 '16 at 15:34

2 Answers2

1

You need to make few changes in your code, such as:

  • You need to place the closing </form> tag beneath the DONE button, like this:

        ...
    
        <fieldset id="doneButtonField">
            <input type="button" name="doneButton" id="doneButton" value="DONE">
        </fieldset> 
    </form>
    

    Your question doesn't really explain how you're planning to use this DONE button but I'm sure you have something in mind regarding this. However, this answer revolves around SEARCH button and the associated jQuery/AJAX and PHP functionality.

  • Change your jQuery/AJAX script in the following way,

    $("#searchButton").click(function(){
        var sgnumber = $('#sgnumber').val();
        $.ajax ({
            method: 'POST',
            url: "workordermovementGET.php",
            data: {sgNumber: sgnumber},
            dataType: 'json',
            success: function( data ){
                if(data.status){
                    $("select#stageSelect option").filter(function() {
                        return $(this).val() == data.productionstage; 
                    }).prop('selected', true);
                    $("textarea#floorNotes").val(data.floornotes);
                }
            }
        });
    });
    

    It selects a particular productionstage from the dropdown list and populates the floornotes data based on the id value entered by the user in input text field.

  • And finally, process your AJAX request in the following way i.e. your PHP code should be like this:

    <?php
        include('inc.php');
    
        if (isset($_POST['sgNumber'])) {
            $sgNumber = $_POST['sgNumber'];
    
            //connect  to the database 
            $conn = new mysqli($servername, $username, $password, $dbname);
    
            // Check connection
            if(mysqli_connect_errno() ) {
                printf('Could not connect: ' . mysqli_connect_error());
                exit();
            }
    
            $conn->select_db($dbname);
    
            if(! $conn->select_db($dbname) ) {
                echo 'Could not select database. '.'<BR>';
            }
    
            $sql= "SELECT productionstage, floornotes FROM invoices WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('i', $sgNumber);
            $stmt->execute();
            $stmt->store_result();     
    
            if ($stmt->num_rows == 1) {
                $stmt->bind_result($productionstage, $floornotes);
                $stmt->fetch();
    
                echo json_encode(array('status' => true, 'productionstage' => $productionstage, 'floornotes' => $floornotes));
            } else {
                echo json_encode(array('status' => false));
            }
        }
    ?>
    

    It uses prepared statement, so you can be sure that it's fairly secure from SQL injection attacks. Furthermore, this is a good read on how you can prevent SQL injection in PHP?

Community
  • 1
  • 1
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • Thank you! This is helping a lot so far. However, I am still seeing that my select menu isn't changing with the results from ajax. My text area is working well though. My select menu for my test id should change to the drop down option "Film Done" as that's the data received from the DB. However, it never changes from the first option in the list. – rdimouro Dec 05 '16 at 16:38
  • @rdimouro Do `alert(data.productionstage);` inside the `success` callback function and see what value you're getting back from the server. – Rajdeep Paul Dec 05 '16 at 16:42
  • The alert returns "Film Done" as it should. I just can't seem to get the select menu to change to the same option. could it be a .prop() issue? – rdimouro Dec 05 '16 at 16:49
  • @rdimouro That's because you're looking for the *text* property, rather than the *value* property of the dropdown list. In the success callback function, change this line `return $(this).val() == data.productionstage;` to return `$(this).text() == data.productionstage;` – Rajdeep Paul Dec 05 '16 at 16:59
  • @rdimouro It's working fine on my end. Did you change anything in the jQuery code snippet? If you changed anything, then paste your jQuery code snippet in [pastebin.com](http://pastebin.com/index.php) and give me it's link here. Also, this retrieved *productionstage* value matches with the *value* or the *text* part of the dropdown list? – Rajdeep Paul Dec 05 '16 at 17:39
  • The one thing I just changed was to make sure the value portion of my select menu options match what should be in the DB so the value "Film Done" from the menu should now match the DB returned "Film Done". That way, productionstage can match either the value or the text. – rdimouro Dec 05 '16 at 18:08
  • @rdimouro Just to debug the issue further, do `alert($(this).val());` and see what you're getting. Also, change the jQuery snippet in the following way, [http://pastebin.com/PZQNmi02](http://pastebin.com/PZQNmi02) and see if it makes any difference. – Rajdeep Paul Dec 05 '16 at 18:26
  • @rdimouro Or may be trim the extra white spaces before comparing, [http://pastebin.com/P8vpi9Xi](http://pastebin.com/P8vpi9Xi). – Rajdeep Paul Dec 05 '16 at 18:33
  • I tried doing 'alert(j(this).val());' but no alert is showing for this line. Upon inspecting the page in chrome, I got the following error: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined at n.fn.init.val (../jquery_min.js:4:3614) at Object.success ('mypageurl'/work_order_movement.js:73:24) at j (../jquery_min.js:2:26860) at Object.fireWith [as resolveWith] (../jquery_min.js:2:27673) at x (/jquery_min.js:4:11120) at XMLHttpRequest. (../jquery_min.js:4:14767) NOTE: actual links removed for privacy. – rdimouro Dec 05 '16 at 18:39
  • also, doing trim() breaks the page. The error from the previous comment only occurs when I do the alert(j(this.val()). – rdimouro Dec 05 '16 at 18:52
  • @rdimouro Try this jQuery code snippet, [http://pastebin.com/Rd3a7T5M](http://pastebin.com/Rd3a7T5M), it uses `.each()` instead of `.filter()` Also, you can Google search the error to debug this issue further, [Uncaught TypeError: Cannot read property 'toLowerCase'](https://www.google.com/search?q=Uncaught+TypeError%3A+Cannot+read+property+%27toLowerCase%27&oq=Uncaught+TypeError%3A+Cannot+read+property+%27toLowerCase%27&aqs=chrome..69i57j69i60l2.403j0j7&sourceid=chrome&ie=UTF-8) – Rajdeep Paul Dec 05 '16 at 19:12
  • Unfortunately, .each() isn't working either. Just the same results. However, I did 'alert("#stageSelect").val()); in the same code after 'j("textarea#floorNotes").val(date.floornotes);' and the alert showed "Cleanroom Done" (which I changed the DB value for other reasons so the select menu should show 'Cleanroom Done'). So the select menu value is getting set correctly. Its just not changing the visible option? – rdimouro Dec 05 '16 at 19:26
  • Furthermore, I am seeing that when clicking on the drop down list, the correct option is highlighted, its just not automatically display in the text box on its own... – rdimouro Dec 05 '16 at 19:32
  • @rdimouro Not sure what's causing the issue, but for me it's working fine. See this jsfiddle, [https://jsfiddle.net/wh9q40v0/](https://jsfiddle.net/wh9q40v0/). By the way, in which textbox you want to display this *correct* option? – Rajdeep Paul Dec 05 '16 at 20:13
  • So the text box that is the select menu box. You would click on the box to get the drop down list. I'm seeing that the correct value will be highlighted when I click on the list, but the actual text in the box doesn't change after I click search and get the results back. How do I get the text to change too? your jsfiddle link was able to do it automatically but mine just stays on "Please Select" but has "Cleanroom Done" highlighted in the drop down menu. – rdimouro Dec 05 '16 at 20:25
0

You need to make an array with your database results and echo json_encode($your_array);. That will return your data as a JSON object to the Ajax success function. Then you can parse that object for the data for the select and the data for the textarea. I can't remember how you change the selected option with JS, but I know it is usually the first or second link on a Google search/

CptMisery
  • 612
  • 4
  • 15